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::collections::HashMap;
42use std::sync::{Arc, OnceLock};
43
44use tabnas::{AltSpec, Plugin, PluginError, Value, TIN_ZZ};
45
46/// The README's Rust examples run as doctests, so a stale one fails the
47/// gate rather than misleading the reader. Its `toml` and `bash` fences
48/// are skipped; rustdoc runs only the `rust` ones.
49#[cfg(doctest)]
50#[doc = include_str!("../README.md")]
51mod readme_examples {}
52
53pub mod ast;
54pub mod block;
55pub mod common;
56pub mod commonmark;
57pub mod engine_block;
58pub mod engine_inline;
59mod entities;
60pub mod html;
61pub mod inline;
62pub mod node;
63pub mod options;
64
65pub use ast::{resolve_references, to_ast};
66pub use block::MAX_CONTAINER_NESTING;
67pub use html::{render_html, render_html_with, DISALLOWED_TAGS};
68pub use inline::MAX_INLINE_NESTING;
69pub use node::{
70 Align, Definition, DefinitionSite, ListData, ListType, MdNode, NodeId, NodeType, ReferenceType,
71 SourcePos, TableAlign, Tree, WalkEvent, Walker,
72};
73pub use options::{Options, RefDef, RefMap, DEFAULT_OPTIONS};
74pub use tabnas::Tabnas;
75
76/// This crate's version. It MUST equal `ts/package.json` "version": the
77/// release orchestrator rewrites both, and `tests/version_test.rs` fails
78/// the build if they drift. Mirrors `VERSION` in `ts/src/markdown.ts` and
79/// `const VERSION` in `go/markdown.go`.
80pub const VERSION: &str = "0.7.15";
81
82/// The error a failed engine parse produces, re-exported so callers need
83/// not depend on the engine crate directly. The parser itself defines an
84/// output for every input; this is the engine's own failure shape (a
85/// budget exceeded, a panic in another plugin's callback).
86pub use tabnas::TabnasError as MarkdownError;
87
88/// The plugin's name, as `Tabnas::use_plugin` records it.
89pub const PLUGIN_NAME: &str = "Markdown";
90
91// ---------------------------------------------------------------------------
92// Public parse API (engine-free)
93
94/// Parse Markdown to the mdast-adjacent JSON AST. References stay
95/// unresolved, as mdast keeps them: a bracketed label is a
96/// `linkReference` or an `imageReference`, and each definition a
97/// `definition` node where it stands. [`resolve_references`] resolves them.
98pub fn parse_document(src: &str, options: &Options) -> Value {
99 to_ast(
100 &commonmark::parse_keeping_references(src, *options),
101 options,
102 )
103}
104
105/// Parse a single run of inline Markdown, returning the inline children of
106/// the resulting paragraph. Empty when the text does not start with a
107/// paragraph.
108pub fn parse_inline(text: &str, options: &Options) -> Vec<Value> {
109 let doc = parse_document(text, options);
110 let Some(Value::Array(children)) = engine_block::value_get(&doc, "children") else {
111 return Vec::new();
112 };
113 let Some(first) = children.first() else {
114 return Vec::new();
115 };
116 if !matches!(engine_block::value_get(first, "type"), Some(Value::String(t)) if t == "paragraph")
117 {
118 return Vec::new();
119 }
120 match engine_block::value_get(first, "children") {
121 Some(Value::Array(inlines)) => inlines.as_ref().clone(),
122 _ => Vec::new(),
123 }
124}
125
126/// Parse Markdown and render it to CommonMark-conformant HTML.
127pub fn to_html(src: &str, options: &Options) -> String {
128 render_html_with(&commonmark::parse(src, *options), *options)
129}
130
131/// Parse Markdown to the native CommonMark node tree.
132pub fn parse_tree(src: &str, options: &Options) -> Tree {
133 commonmark::parse(src, *options)
134}
135
136// ---------------------------------------------------------------------------
137// Plugin wiring
138
139/// Install the parser on a tabnas engine instance.
140///
141/// The engine parse IS the parse, and its rules open and close every
142/// block: the `mdBlock` matcher (`engine_block.rs`) cuts one `#LB` token
143/// per physical line through the lexer's window, runs the shared block
144/// algorithm over it, and hands out before it the tokens of the blocks
145/// that line closed and opened; each node of the AST is a rule that opens
146/// on its token and, for a container, closes on `#EN`; and the document's
147/// children, like every container's, are the `children` rule, a replace
148/// loop, so ten thousand blocks run at the depth one does. The block
149/// decisions are the shared engine-free core's (the anti-drift rule,
150/// dx-report ยง42), which is what keeps this path's AST identical to
151/// [`parse_document`]'s (asserted by the differential gate and the
152/// engine-path conformance harness).
153///
154/// Use this to add Markdown to an engine you are configuring yourself;
155/// [`make`] and [`make_with`] are the short way to a ready one.
156pub fn markdown(tn: &mut Tabnas, options: &Options) -> Result<(), PluginError> {
157 let opts = *options;
158
159 let mut tins: HashMap<&'static str, tabnas::Tin> = HashMap::new();
160 tins.insert(engine_block::LINE_TOKEN, tn.token(engine_block::LINE_TOKEN));
161 tins.insert(engine_block::END_TOKEN, tn.token(engine_block::END_TOKEN));
162 for n in engine_block::NODE_RULES {
163 tins.insert(n.token, tn.token(n.token));
164 }
165
166 // Every built-in matcher is off: deliberate configuration, not
167 // defense. Markdown's block alphabet is *lines*, so the one registered
168 // matcher is the complete lexical description of this phase: mdBlock,
169 // at an order ahead of every built-in, consuming each physical line
170 // whole. (The built-ins would misread the syntax anyway: backtick code
171 // spans lex as unterminated strings, `# heading` as a comment,
172 // `1. list` as a number.)
173 tn.set_options(|o| {
174 o.fixed.lex = false;
175 o.space.lex = false;
176 o.line.lex = false;
177 o.text.lex = false;
178 o.string.lex = false;
179 o.comment.lex = false;
180 o.number.lex = false;
181 o.value.lex = false;
182 o.lex.empty_result = empty_document();
183 o.rule.start = "markdown".to_string();
184 // The GFM dialect is subtracted, not branched around: without the
185 // option, the tagged alts below simply do not exist in this
186 // instance's grammar.
187 o.rule.exclude = if opts.gfm {
188 String::new()
189 } else {
190 "gfm".to_string()
191 };
192 })?;
193
194 // The inline phase's own engine instance, built once per install and
195 // shared by every parse (see `engine_inline.rs` for why that is sound
196 // here and not in Go).
197 let inline_tn = Arc::new(engine_inline::make_inline_tn(&opts));
198
199 tn.options.lex.matchers.insert(
200 engine_block::MD_BLOCK_MATCHER.to_string(),
201 tabnas::LexMatcher {
202 name: engine_block::MD_BLOCK_MATCHER.to_string(),
203 order: engine_block::MD_BLOCK_ORDER,
204 matcher: None,
205 imperative: Some(Arc::new(engine_block::make_md_block_matcher(
206 opts,
207 tins.clone(),
208 Arc::clone(&inline_tn),
209 ))),
210 factory: None,
211 },
212 );
213 tn.options.parse.named_prepare.insert(
214 engine_block::MD_PREPARE.to_string(),
215 tabnas::ParsePrepare::Context(Arc::new(engine_block::make_md_prepare(opts))),
216 );
217
218 let token = |name: &str| tins[name];
219 let slot: Vec<tabnas::Tin> = std::iter::once(token(engine_block::LINE_TOKEN))
220 .chain(engine_block::NODE_RULES.iter().map(|n| token(n.token)))
221 .collect();
222
223 // The document: its children, then the end of the source.
224 let finish = engine_block::make_md_finish(opts, Arc::clone(&inline_tn));
225 tn.define_rule("markdown", |rs| {
226 rs.clear();
227 let mut begin = AltSpec {
228 p: Some("children".to_string()),
229 ..Default::default()
230 };
231 begin.add_action(engine_block::md_begin);
232 rs.add_open(begin);
233 let mut end = AltSpec {
234 s: vec![vec![TIN_ZZ]],
235 ..Default::default()
236 };
237 end.add_action(finish);
238 rs.add_close(end);
239 });
240
241 // A container's children, one node or one line per iteration: a
242 // node's token pushes that node's rule, a line is consumed, and the
243 // loop goes on by replacement (`r`), never by a push chain, while the
244 // next token is either; anything else (`#EN`, `#ZZ`) ends it. The GFM
245 // nodes are the `gfm` group's alts, which `gfm: false` subtracts.
246 tn.define_rule("children", |rs| {
247 rs.clear();
248 for n in engine_block::NODE_RULES {
249 rs.add_open(AltSpec {
250 s: vec![vec![token(n.token)]],
251 b: 1,
252 p: Some(n.rule.to_string()),
253 g: if n.gfm {
254 "gfm".to_string()
255 } else {
256 String::new()
257 },
258 ..Default::default()
259 });
260 }
261 rs.add_open(AltSpec {
262 s: vec![vec![token(engine_block::LINE_TOKEN)]],
263 ..Default::default()
264 });
265 rs.add_open(AltSpec::default());
266 rs.add_close(AltSpec {
267 s: vec![slot.clone()],
268 b: 1,
269 r: Some("children".to_string()),
270 ..Default::default()
271 });
272 rs.add_close(AltSpec::default());
273 });
274
275 // A rule per node: a container opens on its token, pushes its
276 // children, and closes on `#EN`; a leaf opens on its token and closes
277 // at once.
278 for n in engine_block::NODE_RULES {
279 tn.define_rule(n.rule, |rs| {
280 rs.clear();
281 if n.container {
282 let mut open = AltSpec {
283 s: vec![vec![token(n.token)]],
284 p: Some("children".to_string()),
285 ..Default::default()
286 };
287 open.add_action(engine_block::md_open);
288 rs.add_open(open);
289 let mut close = AltSpec {
290 s: vec![vec![token(engine_block::END_TOKEN)]],
291 ..Default::default()
292 };
293 close.add_action(engine_block::md_close);
294 rs.add_close(close);
295 } else {
296 let mut open = AltSpec {
297 s: vec![vec![token(n.token)]],
298 ..Default::default()
299 };
300 open.add_action(engine_block::md_leaf);
301 rs.add_open(open);
302 rs.add_close(AltSpec::default());
303 }
304 });
305 }
306
307 Ok(())
308}
309
310/// The AST of an empty document, which is what the engine answers for an
311/// empty source before any rule runs.
312fn empty_document() -> Value {
313 let mut map = indexmap::IndexMap::with_capacity(2);
314 map.insert("type".to_string(), Value::String("document".to_string()));
315 map.insert("children".to_string(), Value::array(Vec::new()));
316 Value::object(map)
317}
318
319/// The plugin descriptor, for [`Tabnas::use_plugin`]. Options are read
320/// from the plugin option bag (`gfm`, `breaks`), so a caller who has one
321/// already can hand it over; [`markdown`] is the typed way in.
322pub fn plugin() -> Plugin {
323 Plugin::new(PLUGIN_NAME, |tn, options| {
324 markdown(tn, &Options::resolve(options))
325 })
326 .with_defaults(DEFAULT_OPTIONS.to_value())
327}
328
329/// Build a tabnas engine with the Markdown plugin installed under the
330/// given options. The Rust counterpart of `new Tabnas().use(Markdown,
331/// opts)`.
332///
333/// Reuse the result: building the instance dominates a parse of a small
334/// document. This goes through [`plugin`] rather than calling
335/// [`markdown`] directly, so the instance records the plugin and its
336/// resolved options.
337///
338/// ```
339/// let parser = tabnas_markdown::make_with(&tabnas_markdown::Options::COMMONMARK);
340/// let doc = parser.parse("~~not struck~~")?;
341/// assert_eq!(
342/// doc.to_json()["children"][0]["children"][0]["value"],
343/// "~~not struck~~"
344/// );
345/// # Ok::<(), tabnas_markdown::MarkdownError>(())
346/// ```
347pub fn make_with(options: &Options) -> Tabnas {
348 let mut tn = Tabnas::new();
349 tn.use_plugin(plugin(), Some(options.to_value()))
350 .expect("the Markdown plugin installs on a bare engine");
351 // The one matcher cuts a line through the lexer's window and fills it
352 // past the line's end, and nothing else reads the source, so a parse
353 // from a reader (`Tabnas::parse_reader`, admin ADR-30) holds the text
354 // of the lines it has not finished with, and not the whole text. The
355 // option is set here, on the parser this package makes, not in the
356 // plugin.
357 tn.set_options(|o| o.lex.window = true)
358 .expect("the window option installs on the parser this package makes");
359 tn
360}
361
362/// [`make_with`] under the package defaults (`gfm` on, `breaks` off).
363///
364/// ```
365/// let parser = tabnas_markdown::make();
366/// let doc = parser.parse("- [x] done")?;
367/// assert_eq!(doc.to_json()["children"][0]["children"][0]["checked"], true);
368/// # Ok::<(), tabnas_markdown::MarkdownError>(())
369/// ```
370pub fn make() -> Tabnas {
371 make_with(&DEFAULT_OPTIONS)
372}
373
374/// Parse a Markdown source with the shared default engine instance.
375///
376/// The instance is built once, on first use, and reused after that:
377/// [`Tabnas::parse`] takes `&self` and builds a fresh parse context per
378/// call, and `Tabnas` is `Send + Sync`, so concurrent callers share one
379/// installed grammar instead of each rebuilding it. Use [`make`] or
380/// [`make_with`] when the parser needs configuring: that returns a fresh
381/// instance and leaves this one alone.
382///
383/// ```
384/// let doc = tabnas_markdown::parse("Hello *world*")?;
385/// let para = &doc.to_json()["children"][0];
386/// assert_eq!(para["type"], "paragraph");
387/// assert_eq!(para["children"][1]["type"], "emphasis");
388/// # Ok::<(), tabnas_markdown::MarkdownError>(())
389/// ```
390pub fn parse(src: &str) -> Result<Value, MarkdownError> {
391 static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
392 DEFAULT.get_or_init(make).parse(src)
393}
394
395/// Parse through the engine and also hand back the native tree the parse
396/// built: the `keepTree` handshake the engine-path conformance harness
397/// uses, so it can render with the same [`render_html`] the engine-free
398/// path uses and isolate the parse from the rendering.
399///
400/// The tree is `None` for an empty source, which the engine answers with
401/// `lex.empty_result` before any rule runs. The instance must have the
402/// plugin installed; one without it parses, but hands back no tree.
403pub fn parse_keep_tree(tn: &Tabnas, src: &str) -> Result<(Value, Option<Tree>), MarkdownError> {
404 // Clear anything an aborted earlier parse on this thread may have
405 // left, so a stale tree is never mistaken for this parse's.
406 let _ = engine_block::take_kept_tree();
407
408 let mut md = indexmap::IndexMap::with_capacity(1);
409 md.insert("keepTree".to_string(), Value::Bool(true));
410 let mut meta = indexmap::IndexMap::with_capacity(1);
411 meta.insert("md".to_string(), Value::object(md));
412
413 let ast = tn.parse_with_meta(src, Value::object(meta))?;
414 Ok((ast, engine_block::take_kept_tree()))
415}
416
417/// One optional alchemy translation source and its explicit entry point.
418#[derive(Clone, Copy, Debug, Eq, PartialEq)]
419pub struct TranslationPart {
420 /// The definition a host calls after linking the source.
421 pub entry: &'static str,
422 /// The source text, or `None` for an entry supplied by alchemy.
423 pub source: Option<&'static str>,
424}
425
426/// The package-local structural translation interface.
427#[derive(Clone, Copy, Debug, Eq, PartialEq)]
428pub struct TranslationParts {
429 /// The complete `tabnas.plugin.json` text.
430 pub manifest: &'static str,
431 /// An optional lift from the grammar's events to its first read shape.
432 pub lift: Option<TranslationPart>,
433 /// An optional embedding of a plain tree in the format's schema, with its reverse.
434 pub embed: Option<TranslationPart>,
435 /// An optional render from the write shape to text.
436 pub render: Option<TranslationPart>,
437 /// An optional transducer: a document's JSON events from its parser's
438 /// rule passes, for a host that reads parser events.
439 pub transduce: Option<TranslationPart>,
440}
441
442const TRANSLATION: TranslationParts = TranslationParts {
443 manifest: include_str!("../translate/manifest.json"),
444 lift: Some(TranslationPart {
445 entry: "markdown-lift",
446 source: Some(include_str!("../translate/lift.alc")),
447 }),
448 embed: None,
449 render: Some(TranslationPart {
450 entry: "markdown-render",
451 source: Some(include_str!("../translate/render.alc")),
452 }),
453 transduce: Some(TranslationPart {
454 entry: "markdown-transduce",
455 source: Some(include_str!("../translate/transduce.alc")),
456 }),
457};
458
459/// Return Markdown's immutable translation parts.
460#[must_use]
461pub const fn translate() -> Option<TranslationParts> {
462 Some(TRANSLATION)
463}
464
465/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
466/// it. Its `translate` object is what a host that translates reads: the
467/// shapes Markdown is read as (`records`, through the lift, then `tree`)
468/// and written from (`records`), the root whose elements are the records
469/// (`array`), the tree its events carry (`markdown-ast`, the
470/// mdast-adjacent AST the reader builds, whose root is a `document`, not
471/// mdast's `root`, and not a plain tree either), the
472/// files that hold the lift and the render, and the sentences that say
473/// what a translation does not keep. The crate embeds its own copy,
474/// `translate/manifest.json`, since a packaged crate holds nothing outside
475/// `rs/`; `tests/translate_test.rs` holds the copy to the file.
476///
477/// ```
478/// assert!(tabnas_markdown::manifest_text().contains("\"translate\""));
479/// ```
480pub fn manifest_text() -> &'static str {
481 TRANSLATION.manifest
482}
483
484/// Markdown's lift, `alchemy/lift.alc`, the file the manifest's
485/// `translate.lift` names: a library of alchemy definitions, with no
486/// `export`, whose entry point `markdown-lift` reads a document's events
487/// as a table's records, the first row's cells as the column labels and
488/// every later row as a record: the first table's, or the empty table's
489/// when the document holds none. A host links it with its own program.
490/// The crate embeds its own copy, `translate/lift.alc`, held to the file
491/// as the manifest's is.
492///
493/// ```
494/// assert!(tabnas_markdown::lift_text().contains("def markdown-lift [input]"));
495/// ```
496pub fn lift_text() -> &'static str {
497 match TRANSLATION.lift {
498 Some(part) => part.source.unwrap_or_default(),
499 None => "",
500 }
501}
502
503/// Markdown's transducer part, `alchemy/transduce.alc`, the file the
504/// manifest's `translate.transduce` names: a library of alchemy
505/// definitions, with no `export`, whose entry point `markdown-transduce`
506/// writes a document's JSON events from the grammar's rule passes, a block
507/// at a time, as the walk of the parser's value writes them. A host that
508/// reads parser events links it with its own program. The crate embeds its
509/// own copy, `translate/transduce.alc`, held to the file as the
510/// manifest's is.
511///
512/// ```
513/// assert!(tabnas_markdown::transduce_text().contains("def markdown-transduce [input]"));
514/// ```
515pub fn transduce_text() -> &'static str {
516 match TRANSLATION.transduce {
517 Some(part) => part.source.unwrap_or_default(),
518 None => "",
519 }
520}
521
522/// Markdown's render, `alchemy/render.alc`, the file the manifest's
523/// `translate.render` names: a library of alchemy definitions, with no
524/// `export`, whose entry point `markdown-render` writes a table's records
525/// as one GFM pipe table, and a table of no columns as the empty
526/// document. A host links it with its own program. The crate embeds its
527/// own copy, `translate/render.alc`, held to the file as the manifest's
528/// is.
529///
530/// ```
531/// assert!(tabnas_markdown::render_text().contains("def markdown-render [input]"));
532/// ```
533pub fn render_text() -> &'static str {
534 match TRANSLATION.render {
535 Some(part) => part.source.unwrap_or_default(),
536 None => "",
537 }
538}