Skip to main content

tabnas_markdown/
lib.rs

1/* Copyright (c) 2021-2026 Richard Rodger, MIT License */
2
3// The engine's error carries a code, position, hint and a formatted
4// report, so it is large by design and `Result<_, TabnasError>` trips
5// clippy's `result_large_err`. The engine allows the lint at its own
6// crate root for the same reason; boxing here instead would make `parse`
7// return a different shape from `Tabnas::parse` and from the TypeScript
8// and Go ports, which is a worse trade than the lint.
9#![allow(clippy::result_large_err)]
10
11//! `tabnas-markdown`: a CommonMark 0.31.2 parser with the GFM extensions
12//! (tables, strikethrough, task list items, autolink literals and the
13//! disallowed-raw-HTML filter), built as a plugin on the bare `tabnas`
14//! engine.
15//!
16//! ```
17//! let doc = tabnas_markdown::parse("# Hello *world*")?;
18//! assert_eq!(doc.to_json()["children"][0]["type"], "heading");
19//! # Ok::<(), tabnas_markdown::MarkdownError>(())
20//! ```
21//!
22//! This file is only the plugin wiring and the public surface. The parser
23//! itself is engine-free and lives in [`commonmark`] and the modules it
24//! pulls in ([`block`], [`inline`], [`html`], [`common`], [`node`]), so it
25//! can be exercised, and the conformance suite run, without the engine.
26//! Nothing under `commonmark.rs` may import it.
27//!
28//! The parse result is a native CommonMark node tree ([`Tree`]); [`ast`]
29//! projects it to the map-based JSON AST this package has always returned
30//! (as a [`tabnas::Value`]), and [`html`] renders it for [`to_html`].
31//!
32//! Nesting is bounded, at [`MAX_CONTAINER_NESTING`] container blocks and
33//! [`MAX_INLINE_NESTING`] inline containers, which the canonical
34//! TypeScript does not do: a `Value` is dropped and converted
35//! recursively, so an unbounded AST could overflow the caller's stack.
36//! See those constants and `DIVERGENCE.md` at the repository root.
37//!
38//! This is a port of `ts/src/*.ts`, which is canonical, and a sibling of
39//! the Go port in `go/`. See AGENTS.md.
40
41use std::sync::{Arc, OnceLock};
42
43use tabnas::{AltSpec, Plugin, PluginError, Value, TIN_ZZ};
44
45/// The README's Rust examples run as doctests, so a stale one fails the
46/// gate rather than misleading the reader. Its `toml` and `bash` fences
47/// are skipped; rustdoc runs only the `rust` ones.
48#[cfg(doctest)]
49#[doc = include_str!("../README.md")]
50mod readme_examples {}
51
52pub mod ast;
53pub mod block;
54pub mod common;
55pub mod commonmark;
56pub mod engine_block;
57pub mod engine_inline;
58mod entities;
59pub mod html;
60pub mod inline;
61pub mod node;
62pub mod options;
63
64pub use ast::to_ast;
65pub use block::MAX_CONTAINER_NESTING;
66pub use html::{render_html, render_html_with, DISALLOWED_TAGS};
67pub use inline::MAX_INLINE_NESTING;
68pub use node::{
69    Align, ListData, ListType, MdNode, NodeId, NodeType, SourcePos, TableAlign, Tree, WalkEvent,
70    Walker,
71};
72pub use options::{Options, RefDef, RefMap, DEFAULT_OPTIONS};
73pub use tabnas::Tabnas;
74
75/// This crate's version. It MUST equal `ts/package.json` "version": the
76/// release orchestrator rewrites both, and `tests/version_test.rs` fails
77/// the build if they drift. Mirrors `VERSION` in `ts/src/markdown.ts` and
78/// `const VERSION` in `go/markdown.go`.
79pub const VERSION: &str = "0.7.13";
80
81/// The error a failed engine parse produces, re-exported so callers need
82/// not depend on the engine crate directly. The parser itself defines an
83/// output for every input; this is the engine's own failure shape (a
84/// budget exceeded, a panic in another plugin's callback).
85pub use tabnas::TabnasError as MarkdownError;
86
87/// The plugin's name, as `Tabnas::use_plugin` records it.
88pub const PLUGIN_NAME: &str = "Markdown";
89
90// ---------------------------------------------------------------------------
91// Public parse API (engine-free)
92
93/// Parse Markdown to the mdast-adjacent JSON AST.
94pub fn parse_document(src: &str, options: &Options) -> Value {
95    to_ast(&commonmark::parse(src, *options), options)
96}
97
98/// Parse a single run of inline Markdown, returning the inline children of
99/// the resulting paragraph. Empty when the text does not start with a
100/// paragraph.
101pub fn parse_inline(text: &str, options: &Options) -> Vec<Value> {
102    let doc = parse_document(text, options);
103    let Some(Value::Array(children)) = engine_block::value_get(&doc, "children") else {
104        return Vec::new();
105    };
106    let Some(first) = children.first() else {
107        return Vec::new();
108    };
109    if !matches!(engine_block::value_get(first, "type"), Some(Value::String(t)) if t == "paragraph")
110    {
111        return Vec::new();
112    }
113    match engine_block::value_get(first, "children") {
114        Some(Value::Array(inlines)) => inlines.as_ref().clone(),
115        _ => Vec::new(),
116    }
117}
118
119/// Parse Markdown and render it to CommonMark-conformant HTML.
120pub fn to_html(src: &str, options: &Options) -> String {
121    render_html_with(&commonmark::parse(src, *options), *options)
122}
123
124/// Parse Markdown to the native CommonMark node tree.
125pub fn parse_tree(src: &str, options: &Options) -> Tree {
126    commonmark::parse(src, *options)
127}
128
129// ---------------------------------------------------------------------------
130// Plugin wiring
131
132/// Install the parser on a tabnas engine instance.
133///
134/// The engine parse IS the parse: the `mdLine` custom matcher
135/// (`engine_block.rs`) lexes one `#LB` token per physical line,
136/// `parse.prepare` seeds a fresh block parser for the parse, the `line`
137/// rule feeds each matched line to the shared `incorporate_line`, and the
138/// `markdown` rule's close action on `#ZZ` finalizes, runs the shared
139/// inline phase, and projects the public AST into the rule's node. No
140/// recognition or block decision happens here: the engine owns
141/// tokenization, dispatch and state carriage; the algorithm stays in the
142/// engine-free core (the anti-drift rule, dx-report ยง42), which is what
143/// keeps this path byte-identical to [`parse_document`] (asserted by the
144/// differential gate and the engine-path conformance harness).
145///
146/// Use this to add Markdown to an engine you are configuring yourself;
147/// [`make`] and [`make_with`] are the short way to a ready one.
148pub fn markdown(tn: &mut Tabnas, options: &Options) -> Result<(), PluginError> {
149    let opts = *options;
150
151    let lb = tn.token(engine_block::LINE_TOKEN);
152
153    // Every built-in matcher is off: deliberate configuration, not
154    // defense. Markdown's block alphabet is *lines*, so the one registered
155    // matcher is the complete lexical description of this phase: mdLine,
156    // at an order ahead of every built-in, consuming each physical line
157    // whole. (The built-ins would misread the syntax anyway: backtick code
158    // spans lex as unterminated strings, `# heading` as a comment,
159    // `1. list` as a number.)
160    tn.set_options(|o| {
161        o.fixed.lex = false;
162        o.space.lex = false;
163        o.line.lex = false;
164        o.text.lex = false;
165        o.string.lex = false;
166        o.comment.lex = false;
167        o.number.lex = false;
168        o.value.lex = false;
169        o.lex.empty_result = empty_document();
170        o.rule.start = "markdown".to_string();
171        // The GFM dialect is subtracted, not branched around: without the
172        // option, the tagged alts below simply do not exist in this
173        // instance's grammar.
174        o.rule.exclude = if opts.gfm {
175            String::new()
176        } else {
177            "gfm".to_string()
178        };
179    })?;
180
181    tn.options.lex.matchers.insert(
182        engine_block::MD_LINE_MATCHER.to_string(),
183        tabnas::LexMatcher {
184            name: engine_block::MD_LINE_MATCHER.to_string(),
185            order: engine_block::MD_LINE_ORDER,
186            matcher: None,
187            imperative: Some(Arc::new(engine_block::make_md_line_matcher(lb))),
188            factory: None,
189        },
190    );
191    tn.options.parse.named_prepare.insert(
192        engine_block::MD_PREPARE.to_string(),
193        tabnas::ParsePrepare::Context(Arc::new(engine_block::make_md_prepare(opts))),
194    );
195
196    // The inline phase's own engine instance, built once per install and
197    // shared by every parse (see `engine_inline.rs` for why that is sound
198    // here and not in Go).
199    let inline_tn = Arc::new(engine_inline::make_inline_tn(&opts));
200    let run_inlines = move |tree: Tree, refmap: RefMap| {
201        engine_inline::parse_inlines_engine(&inline_tn, tree, refmap, &opts)
202    };
203
204    tn.define_rule("markdown", |rs| {
205        rs.clear();
206        rs.add_open(AltSpec {
207            p: Some("line".to_string()),
208            ..Default::default()
209        });
210        let mut finish = AltSpec {
211            s: vec![vec![TIN_ZZ]],
212            ..Default::default()
213        };
214        finish.add_action(engine_block::make_md_finish_action(opts, run_inlines));
215        rs.add_close(finish);
216        rs.add_close(AltSpec::default());
217    });
218
219    // One `#LB` consumed per iteration, tail-recursing via `r` until only
220    // `#ZZ` remains; the empty alts are the fall-through that hands
221    // control back to markdown's close.
222    //
223    // The first alt is the GFM extension seam: tagged `g: "gfm"`, gated on
224    // the token's tblArm bit, arming the shared table probe for this line.
225    // It is injected exactly the way a downstream dialect would extend
226    // this grammar (an alt ahead of the base one, subtractable by its
227    // group tag) and gfm:false removes it via `rule.exclude` above, so the
228    // base dialect is the grammar minus the tagged alts, visibly.
229    tn.define_rule("line", |rs| {
230        rs.clear();
231        let mut gfm = AltSpec {
232            s: vec![vec![lb]],
233            c_fn: Some(Arc::new(engine_block::md_line_gfm_condition)),
234            r: Some("line".to_string()),
235            g: "gfm".to_string(),
236            ..Default::default()
237        };
238        gfm.add_action(engine_block::md_line_gfm_action);
239        rs.add_open(gfm);
240        let mut base = AltSpec {
241            s: vec![vec![lb]],
242            r: Some("line".to_string()),
243            ..Default::default()
244        };
245        base.add_action(engine_block::md_line_action);
246        rs.add_open(base);
247        rs.add_open(AltSpec::default());
248        rs.add_close(AltSpec::default());
249    });
250
251    Ok(())
252}
253
254/// The AST of an empty document, which is what the engine answers for an
255/// empty source before any rule runs.
256fn empty_document() -> Value {
257    let mut map = indexmap::IndexMap::with_capacity(2);
258    map.insert("type".to_string(), Value::String("document".to_string()));
259    map.insert("children".to_string(), Value::array(Vec::new()));
260    Value::object(map)
261}
262
263/// The plugin descriptor, for [`Tabnas::use_plugin`]. Options are read
264/// from the plugin option bag (`gfm`, `breaks`), so a caller who has one
265/// already can hand it over; [`markdown`] is the typed way in.
266pub fn plugin() -> Plugin {
267    Plugin::new(PLUGIN_NAME, |tn, options| {
268        markdown(tn, &Options::resolve(options))
269    })
270    .with_defaults(DEFAULT_OPTIONS.to_value())
271}
272
273/// Build a tabnas engine with the Markdown plugin installed under the
274/// given options. The Rust counterpart of `new Tabnas().use(Markdown,
275/// opts)`.
276///
277/// Reuse the result: building the instance dominates a parse of a small
278/// document. This goes through [`plugin`] rather than calling
279/// [`markdown`] directly, so the instance records the plugin and its
280/// resolved options.
281///
282/// ```
283/// let parser = tabnas_markdown::make_with(&tabnas_markdown::Options::COMMONMARK);
284/// let doc = parser.parse("~~not struck~~")?;
285/// assert_eq!(
286///     doc.to_json()["children"][0]["children"][0]["value"],
287///     "~~not struck~~"
288/// );
289/// # Ok::<(), tabnas_markdown::MarkdownError>(())
290/// ```
291pub fn make_with(options: &Options) -> Tabnas {
292    let mut tn = Tabnas::new();
293    tn.use_plugin(plugin(), Some(options.to_value()))
294        .expect("the Markdown plugin installs on a bare engine");
295    tn
296}
297
298/// [`make_with`] under the package defaults (`gfm` on, `breaks` off).
299///
300/// ```
301/// let parser = tabnas_markdown::make();
302/// let doc = parser.parse("- [x] done")?;
303/// assert_eq!(doc.to_json()["children"][0]["children"][0]["checked"], true);
304/// # Ok::<(), tabnas_markdown::MarkdownError>(())
305/// ```
306pub fn make() -> Tabnas {
307    make_with(&DEFAULT_OPTIONS)
308}
309
310/// Parse a Markdown source with the shared default engine instance.
311///
312/// The instance is built once, on first use, and reused after that:
313/// [`Tabnas::parse`] takes `&self` and builds a fresh parse context per
314/// call, and `Tabnas` is `Send + Sync`, so concurrent callers share one
315/// installed grammar instead of each rebuilding it. Use [`make`] or
316/// [`make_with`] when the parser needs configuring: that returns a fresh
317/// instance and leaves this one alone.
318///
319/// ```
320/// let doc = tabnas_markdown::parse("Hello *world*")?;
321/// let para = &doc.to_json()["children"][0];
322/// assert_eq!(para["type"], "paragraph");
323/// assert_eq!(para["children"][1]["type"], "emphasis");
324/// # Ok::<(), tabnas_markdown::MarkdownError>(())
325/// ```
326pub fn parse(src: &str) -> Result<Value, MarkdownError> {
327    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
328    DEFAULT.get_or_init(make).parse(src)
329}
330
331/// Parse through the engine and also hand back the native tree the parse
332/// built: the `keepTree` handshake the engine-path conformance harness
333/// uses, so it can render with the same [`render_html`] the engine-free
334/// path uses and isolate the parse from the rendering.
335///
336/// The tree is `None` for an empty source, which the engine answers with
337/// `lex.empty_result` before any rule runs. The instance must have the
338/// plugin installed; one without it parses, but hands back no tree.
339pub fn parse_keep_tree(tn: &Tabnas, src: &str) -> Result<(Value, Option<Tree>), MarkdownError> {
340    // Clear anything an aborted earlier parse on this thread may have
341    // left, so a stale tree is never mistaken for this parse's.
342    let _ = engine_block::take_kept_tree();
343
344    let mut md = indexmap::IndexMap::with_capacity(1);
345    md.insert("keepTree".to_string(), Value::Bool(true));
346    let mut meta = indexmap::IndexMap::with_capacity(1);
347    meta.insert("md".to_string(), Value::object(md));
348
349    let ast = tn.parse_with_meta(src, Value::object(meta))?;
350    Ok((ast, engine_block::take_kept_tree()))
351}
352
353/// One optional alchemy translation source and its explicit entry point.
354#[derive(Clone, Copy, Debug, Eq, PartialEq)]
355pub struct TranslationPart {
356    /// The definition a host calls after linking the source.
357    pub entry: &'static str,
358    /// The source text, or `None` for an entry supplied by alchemy.
359    pub source: Option<&'static str>,
360}
361
362/// The package-local structural translation interface.
363#[derive(Clone, Copy, Debug, Eq, PartialEq)]
364pub struct TranslationParts {
365    /// The complete `tabnas.plugin.json` text.
366    pub manifest: &'static str,
367    /// An optional lift from the grammar's events to its first read shape.
368    pub lift: Option<TranslationPart>,
369    /// An optional embedding of a plain tree in the format's schema, with its reverse.
370    pub embed: Option<TranslationPart>,
371    /// An optional render from the write shape to text.
372    pub render: Option<TranslationPart>,
373}
374
375const TRANSLATION: TranslationParts = TranslationParts {
376    manifest: include_str!("../translate/manifest.json"),
377    lift: Some(TranslationPart {
378        entry: "markdown-lift",
379        source: Some(include_str!("../translate/lift.alc")),
380    }),
381    embed: None,
382    render: Some(TranslationPart {
383        entry: "markdown-render",
384        source: Some(include_str!("../translate/render.alc")),
385    }),
386};
387
388/// Return Markdown's immutable translation parts.
389#[must_use]
390pub const fn translate() -> Option<TranslationParts> {
391    Some(TRANSLATION)
392}
393
394/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
395/// it. Its `translate` object is what a host that translates reads: the
396/// shapes Markdown is read as (`records`, through the lift, then `tree`)
397/// and written from (`records`), the root whose elements are the records
398/// (`array`), the tree its events carry (`markdown-ast`, the
399/// mdast-adjacent AST the reader builds, whose root is a `document`, not
400/// mdast's `root`, and not a plain tree either), the
401/// files that hold the lift and the render, and the sentences that say
402/// what a translation does not keep. The crate embeds its own copy,
403/// `translate/manifest.json`, since a packaged crate holds nothing outside
404/// `rs/`; `tests/translate_test.rs` holds the copy to the file.
405///
406/// ```
407/// assert!(tabnas_markdown::manifest_text().contains("\"translate\""));
408/// ```
409pub fn manifest_text() -> &'static str {
410    TRANSLATION.manifest
411}
412
413/// Markdown's lift, `alchemy/lift.alc`, the file the manifest's
414/// `translate.lift` names: a library of alchemy definitions, with no
415/// `export`, whose entry point `markdown-lift` reads a document's events
416/// as a table's records, the first row's cells as the column labels and
417/// every later row as a record: the first table's, or the empty table's
418/// when the document holds none. A host links it with its own program.
419/// The crate embeds its own copy, `translate/lift.alc`, held to the file
420/// as the manifest's is.
421///
422/// ```
423/// assert!(tabnas_markdown::lift_text().contains("def markdown-lift [input]"));
424/// ```
425pub fn lift_text() -> &'static str {
426    match TRANSLATION.lift {
427        Some(part) => part.source.unwrap_or_default(),
428        None => "",
429    }
430}
431
432/// Markdown's render, `alchemy/render.alc`, the file the manifest's
433/// `translate.render` names: a library of alchemy definitions, with no
434/// `export`, whose entry point `markdown-render` writes a table's records
435/// as one GFM pipe table, and a table of no columns as the empty
436/// document. A host links it with its own program. The crate embeds its
437/// own copy, `translate/render.alc`, held to the file as the manifest's
438/// is.
439///
440/// ```
441/// assert!(tabnas_markdown::render_text().contains("def markdown-render [input]"));
442/// ```
443pub fn render_text() -> &'static str {
444    match TRANSLATION.render {
445        Some(part) => part.source.unwrap_or_default(),
446        None => "",
447    }
448}