tabnas-markdown 0.7.7

A CommonMark 0.31.2 parser with GFM extensions for the tabnas parsing engine, into a JSON AST or HTML.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
/* Copyright (c) 2021-2026 Richard Rodger, MIT License */

// The engine's error carries a code, position, hint and a formatted
// report, so it is large by design and `Result<_, TabnasError>` trips
// clippy's `result_large_err`. The engine allows the lint at its own
// crate root for the same reason; boxing here instead would make `parse`
// return a different shape from `Tabnas::parse` and from the TypeScript
// and Go ports, which is a worse trade than the lint.
#![allow(clippy::result_large_err)]

//! `tabnas-markdown`: a CommonMark 0.31.2 parser with the GFM extensions
//! (tables, strikethrough, task list items, autolink literals and the
//! disallowed-raw-HTML filter), built as a plugin on the bare `tabnas`
//! engine.
//!
//! ```
//! let doc = tabnas_markdown::parse("# Hello *world*")?;
//! assert_eq!(doc.to_json()["children"][0]["type"], "heading");
//! # Ok::<(), tabnas_markdown::MarkdownError>(())
//! ```
//!
//! This file is only the plugin wiring and the public surface. The parser
//! itself is engine-free and lives in [`commonmark`] and the modules it
//! pulls in ([`block`], [`inline`], [`html`], [`common`], [`node`]), so it
//! can be exercised, and the conformance suite run, without the engine.
//! Nothing under `commonmark.rs` may import it.
//!
//! The parse result is a native CommonMark node tree ([`Tree`]); [`ast`]
//! projects it to the map-based JSON AST this package has always returned
//! (as a [`tabnas::Value`]), and [`html`] renders it for [`to_html`].
//!
//! Nesting is bounded, at [`MAX_CONTAINER_NESTING`] container blocks and
//! [`MAX_INLINE_NESTING`] inline containers, which the canonical
//! TypeScript does not do: a `Value` is dropped and converted
//! recursively, so an unbounded AST could overflow the caller's stack.
//! See those constants and `DIVERGENCE.md` at the repository root.
//!
//! This is a port of `ts/src/*.ts`, which is canonical, and a sibling of
//! the Go port in `go/`. See AGENTS.md.

use std::sync::{Arc, OnceLock};

use tabnas::{AltSpec, Plugin, PluginError, Value, TIN_ZZ};

/// The README's Rust examples run as doctests, so a stale one fails the
/// gate rather than misleading the reader. Its `toml` and `bash` fences
/// are skipped; rustdoc runs only the `rust` ones.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
mod readme_examples {}

pub mod ast;
pub mod block;
pub mod common;
pub mod commonmark;
pub mod engine_block;
pub mod engine_inline;
mod entities;
pub mod html;
pub mod inline;
pub mod node;
pub mod options;

pub use ast::to_ast;
pub use block::MAX_CONTAINER_NESTING;
pub use html::{render_html, render_html_with, DISALLOWED_TAGS};
pub use inline::MAX_INLINE_NESTING;
pub use node::{
    Align, ListData, ListType, MdNode, NodeId, NodeType, SourcePos, TableAlign, Tree, WalkEvent,
    Walker,
};
pub use options::{Options, RefDef, RefMap, DEFAULT_OPTIONS};
pub use tabnas::Tabnas;

/// This crate's version. It MUST equal `ts/package.json` "version": the
/// release orchestrator rewrites both, and `tests/version_test.rs` fails
/// the build if they drift. Mirrors `VERSION` in `ts/src/markdown.ts` and
/// `const VERSION` in `go/markdown.go`.
pub const VERSION: &str = "0.7.7";

/// The error a failed engine parse produces, re-exported so callers need
/// not depend on the engine crate directly. The parser itself defines an
/// output for every input; this is the engine's own failure shape (a
/// budget exceeded, a panic in another plugin's callback).
pub use tabnas::TabnasError as MarkdownError;

/// The plugin's name, as `Tabnas::use_plugin` records it.
pub const PLUGIN_NAME: &str = "Markdown";

// ---------------------------------------------------------------------------
// Public parse API (engine-free)

/// Parse Markdown to the mdast-adjacent JSON AST.
pub fn parse_document(src: &str, options: &Options) -> Value {
    to_ast(&commonmark::parse(src, *options), options)
}

