tabnas_railroad/lib.rs
1/* Copyright (c) 2026 Richard Rodger and other contributors, MIT License */
2
3//! Railroad (syntax) diagram renderer for the `tabnas` parser: the Rust
4//! port of `@tabnas/railroad`.
5//!
6//! It does not parse anything itself. It introspects a live [`Tabnas`]
7//! instance that already has a grammar installed and emits three
8//! artifacts from that grammar:
9//!
10//! - a declarative, JSON-serializable [`GrammarModel`] (the interchange
11//! format: one node tree per rule),
12//! - a vertical-flow SVG (one anchored, linked track per rule), and
13//! - a vertical ASCII diagram (Unicode box drawing, or plain `| - +`).
14//!
15//! ```
16//! use tabnas_railroad::{extract_grammar, model_to_ascii, AsciiOptions, ExtractOptions};
17//!
18//! let parser = tabnas_json::make();
19//! let model = extract_grammar(&parser, &ExtractOptions::default());
20//! assert_eq!(model.start, "val");
21//! assert_eq!(model.rules.len(), 5);
22//!
23//! let ascii = model_to_ascii(&model, &AsciiOptions::default());
24//! assert!(ascii.starts_with("val:\n"));
25//! ```
26//!
27//! The extraction and rendering logic lives in `extract`, `svg` and
28//! `ascii`; this file is the plugin wiring plus the bare re-exports for
29//! instance-free use. Because the model is pure data, the SVG and ASCII
30//! are fully reproducible from the JSON alone: no renderer reads
31//! anything off the live instance.
32
33pub mod ascii;
34#[cfg(feature = "cli")]
35pub mod cli;
36pub mod extract;
37pub mod model;
38pub mod svg;
39
40use tabnas::{Plugin, PluginError, Tabnas};
41
42pub use ascii::{model_to_ascii, render_node_ascii, AsciiOptions};
43pub use extract::{extract_grammar, ExtractOptions};
44pub use model::{
45 choice, comment, diagram, node_equal, non_terminal, one_or_more, optional, sequence, skip,
46 terminal, to_text, zero_or_more, GrammarModel, LegendEntry, RailroadError, RailroadNode,
47};
48pub use svg::{model_to_svg, render_node_svg, LinkFor, SvgOptions};
49
50/// The README's Rust examples run as doctests, so a stale one fails the
51/// gate rather than misleading the reader. Its `text`, `toml` and `bash`
52/// fences are skipped; rustdoc runs only the `rust` ones.
53#[cfg(doctest)]
54#[doc = include_str!("../README.md")]
55mod readme_examples {}
56
57/// This crate's version. It MUST equal `ts/package.json` "version": the
58/// release orchestrator rewrites both, and `tests/version_test.rs` fails
59/// the build if they drift. Mirrors `VERSION` in `ts/src/railroad.ts`
60/// and `const VERSION` in `go/model.go`.
61pub const VERSION: &str = "0.3.12";
62
63/// The key under which the plugin marks the instance (retrieve the mark
64/// with `parser.decoration::<RailroadDecoration>(DECORATION_NAME)`).
65pub const DECORATION_NAME: &str = "railroad";
66
67/// The mark the plugin leaves on an instance. TypeScript decorates the
68/// instance with a callable API bound to it; a Rust decoration cannot
69/// hold a reference to the instance it sits on, so the mark is a unit
70/// and [`of`] binds the API to any instance on demand.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct RailroadDecoration;
73
74/// The plugin, for `parser.use_plugin(tabnas_railroad::plugin(), None)`.
75///
76/// Installing it marks the instance (see [`installed`]). Everything else
77/// is lazy: [`of`] re-reads the instance's current grammar on every
78/// call, so plugin install order does not matter.
79pub fn plugin() -> Plugin {
80 Plugin::new("railroad", |parser: &mut Tabnas, _options| {
81 parser.decorate(DECORATION_NAME, RailroadDecoration);
82 Ok(())
83 })
84}
85
86/// Install the plugin on `parser`.
87///
88/// ```
89/// let mut parser = tabnas_json::make();
90/// tabnas_railroad::railroad(&mut parser)?;
91/// assert!(tabnas_railroad::installed(&parser));
92/// # Ok::<(), tabnas::PluginError>(())
93/// ```
94pub fn railroad(parser: &mut Tabnas) -> Result<(), PluginError> {
95 parser.use_plugin(plugin(), None).map(|_| ())
96}
97
98/// Whether [`plugin`] has been installed on `parser` (or on an instance
99/// it was derived from).
100pub fn installed(parser: &Tabnas) -> bool {
101 parser
102 .decoration::<RailroadDecoration>(DECORATION_NAME)
103 .is_some()
104}
105
106/// The API bound to one instance: the Rust analog of the TypeScript
107/// `tn.railroad` callable, and of the Go `RailroadApi`.
108#[derive(Clone, Copy)]
109pub struct RailroadApi<'a> {
110 parser: &'a Tabnas,
111}
112
113impl std::fmt::Debug for RailroadApi<'_> {
114 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
115 formatter
116 .debug_struct("RailroadApi")
117 .field("start", &self.parser.options.rule.start)
118 .field("rules", &self.parser.rule_names())
119 .finish()
120 }
121}
122
123/// Bind the API to `parser`, whether or not the plugin is installed.
124pub fn of(parser: &Tabnas) -> RailroadApi<'_> {
125 RailroadApi { parser }
126}
127
128impl<'a> RailroadApi<'a> {
129 /// The instance this API reads.
130 pub fn parser(&self) -> &'a Tabnas {
131 self.parser
132 }
133
134 /// Introspect this instance's grammar and return its model.
135 pub fn extract(&self, opts: &ExtractOptions) -> GrammarModel {
136 extract_grammar(self.parser, opts)
137 }
138
139 /// The model with default extraction options (the TypeScript
140 /// `tn.railroad()` / `tn.railroad.toJson()`).
141 pub fn to_json(&self) -> GrammarModel {
142 self.extract(&ExtractOptions::default())
143 }
144
145 /// Extract this instance's grammar and render it to SVG.
146 pub fn to_svg(&self) -> String {
147 model_to_svg(&self.to_json())
148 }
149
150 /// Extract this instance's grammar and render it to ASCII.
151 pub fn to_ascii(&self, opts: &AsciiOptions) -> String {
152 model_to_ascii(&self.to_json(), opts)
153 }
154
155 /// Render a single node to a standalone SVG.
156 pub fn render_node(&self, node: &RailroadNode, opts: &SvgOptions) -> String {
157 render_node_svg(node, opts)
158 }
159
160 /// Render a single node to an ASCII block.
161 pub fn render_node_ascii(&self, node: &RailroadNode, opts: &AsciiOptions) -> String {
162 render_node_ascii(node, opts)
163 }
164
165 /// Render a single node to compact EBNF text.
166 pub fn render_node_text(&self, node: &RailroadNode) -> String {
167 to_text(node)
168 }
169}