/// Parse a single run of inline Markdown, returning the inline children of
/// the resulting paragraph. Empty when the text does not start with a
/// paragraph.
pub fn parse_inline(text: &str, options: &Options) -> Vec<Value> {
    let doc = parse_document(text, options);
    let Some(Value::Array(children)) = engine_block::value_get(&doc, "children") else {
        return Vec::new();
    };
    let Some(first) = children.first() else {
        return Vec::new();
    };
    if !matches!(engine_block::value_get(first, "type"), Some(Value::String(t)) if t == "paragraph")
    {
        return Vec::new();
    }
    match engine_block::value_get(first, "children") {
        Some(Value::Array(inlines)) => inlines.as_ref().clone(),
        _ => Vec::new(),
    }
}

/// Parse Markdown and render it to CommonMark-conformant HTML.
pub fn to_html(src: &str, options: &Options) -> String {
    render_html_with(&commonmark::parse(src, *options), *options)
}

/// Parse Markdown to the native CommonMark node tree.
pub fn parse_tree(src: &str, options: &Options) -> Tree {
    commonmark::parse(src, *options)
}

// ---------------------------------------------------------------------------
// Plugin wiring

/// Install the parser on a tabnas engine instance.
///
/// The engine parse IS the parse: the `mdLine` custom matcher
/// (`engine_block.rs`) lexes one `#LB` token per physical line,
/// `parse.prepare` seeds a fresh block parser for the parse, the `line`
/// rule feeds each matched line to the shared `incorporate_line`, and the
/// `markdown` rule's close action on `#ZZ` finalizes, runs the shared
/// inline phase, and projects the public AST into the rule's node. No
/// recognition or block decision happens here: the engine owns
/// tokenization, dispatch and state carriage; the algorithm stays in the
/// engine-free core (the anti-drift rule, dx-report §42), which is what
/// keeps this path byte-identical to [`parse_document`] (asserted by the
/// differential gate and the engine-path conformance harness).
///
/// Use this to add Markdown to an engine you are configuring yourself;
/// [`make`] and [`make_with`] are the short way to a ready one.
pub fn markdown(tn: &mut Tabnas, options: &Options) -> Result<(), PluginError> {
    let opts = *options;

    let lb = tn.token(engine_block::LINE_TOKEN);

    // Every built-in matcher is off: deliberate configuration, not
    // defense. Markdown's block alphabet is *lines*, so the one registered
    // matcher is the complete lexical description of this phase: mdLine,
    // at an order ahead of every built-in, consuming each physical line
    // whole. (The built-ins would misread the syntax anyway: backtick code
    // spans lex as unterminated strings, `# heading` as a comment,
    // `1. list` as a number.)
    tn.set_options(|o| {
        o.fixed.lex = false;
        o.space.lex = false;
        o.line.lex = false;
        o.text.lex = false;
        o.string.lex = false;
        o.comment.lex = false;
        o.number.lex = false;
        o.value.lex = false;
        o.lex.empty_result = empty_document();
        o.rule.start = "markdown".to_string();
        // The GFM dialect is subtracted, not branched around: without the
        // option, the tagged alts below simply do not exist in this
        // instance's grammar.
        o.rule.exclude = if opts.gfm {
            String::new()
        } else {
            "gfm".to_string()
        };
    })?;

    tn.options.lex.matchers.insert(
        engine_block::MD_LINE_MATCHER.to_string(),
        tabnas::LexMatcher {
            name: engine_block::MD_LINE_MATCHER.to_string(),
            order: engine_block::MD_LINE_ORDER,
            matcher: None,
            imperative: Some(Arc::new(engine_block::make_md_line_matcher(lb))),
            factory: None,
        },
    );
    tn.options.parse.named_prepare.insert(
        engine_block::MD_PREPARE.to_string(),
        tabnas::ParsePrepare::Context(Arc::new(engine_block::make_md_prepare(opts))),
    );

    // The inline phase's own engine instance, built once per install and
    // shared by every parse (see `engine_inline.rs` for why that is sound
    // here and not in Go).
    let inline_tn = Arc::new(engine_inline::make_inline_tn(&opts));
    let run_inlines = move |tree: Tree, refmap: RefMap| {
        engine_inline::parse_inlines_engine(&inline_tn, tree, refmap, &opts)
    };

    tn.define_rule("markdown", |rs| {
        rs.clear();
        rs.add_open(AltSpec {
            p: Some("line".to_string()),
            ..Default::default()
        });
        let mut finish = AltSpec {
            s: vec![vec![TIN_ZZ]],
            ..Default::default()
        };
        finish.add_action(engine_block::make_md_finish_action(opts, run_inlines));
        rs.add_close(finish);
        rs.add_close(AltSpec::default());
    });

    // One `#LB` consumed per iteration, tail-recursing via `r` until only
    // `#ZZ` remains; the empty alts are the fall-through that hands
    // control back to markdown's close.
    //
    // The first alt is the GFM extension seam: tagged `g: "gfm"`, gated on
    // the token's tblArm bit, arming the shared table probe for this line.
    // It is injected exactly the way a downstream dialect would extend
    // this grammar (an alt ahead of the base one, subtractable by its
    // group tag) and gfm:false removes it via `rule.exclude` above, so the
    // base dialect is the grammar minus the tagged alts, visibly.
    tn.define_rule("line", |rs| {
        rs.clear();
        let mut gfm = AltSpec {
            s: vec![vec![lb]],
            c_fn: Some(Arc::new(engine_block::md_line_gfm_condition)),
            r: Some("line".to_string()),
            g: "gfm".to_string(),
            ..Default::default()
        };
        gfm.add_action(engine_block::md_line_gfm_action);
        rs.add_open(gfm);
        let mut base = AltSpec {
            s: vec![vec![lb]],
            r: Some("line".to_string()),
            ..Default::default()
        };
        base.add_action(engine_block::md_line_action);
        rs.add_open(base);
        rs.add_open(AltSpec::default());
        rs.add_close(AltSpec::default());
    });

    Ok(())
}

/// The AST of an empty document, which is what the engine answers for an
/// empty source before any rule runs.
fn empty_document() -> Value {
    let mut map = indexmap::IndexMap::with_capacity(2);
    map.insert("type".to_string(), Value::String("document".to_string()));
    map.insert("children".to_string(), Value::array(Vec::new()));
    Value::object(map)
}

/// The plugin descriptor, for [`Tabnas::use_plugin`]. Options are read
/// from the plugin option bag (`gfm`, `breaks`), so a caller who has one
/// already can hand it over; [`markdown`] is the typed way in.
pub fn plugin() -> Plugin {
    Plugin::new(PLUGIN_NAME, |tn, options| {
        markdown(tn, &Options::resolve(options))
    })
    .with_defaults(DEFAULT_OPTIONS.to_value())
}

/// Build a tabnas engine with the Markdown plugin installed under the
/// given options. The Rust counterpart of `new Tabnas().use(Markdown,
/// opts)`.
///
/// Reuse the result: building the instance dominates a parse of a small
/// document. This goes through [`plugin`] rather than calling
/// [`markdown`] directly, so the instance records the plugin and its
/// resolved options.
///
/// ```
/// let parser = tabnas_markdown::make_with(&tabnas_markdown::Options::COMMONMARK);
/// let doc = parser.parse("~~not struck~~")?;
/// assert_eq!(
///     doc.to_json()["children"][0]["children"][0]["value"],
///     "~~not struck~~"
/// );
/// # Ok::<(), tabnas_markdown::MarkdownError>(())
/// ```
pub fn make_with(options: &Options) -> Tabnas {
    let mut tn = Tabnas::new();
    tn.use_plugin(plugin(), Some(options.to_value()))
        .expect("the Markdown plugin installs on a bare engine");
    tn
}

/// [`make_with`] under the package defaults (`gfm` on, `breaks` off).
///
/// ```
/// let parser = tabnas_markdown::make();
/// let doc = parser.parse("- [x] done")?;
/// assert_eq!(doc.to_json()["children"][0]["children"][0]["checked"], true);
/// # Ok::<(), tabnas_markdown::MarkdownError>(())
/// ```
pub fn make() -> Tabnas {
    make_with(&DEFAULT_OPTIONS)
}

/// Parse a Markdown source with the shared default engine instance.
///
/// The instance is built once, on first use, and reused after that:
/// [`Tabnas::parse`] takes `&self` and builds a fresh parse context per
/// call, and `Tabnas` is `Send + Sync`, so concurrent callers share one
/// installed grammar instead of each rebuilding it. Use [`make`] or
/// [`make_with`] when the parser needs configuring: that returns a fresh
/// instance and leaves this one alone.
///
/// ```
/// let doc = tabnas_markdown::parse("Hello *world*")?;
/// let para = &doc.to_json()["children"][0];
/// assert_eq!(para["type"], "paragraph");
/// assert_eq!(para["children"][1]["type"], "emphasis");
/// # Ok::<(), tabnas_markdown::MarkdownError>(())
/// ```
pub fn parse(src: &str) -> Result<Value, MarkdownError> {
    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
    DEFAULT.get_or_init(make).parse(src)
}

/// Parse through the engine and also hand back the native tree the parse
/// built: the `keepTree` handshake the engine-path conformance harness
/// uses, so it can render with the same [`render_html`] the engine-free
/// path uses and isolate the parse from the rendering.
///
/// The tree is `None` for an empty source, which the engine answers with
/// `lex.empty_result` before any rule runs. The instance must have the
/// plugin installed; one without it parses, but hands back no tree.
pub fn parse_keep_tree(tn: &Tabnas, src: &str) -> Result<(Value, Option<Tree>), MarkdownError> {
    // Clear anything an aborted earlier parse on this thread may have
    // left, so a stale tree is never mistaken for this parse's.
    let _ = engine_block::take_kept_tree();

    let mut md = indexmap::IndexMap::with_capacity(1);
    md.insert("keepTree".to_string(), Value::Bool(true));
    let mut meta = indexmap::IndexMap::with_capacity(1);
    meta.insert("md".to_string(), Value::object(md));

    let ast = tn.parse_with_meta(src, Value::object(meta))?;
    Ok((ast, engine_block::take_kept_tree()))
}

/// One optional alchemy translation source and its explicit entry point.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationPart {
    /// The definition a host calls after linking the source.
    pub entry: &'static str,
    /// The source text, or `None` for an entry supplied by alchemy.
    pub source: Option<&'static str>,
}

/// The package-local structural translation interface.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TranslationParts {
    /// The complete `tabnas.plugin.json` text.
    pub manifest: &'static str,
    /// An optional lift from the grammar's events to its first read shape.
    pub lift: Option<TranslationPart>,
    /// An optional render from the write shape to text.
    pub render: Option<TranslationPart>,
}

const TRANSLATION: TranslationParts = TranslationParts {
    manifest: include_str!("../translate/manifest.json"),
    lift: Some(TranslationPart {
        entry: "markdown-lift",
        source: Some(include_str!("../translate/lift.alc")),
    }),
    render: Some(TranslationPart {
        entry: "markdown-render",
        source: Some(include_str!("../translate/render.alc")),
    }),
};

/// Return Markdown's immutable translation parts.
#[must_use]
pub const fn translate() -> Option<TranslationParts> {
    Some(TRANSLATION)
}

/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
/// it. Its `translate` object is what a host that translates reads: the
/// shapes Markdown is read as (`records`, through the lift, then `tree`)
/// and written from (`records`), the files that hold the lift and the
/// render, and the sentences that say what a translation does not keep.
/// The crate embeds its own copy, `translate/manifest.json`, since a
/// packaged crate holds nothing outside `rs/`; `tests/translate_test.rs`
/// holds the copy to the file.
///
/// ```
/// assert!(tabnas_markdown::manifest_text().contains("\"translate\""));
/// ```
pub fn manifest_text() -> &'static str {
    TRANSLATION.manifest
}

/// Markdown's lift, `alchemy/lift.alc`, the file the manifest's
/// `translate.lift` names: a library of alchemy definitions, with no
/// `export`, whose entry point `markdown-lift` reads a document's events
/// as a table's records, the first row's cells as the column labels and
/// every later row as a record. A host links it with its own program.
/// The crate embeds its own copy, `translate/lift.alc`, held to the file
/// as the manifest's is.
///
/// ```
/// assert!(tabnas_markdown::lift_text().contains("def markdown-lift [input]"));
/// ```
pub fn lift_text() -> &'static str {
    match TRANSLATION.lift {
        Some(part) => part.source.unwrap_or_default(),
        None => "",
    }
}

/// Markdown's render, `alchemy/render.alc`, the file the manifest's
/// `translate.render` names: a library of alchemy definitions, with no
/// `export`, whose entry point `markdown-render` writes a table's records
/// as one GFM pipe table. A host links it with its own program. The
/// crate embeds its own copy, `translate/render.alc`, held to the file as
/// the manifest's is.
///
/// ```
/// assert!(tabnas_markdown::render_text().contains("def markdown-render [input]"));
/// ```
pub fn render_text() -> &'static str {
    match TRANSLATION.render {
        Some(part) => part.source.unwrap_or_default(),
        None => "",
    }
}