Skip to main content

tabnas_proto/
lib.rs

1// Copyright (c) 2026 Richard Rodger and other contributors, 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`. This crate boxes it inside `ProtoError`
6// for that reason; the allow covers the engine's own `Result` where it
7// surfaces here.
8#![allow(clippy::result_large_err)]
9
10//! Parse Protocol Buffers `.proto` IDL into FileDescriptorProto-shaped
11//! values.
12//!
13//! proto2, proto3 and editions 2023 and 2024, with the version detected
14//! from the file's `syntax` or `edition` declaration. The parser is an
15//! [ABNF](https://github.com/tabnas/abnf) grammar driving the
16//! [`tabnas`](https://github.com/tabnas/parser) engine rather than a
17//! hand-written parser: `proto-grammar/*.abnf` at the repository root is
18//! the single source of truth, embedded into every runtime by
19//! `ts/embed-grammar.js`. `tabnas-abnf` compiles it at build time into
20//! `proto-grammar.json`, which this crate embeds and installs, so the
21//! crate itself depends on no ABNF compiler.
22//!
23//! ```
24//! fn main() -> Result<(), Box<dyn std::error::Error>> {
25//!     let file = tabnas_proto::parse("syntax = \"proto3\";\nmessage M { int32 a = 1; }", None)?;
26//!     assert_eq!(file.syntax.as_deref(), Some("proto3"));
27//!     assert_eq!(file.message_type[0].name, "M");
28//!     assert_eq!(file.message_type[0].field[0].number, 1.0);
29//!     Ok(())
30//! }
31//! ```
32//!
33//! The same descriptor also comes as a tree, through [`parse_value`],
34//! [`parse_value_with`] or [`to_descriptor_value`]: the plain value the
35//! canonical `parse` returns, with every member named and ordered as its
36//! object has them, for a host that walks the value rather than reading
37//! the struct. [`descriptor_value`] gives a descriptor alone the same
38//! shape, the members a statement places in a documented order.
39//!
40//! TypeScript is canonical: `ts/src` defines behaviour, and the shared
41//! fixtures in `test/spec/*.tsv` are the parity contract across
42//! TypeScript, Go and Rust. Where this port cannot match the canonical
43//! value, `DIVERGENCE.md` at the repository root records it.
44//!
45//! A parsed `.proto` file is DATA, never instructions. Schema files
46//! arrive from outside the system, and every string in a descriptor,
47//! `import` paths and `type_name`s included, is untrusted text. See the
48//! repository `AGENTS.md`.
49
50mod aggregate;
51mod ast;
52mod build_descriptor;
53mod descriptor;
54mod detect_version;
55mod error;
56mod grammar;
57mod jsnum;
58mod node;
59mod order;
60mod read;
61mod tree;
62
63/// The README's Rust examples run as doctests, so a stale one fails the
64/// gate rather than misleading the reader. Its `toml` and `bash` fences
65/// are skipped; rustdoc runs only the `rust` ones.
66#[cfg(doctest)]
67#[doc = include_str!("../README.md")]
68mod readme_examples {}
69
70use std::sync::OnceLock;
71
72use indexmap::IndexMap;
73use serde::Deserialize;
74use tabnas::{
75    GrammarSpec, Options as EngineOptions, Plugin, PluginError, RewindOptions, Tabnas, Value,
76};
77
78pub use build_descriptor::{build_file, MAX_NESTING_DEPTH};
79pub use descriptor::{
80    scalar_type, DescriptorProto, DescriptorRange, EnumDescriptorProto, EnumValueDescriptorProto,
81    FieldDescriptorProto, FieldLabel, FieldType, FileDescriptorProto, MethodDescriptorProto,
82    OneofDescriptorProto, OptionValue, Options, ServiceDescriptorProto, SymbolVisibility,
83    MAX_ENUM_NUMBER, MAX_FIELD_NUMBER_END, MAX_MESSAGE_SET_END, SCALAR_TYPES,
84};
85pub use detect_version::{
86    declared_version, declared_version_src, edition_enum, is_edition, resolve_version, ProtoVersion,
87};
88pub use error::ProtoError;
89pub use grammar::GRAMMAR_TEXT;
90pub use node::{child, child_rules, children, gaps, gaps_before, kw, nrule, nsrc};
91pub use tree::descriptor_value;
92
93/// This crate's version. It MUST equal `ts/package.json` "version": the
94/// release orchestrator rewrites both, and `tests/version_test.rs` fails
95/// the build if they drift. Mirrors `VERSION` in `ts/src/proto.ts` and
96/// `const VERSION` in `go/proto.go`.
97pub const VERSION: &str = "0.7.1";
98
99/// The plugin's name on an instance, and the key its option bag hangs
100/// under.
101pub const PLUGIN_NAME: &str = "Proto";
102
103/// The compiled grammar: `proto-grammar.json`, the engine's serialized
104/// rule set, which `tabnas-abnf` compiles from [`GRAMMAR_TEXT`] at build
105/// time (`tests/grammar_spec_test.rs` writes it, and fails when it is
106/// stale). Generated: never edit it.
107const GRAMMAR_SPEC: &str = include_str!("../proto-grammar.json");
108
109/// The engine's retained rewind history: its default, 64 consumed tokens,
110/// which the canonical `new Tabnas()` keeps.
111///
112/// The compiled grammar has no probe, the one builtin that rewinds, so no
113/// parse rewinds, and the one reader of the history is the action that
114/// records an aggregate's text, which reads the last token consumed. Every
115/// document of the fixtures and the corpus parses alike at 64 and at 8,192,
116/// the bound this crate kept through 0.7.0 (`tests/history_test.rs`); a
117/// longer history only holds a window's text back to its oldest token.
118pub const REWIND_HISTORY: usize = 64;
119
120/// How a `.proto` document is read.
121///
122/// Mirrors the canonical `ProtoOptions`. The defaults auto-detect the
123/// version from the file's declaration and refuse an explicit version
124/// that disagrees with it.
125#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
126#[serde(default)]
127pub struct ProtoOptions {
128    /// An explicit protobuf version. `None` auto-detects from the file's
129    /// `syntax` or `edition` declaration.
130    pub version: Option<ProtoVersion>,
131    /// When true (the default), a version that disagrees with the file's
132    /// declaration is an error; when false the declaration wins.
133    pub reconcile: bool,
134}
135
136impl Default for ProtoOptions {
137    fn default() -> Self {
138        ProtoOptions {
139            version: None,
140            reconcile: true,
141        }
142    }
143}
144
145/// Install the union proto grammar on an engine instance, so it can parse
146/// `.proto` source into a `{rule, src, kids}` CST.
147///
148/// Use [`to_descriptor`] to turn that CST into a [`FileDescriptorProto`].
149/// The Rust spelling of the canonical `tn.use(Proto)`.
150///
151/// The parser refuses a document nesting past [`MAX_NESTING_DEPTH`] as it
152/// reads it: the brace that opens the level past the cap fails the parse,
153/// at that brace, with the code `proto_too_deep`, so no tree deeper than
154/// the cap is built, from a text or from a reader.
155///
156/// ```
157/// fn main() -> Result<(), Box<dyn std::error::Error>> {
158///     let mut parser = tabnas_proto::engine();
159///     tabnas_proto::proto(&mut parser)?;
160///     let source = "syntax = \"proto3\";";
161///     tabnas_proto::preflight(source)?;
162///     let cst = parser.parse(source)?;
163///     let file = tabnas_proto::to_descriptor(&cst, None)?;
164///     assert_eq!(file.syntax.as_deref(), Some("proto3"));
165///     Ok(())
166/// }
167/// ```
168pub fn proto(parser: &mut Tabnas) -> Result<(), ProtoError> {
169    // Guard against re-invocation on the same instance: the grammar is
170    // stateless, but loading and installing it twice is wasted work.
171    // The engine's own rule list answers the question without inventing
172    // a decoration key.
173    if parser.rule_names().iter().any(|name| "proto" == name) {
174        return Ok(());
175    }
176    // The union grammar, compiled at build time with the options this
177    // function used to pass at every install. `word_keywords` is REQUIRED:
178    // it makes literal keywords match as whole words, so `option` does not
179    // grab the `option` prefix of `optional`. Without it the grammar
180    // mis-tokenises. `token_classes` compiles `ident` (an identifier or any
181    // keyword) to one engine token set, so a lookahead position peeks it as
182    // one token rather than one alternate per keyword. The CST builders are
183    // the engine's own `@node$` / `@capture$` / `@bubble$` builtins, so the
184    // document is pure data and installs with no compiler.
185    let spec = GrammarSpec::from_json(GRAMMAR_SPEC)
186        .map_err(|error| ProtoError::Grammar(format!("proto: {error}")))?;
187    parser
188        .grammar(&spec)
189        .map_err(|error| ProtoError::Grammar(format!("proto: {error}")))?;
190    // An aggregate value (`option (f) = { a: 1 };`) is recorded as the text
191    // between its braces, which the CST's `src` does not keep: the lexer
192    // drops whitespace and comments. This action reads it from the source
193    // while the brace tokens are to hand; see `aggregate.rs`.
194    parser.define_rule("constant", |spec| {
195        spec.add_ac(aggregate::record_aggregate);
196    });
197    // The nesting cap, counted as the lexer gives the parser its tokens,
198    // and in a parse from a reader an aggregate's text: see `read.rs`.
199    parser
200        .set_options(|options| {
201            options
202                .error
203                .insert(read::TOO_DEEP.to_string(), read::too_deep_message());
204            options
205                .hint
206                .insert(read::TOO_DEEP.to_string(), read::too_deep_hint());
207        })
208        .map_err(|error| ProtoError::Grammar(format!("proto: {error}")))?;
209    parser.subscribe_lex(read::read_token);
210    Ok(())
211}
212
213/// The plugin form of [`proto`], for [`Tabnas::use_plugin`].
214///
215/// Installed this way the grammar is re-applied to derived instances, as
216/// every native plugin is.
217pub fn plugin() -> Plugin {
218    let mut defaults = IndexMap::new();
219    defaults.insert("version".to_string(), Value::Null);
220    defaults.insert("reconcile".to_string(), Value::Bool(true));
221    Plugin::new(PLUGIN_NAME, |parser, _options| {
222        proto(parser).map_err(|error| PluginError(error.to_string()))
223    })
224    .with_defaults(Value::object(defaults))
225}
226
227/// A bare engine configured the way this plugin needs it, with no grammar
228/// installed yet.
229///
230/// The canonical `new Tabnas()`, with the engine's default
231/// [`REWIND_HISTORY`].
232pub fn engine() -> Tabnas {
233    Tabnas::with_options(EngineOptions {
234        rewind: RewindOptions {
235            history: Some(REWIND_HISTORY),
236        },
237        ..EngineOptions::default()
238    })
239}
240
241/// The parser for a tree: [`engine`] with this plugin installed, the
242/// counterpart of `new Tabnas().use(Proto)` and the Go `Proto(j)`. Its
243/// value is the `{rule, src, kids}` CST that [`to_tree`] and
244/// [`to_descriptor`] walk, as [`parse_with`], [`parse_value_with`] and
245/// [`parse_tree_with`] take it. A CST holds the whole document: for a
246/// stream, take [`make_streaming`].
247///
248/// The two parsers, this and [`make_streaming`]'s, each refuse a document
249/// nesting past [`MAX_NESTING_DEPTH`] as they read it, with the code
250/// `proto_too_deep` at the brace past the cap, and declare `lex.window`, so
251/// that [`Tabnas::parse_reader`] reads a document a window at a time, never
252/// whole. Both make the same rule passes, token for token, and fail the
253/// same documents at the same place. Their values differ, so neither
254/// stands in for the other. This one keeps an aggregate option value's
255/// text from the tokens between its braces in a parse from a reader, since
256/// a window never holds the whole source.
257///
258/// Installing the grammar dominates a parse by more than an order of
259/// magnitude, so it is installed once per process, and each call returns
260/// a clone of that parser. A clone is a parser of its own: it prepares
261/// its own state, and a subscriber added to it, or an option changed on
262/// it, reaches no other parser.
263///
264/// ```
265/// fn main() -> Result<(), Box<dyn std::error::Error>> {
266///     let parser = tabnas_proto::make();
267///     let file = tabnas_proto::parse_with(&parser, "message M {}", None)?;
268///     // No declaration and no option: protoc's default is proto2.
269///     assert_eq!(file.syntax.as_deref(), Some("proto2"));
270///     Ok(())
271/// }
272/// ```
273pub fn make() -> Tabnas {
274    shared().clone()
275}
276
277/// The parser a host streams a `.proto` document through: its rule passes,
278/// which the transducer part (`alchemy/transduce.alc`) reads a declaration
279/// at a time, are [`make`]'s, and it builds no tree. Its grammar is the
280/// compiled one without the CST's builders, so a parse holds no
281/// declaration it has closed, nor any of their text, and its value is not
282/// the CST: [`Tabnas::parse`] returns a null, which no walk takes. For a
283/// tree, take [`make`].
284///
285/// Like [`make`], it refuses a document nesting past [`MAX_NESTING_DEPTH`]
286/// as it reads it, declares `lex.window`, and returns a clone of a parser
287/// installed once per process, so a host that needs a parser per document
288/// pays the install once. It keeps the engine's rule history at three
289/// predecessors, [`tabnas::DEFAULT_RULE_HISTORY`], which the TypeScript
290/// and Go parsers set themselves, their engines keeping every rule by
291/// default. The bound is safe because this grammar has no action, so
292/// nothing reads back through the links it cuts, as
293/// `tests/streaming_test.rs` holds: its passes are [`make`]'s over every
294/// document.
295///
296/// ```
297/// fn main() -> Result<(), Box<dyn std::error::Error>> {
298///     let parser = tabnas_proto::make_streaming();
299///     let value = parser.parse("syntax = \"proto3\";\nmessage M { int32 a = 1; }")?;
300///     assert_eq!(value, tabnas::Value::Null);
301///     Ok(())
302/// }
303/// ```
304pub fn make_streaming() -> Tabnas {
305    shared_streaming().clone()
306}
307
308/// The compiled grammar's tree builders, the engine's builtins that build
309/// the `{rule, src, kids}` CST, each with the member of an alternate's `k`
310/// that configures it, if any.
311const TREE_BUILDERS: [(&str, Option<&str>); 3] = [
312    ("@node$", Some("node$")),
313    ("@capture$", Some("capture$")),
314    ("@bubble$", None),
315];
316
317/// The compiled grammar without its tree builders, which the parser
318/// [`make_streaming`] builds installs: the same rules, alternates, tokens
319/// and counters, so the same rule passes, and no node built. A builder is
320/// an alternate's action, which runs after the alternate has matched, and
321/// the grammar's conditions read counters, never a node, so taking the
322/// builders away changes what a parse builds and nothing of how it goes.
323/// Port of `withoutTree` in `ts/src/proto.ts`.
324fn streaming_grammar() -> Result<GrammarSpec, ProtoError> {
325    let mut document: serde_json::Value = serde_json::from_str(GRAMMAR_SPEC)
326        .map_err(|error| ProtoError::Grammar(format!("proto: {error}")))?;
327    if let Some(serde_json::Value::Object(rules)) = document.get_mut("rule") {
328        for rule in rules.values_mut() {
329            for state in ["open", "close"] {
330                let Some(serde_json::Value::Array(alternates)) = rule.get_mut(state) else {
331                    continue;
332                };
333                for alternate in alternates.iter_mut() {
334                    let Some(alternate) = alternate.as_object_mut() else {
335                        continue;
336                    };
337                    let builder = alternate.get("a").and_then(serde_json::Value::as_str);
338                    let Some((_, config)) = TREE_BUILDERS
339                        .iter()
340                        .find(|(name, _)| Some(*name) == builder)
341                    else {
342                        continue;
343                    };
344                    alternate.shift_remove("a");
345                    if let Some(config) = config {
346                        let emptied = match alternate.get_mut("k") {
347                            Some(serde_json::Value::Object(k)) => {
348                                k.shift_remove(*config);
349                                k.is_empty()
350                            }
351                            _ => false,
352                        };
353                        if emptied {
354                            alternate.shift_remove("k");
355                        }
356                    }
357                }
358            }
359        }
360    }
361    GrammarSpec::from_value(document)
362        .map_err(|error| ProtoError::Grammar(format!("proto: {error}")))
363}
364
365/// [`engine`] with the grammar without its tree builders installed, built
366/// anew: the parser [`shared_streaming`] holds, which [`make_streaming`]
367/// clones.
368fn build_streaming() -> Tabnas {
369    let mut parser = engine();
370    let spec = streaming_grammar().expect("the embedded proto grammar is fixed and valid");
371    parser
372        .grammar(&spec)
373        .expect("the embedded proto grammar installs");
374    parser
375        .set_options(|options| {
376            options
377                .error
378                .insert(read::TOO_DEEP.to_string(), read::too_deep_message());
379            options
380                .hint
381                .insert(read::TOO_DEEP.to_string(), read::too_deep_hint());
382            options.lex.window = true;
383            options.rule.history = Some(tabnas::DEFAULT_RULE_HISTORY);
384        })
385        .expect("the streaming proto parser takes its options");
386    parser.subscribe_lex(read::read_nesting);
387    parser
388}
389
390/// The shared streaming parser, installed once, as [`shared`] is.
391fn shared_streaming() -> &'static Tabnas {
392    static STREAMING: OnceLock<Tabnas> = OnceLock::new();
393    STREAMING.get_or_init(build_streaming)
394}
395
396/// [`engine`] with this plugin installed, built anew: the parser
397/// [`shared`] holds, which [`make`] clones. It declares `lex.window`, so
398/// that a parse from a reader reads the source a window at a time; a
399/// parse of a whole text is unchanged by it.
400fn build() -> Tabnas {
401    let mut parser = engine();
402    proto(&mut parser).expect("the embedded proto grammar is fixed and valid");
403    parser
404        .set_options(|options| options.lex.window = true)
405        .expect("the proto parser takes the window");
406    parser
407}
408
409/// The shared default parser.
410///
411/// Installing the grammar dominates a parse by more than an order of
412/// magnitude, and the plugin keeps no per-parse state on the instance, so one instance
413/// serves every call to [`parse`]. Parsing builds a fresh context and
414/// only reads instance state, so it is safe for concurrent use.
415fn shared() -> &'static Tabnas {
416    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
417    DEFAULT.get_or_init(build)
418}
419
420/// Turn a parsed proto CST into a [`FileDescriptorProto`], resolving the
421/// version from the file's declaration and the supplied options.
422///
423/// The walk refuses a CST nesting past [`MAX_NESTING_DEPTH`]. A parser
424/// this crate builds never builds one: it refuses the document as it
425/// reads the brace past the cap. A CST from an engine with the grammar
426/// alone can be that deep, and by then the tree EXISTS, and a
427/// `tabnas::Value` that deep aborts the process when it drops, so such a
428/// caller runs [`preflight`] on the source first.
429pub fn to_descriptor(
430    cst: &Value,
431    options: Option<&ProtoOptions>,
432) -> Result<FileDescriptorProto, ProtoError> {
433    to_descriptor_ordered(cst, options).map(|(file, _)| file)
434}
435
436/// [`to_descriptor`], with the walk's record of the source's order
437/// (`order.rs`).
438fn to_descriptor_ordered(
439    cst: &Value,
440    options: Option<&ProtoOptions>,
441) -> Result<(FileDescriptorProto, order::Order), ProtoError> {
442    let opts = options.cloned().unwrap_or_default();
443    let first = child_rules(cst).into_iter().next();
444    let declared = match first {
445        Some(node) if "syntaxOrEdition" == nrule(node) => declared_version(node)?,
446        _ => None,
447    };
448    let version = resolve_version(declared, opts.version, opts.reconcile)?;
449    build_descriptor::build_file_ordered(cst, version)
450}
451
452/// Turn a parsed proto CST into the descriptor as a tree: what
453/// [`parse_value`] gives, as [`to_descriptor`] turns one into a
454/// [`FileDescriptorProto`]. Every member and option is named and ordered
455/// as the canonical object has it, the source's order of the members a
456/// statement places included, which the walk records beside the
457/// descriptor and [`descriptor_value`], handed the descriptor alone,
458/// cannot know.
459///
460/// As for [`to_descriptor`], a CST deeper than the cap comes only from
461/// an engine with the grammar alone; [`parse_value_with`] parses and
462/// walks in one call.
463///
464/// ```
465/// fn main() -> Result<(), Box<dyn std::error::Error>> {
466///     let parser = tabnas_proto::make();
467///     let source = "option java_package = \"x\";\npackage p;";
468///     tabnas_proto::preflight(source)?;
469///     let cst = parser.parse(source)?;
470///     let tree = tabnas_proto::to_descriptor_value(&cst, None)?;
471///     assert_eq!(tree, tabnas_proto::parse_value(source, None)?);
472///     Ok(())
473/// }
474/// ```
475pub fn to_descriptor_value(
476    cst: &Value,
477    options: Option<&ProtoOptions>,
478) -> Result<Value, ProtoError> {
479    let (file, order) = to_descriptor_ordered(cst, options)?;
480    Ok(tree::file_value(&file, Some(&order)))
481}
482
483/// Refuse a `.proto` source that nests deeper than
484/// [`MAX_NESTING_DEPTH`], before anything builds a tree that deep.
485///
486/// The TypeScript `preflight` and the Go `Preflight` are the same check,
487/// with the same scan, cap and message, and their `parse` and `Parse`
488/// run it as [`parse`] does here.
489///
490/// [`parse`] and [`parse_with`] run this themselves, so that their
491/// refusal names the document's depth. The parser [`proto`] installs
492/// refuses the same documents as it reads them, at the brace past the cap
493/// with the code `proto_too_deep`, which a parse from a reader needs,
494/// since it never holds the whole text this counts. The check matters
495/// because the engine's `parse` builds a [`tabnas::Value`] tree that
496/// mirrors the document, and that value DROPS recursively, so a deep
497/// enough tree aborts the process even when the descriptor walk refuses
498/// it; an abort cannot be caught, so the refusal has to come before the
499/// tree exists. It is public for a caller that wants a whole text's
500/// depth checked before any engine runs.
501///
502/// The depth is counted in braces, skipping the string literals and
503/// comments the lexer skips, where it skips them: a line comment ends at
504/// a carriage return as well as a line feed, a backtick string is a
505/// string, and a quote opens one only where a token starts, so a quote
506/// inside a word is part of the word. Over-counting is safe here and
507/// under-counting is not, so an unterminated string or comment counts
508/// every brace inside it; the engine rejects that source anyway.
509///
510/// ```
511/// fn main() -> Result<(), Box<dyn std::error::Error>> {
512///     let cap = tabnas_proto::MAX_NESTING_DEPTH;
513///     let parser = tabnas_proto::make();
514///
515///     let deep = format!("{}{}", "message M {".repeat(cap + 1), "}".repeat(cap + 1));
516///     assert!(tabnas_proto::preflight(&deep).is_err());
517///
518///     // At the cap the document is accepted, and the engine may run.
519///     let ok = format!("{}{}", "message M {".repeat(cap), "}".repeat(cap));
520///     tabnas_proto::preflight(&ok)?;
521///     let cst = parser.parse(&ok)?;
522///     assert_eq!(tabnas_proto::nrule(&cst), "proto");
523///     Ok(())
524/// }
525/// ```
526pub fn preflight(src: &str) -> Result<(), ProtoError> {
527    let depth = build_descriptor::brace_depth(src);
528    if depth > MAX_NESTING_DEPTH {
529        return Err(ProtoError::TooDeep(format!(
530            "proto: document nests {depth} levels deep, past the {MAX_NESTING_DEPTH} this \
531             parser accepts"
532        )));
533    }
534    Ok(())
535}
536
537/// Parse a `.proto` source string on a parser the caller holds.
538///
539/// The high-throughput path. Installing the grammar dominates a parse by
540/// more than an order of magnitude, so a caller reading many documents builds one
541/// instance with [`make`] and passes it here: this runs the same
542/// [`preflight`] [`parse`] runs, whose refusal names the document's depth,
543/// then the engine, then the walk.
544///
545/// ```
546/// fn main() -> Result<(), Box<dyn std::error::Error>> {
547///     let parser = tabnas_proto::make();
548///     for source in ["syntax = \"proto2\";", "edition = \"2023\";"] {
549///         let file = tabnas_proto::parse_with(&parser, source, None)?;
550///         assert!(file.syntax.is_some());
551///     }
552///     Ok(())
553/// }
554/// ```
555pub fn parse_with(
556    parser: &Tabnas,
557    src: &str,
558    options: Option<&ProtoOptions>,
559) -> Result<FileDescriptorProto, ProtoError> {
560    preflight(src)?;
561    let cst = parser.parse(src)?;
562    to_descriptor(&cst, options)
563}
564
565/// Parse a `.proto` source string to a [`FileDescriptorProto`].
566///
567/// ```
568/// fn main() -> Result<(), Box<dyn std::error::Error>> {
569///     let source = "syntax = \"proto2\";\nmessage M { required int32 id = 1; }";
570///     let file = tabnas_proto::parse(source, None)?;
571///     let field = &file.message_type[0].field[0];
572///     assert_eq!(field.label, Some(tabnas_proto::FieldLabel::Required));
573///     assert_eq!(field.r#type, Some(tabnas_proto::FieldType::Int32));
574///     Ok(())
575/// }
576/// ```
577///
578/// A document nesting deeper than [`MAX_NESTING_DEPTH`] is refused before
579/// the engine builds a tree that deep; see that constant.
580pub fn parse(src: &str, options: Option<&ProtoOptions>) -> Result<FileDescriptorProto, ProtoError> {
581    parse_with(shared(), src, options)
582}
583
584/// Parse a `.proto` source string to the descriptor as a tree: the value
585/// the canonical `parse` returns, every member named and ordered as its
586/// object has them.
587///
588/// A host that walks the value, as a translation does when it streams a
589/// tree's events, reads this rather than the [`FileDescriptorProto`]
590/// struct, whose serialization holds the same members in the order the
591/// struct declares them. The members a statement places come in the
592/// source's order, which the walk records beside the descriptor; on a
593/// parser the caller holds, [`parse_value_with`] gives the same tree.
594///
595/// ```
596/// fn main() -> Result<(), Box<dyn std::error::Error>> {
597///     let tree = tabnas_proto::parse_value("syntax = \"proto3\";\nmessage M { optional int32 a = 1; }", None)?;
598///     let tabnas::Value::Object(file) = &tree else { panic!("an object") };
599///     let tabnas::Value::Array(messages) = &file["messageType"] else { panic!("a list") };
600///     let tabnas::Value::Object(message) = &messages[0] else { panic!("an object") };
601///     let tabnas::Value::Array(fields) = &message["field"] else { panic!("a list") };
602///     let tabnas::Value::Object(field) = &fields[0] else { panic!("an object") };
603///     let names: Vec<&str> = field.keys().map(String::as_str).collect();
604///     // `proto3Optional` straight after `label`, and the synthesised
605///     // oneof's index last, as the canonical walk assigns them.
606///     assert_eq!(names, ["name", "number", "label", "proto3Optional", "type", "oneofIndex"]);
607///     Ok(())
608/// }
609/// ```
610pub fn parse_value(src: &str, options: Option<&ProtoOptions>) -> Result<Value, ProtoError> {
611    parse_value_with(shared(), src, options)
612}
613
614/// [`parse_value`] on a parser the caller holds, as [`parse_with`] is
615/// [`parse`]: it runs the same [`preflight`], then the engine, then
616/// [`to_descriptor_value`].
617///
618/// ```
619/// fn main() -> Result<(), Box<dyn std::error::Error>> {
620///     let parser = tabnas_proto::make();
621///     for source in ["package p;\noption a = 1;", "option a = 1;\npackage p;"] {
622///         let tree = tabnas_proto::parse_value_with(&parser, source, None)?;
623///         assert_eq!(tree, tabnas_proto::parse_value(source, None)?);
624///     }
625///     Ok(())
626/// }
627/// ```
628pub fn parse_value_with(
629    parser: &Tabnas,
630    src: &str,
631    options: Option<&ProtoOptions>,
632) -> Result<Value, ProtoError> {
633    preflight(src)?;
634    let cst = parser.parse(src)?;
635    to_descriptor_value(&cst, options)
636}
637
638/// Turn a parsed proto CST into the source-ordered tree: the file's
639/// declarations in the order the file writes them, the schema `proto-ast`
640/// (alchemy's `docs/streaming-plan.md`, section 13.1). Every node is an
641/// object whose `type` comes first and whose other members follow in the
642/// order the statement spells them, and every scalar is the text the
643/// source spells. It is the tree the translation parts read and write,
644/// and the one the transducer part (`alchemy/transduce.alc`) streams from
645/// the parse's rule passes.
646///
647/// As for [`to_descriptor`], a CST deeper than the cap comes only from
648/// an engine with the grammar alone; [`parse_tree_with`] parses and walks
649/// in one call, and the walk refuses a CST nesting past
650/// [`MAX_NESTING_DEPTH`].
651///
652/// ```
653/// fn main() -> Result<(), Box<dyn std::error::Error>> {
654///     let parser = tabnas_proto::make();
655///     let source = "message M { int32 a = 1; }";
656///     tabnas_proto::preflight(source)?;
657///     let cst = parser.parse(source)?;
658///     assert_eq!(tabnas_proto::to_tree(&cst)?, tabnas_proto::parse_tree(source)?);
659///     Ok(())
660/// }
661/// ```
662pub fn to_tree(cst: &Value) -> Result<Value, ProtoError> {
663    ast::build_tree(cst)
664}
665
666/// Parse a `.proto` source string to its source-ordered tree on a parser
667/// the caller holds: [`preflight`], then the engine, then [`to_tree`].
668pub fn parse_tree_with(parser: &Tabnas, src: &str) -> Result<Value, ProtoError> {
669    preflight(src)?;
670    let cst = parser.parse(src)?;
671    to_tree(&cst)
672}
673
674/// Parse a `.proto` source string to its source-ordered tree, the schema
675/// `proto-ast`: the file's declarations in source order.
676///
677/// ```
678/// fn main() -> Result<(), Box<dyn std::error::Error>> {
679///     let tree = tabnas_proto::parse_tree("syntax = \"proto3\";\nmessage M { int32 a = 1; }")?;
680///     let tabnas::Value::Object(file) = &tree else { panic!("an object") };
681///     let tabnas::Value::Array(body) = &file["body"] else { panic!("a list") };
682///     let tabnas::Value::Object(syntax) = &body[0] else { panic!("an object") };
683///     // A scalar is the source's text: a string literal keeps its quotes.
684///     assert_eq!(syntax["value"], tabnas::Value::String("\"proto3\"".into()));
685///     Ok(())
686/// }
687/// ```
688pub fn parse_tree(src: &str) -> Result<Value, ProtoError> {
689    parse_tree_with(shared(), src)
690}
691
692/// One optional alchemy translation source and its explicit entry point.
693#[derive(Clone, Copy, Debug, Eq, PartialEq)]
694pub struct TranslationPart {
695    /// The definition a host calls after linking the source.
696    pub entry: &'static str,
697    /// The source text, or `None` for an entry supplied by alchemy.
698    pub source: Option<&'static str>,
699}
700
701/// The package-local structural translation interface.
702#[derive(Clone, Copy, Debug, Eq, PartialEq)]
703pub struct TranslationParts {
704    /// The complete `tabnas.plugin.json` text.
705    pub manifest: &'static str,
706    /// An optional lift from the grammar's events to its first read shape.
707    pub lift: Option<TranslationPart>,
708    /// An optional embedding of a plain tree in the format's schema, with its reverse.
709    pub embed: Option<TranslationPart>,
710    /// An optional render from the write shape to text.
711    pub render: Option<TranslationPart>,
712    /// An optional transducer: the format's JSON events from its parser's
713    /// rule passes, which a host that reads parser events reads a document
714    /// through.
715    pub transduce: Option<TranslationPart>,
716}
717
718const TRANSLATION: TranslationParts = TranslationParts {
719    manifest: include_str!("../translate/manifest.json"),
720    lift: None,
721    embed: None,
722    render: Some(TranslationPart {
723        entry: "proto-render",
724        source: Some(include_str!("../translate/render.alc")),
725    }),
726    transduce: Some(TranslationPart {
727        entry: "proto-transduce",
728        source: Some(include_str!("../translate/transduce.alc")),
729    }),
730};
731
732/// Return the translation parts of `.proto` files: the manifest, the
733/// render that writes the source-ordered tree ([`parse_tree`]'s, the
734/// schema `proto-ast`) back as a `.proto` file, and the transducer part,
735/// `proto-transduce`, that makes the same tree's JSON events from the
736/// grammar's rule passes (the manifest's `translate.transduce`). There is
737/// no lift, and no embed: the tree is the format's own shape, which a host
738/// renders only from a source of the same schema or from a program that
739/// builds the tree.
740///
741/// ```
742/// let parts = tabnas_proto::translate().expect("proto carries translation parts");
743/// assert_eq!(parts.render.map(|part| part.entry), Some("proto-render"));
744/// assert_eq!(parts.transduce.map(|part| part.entry), Some("proto-transduce"));
745/// assert_eq!(parts.embed, None);
746/// ```
747#[must_use]
748pub const fn translate() -> Option<TranslationParts> {
749    Some(TRANSLATION)
750}
751
752/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
753/// it. Its `translate` object is what a host that translates reads: the
754/// shape the format is read as and written from (`tree`), the schema of
755/// that tree (`proto-ast`), the root the render needs (`object`), the
756/// files that hold the render and the transducer part, and the sentences
757/// that say what a written file does not keep. The crate embeds its own copy,
758/// `translate/manifest.json`, since a packaged crate holds nothing outside
759/// `rs/`; `tests/translate_test.rs` holds the copy to the file.
760///
761/// ```
762/// assert!(tabnas_proto::manifest_text().contains("\"proto-ast\""));
763/// ```
764pub fn manifest_text() -> &'static str {
765    TRANSLATION.manifest
766}
767
768/// The render, `alchemy/render.alc`, the file the manifest's
769/// `translate.render` names: a library of alchemy definitions, with no
770/// `export`, whose entry point `proto-render` writes the source-ordered
771/// tree's events as one `.proto` file that reads back as the same tree. A
772/// host links it with its own program. The crate embeds its own copy,
773/// `translate/render.alc`, held to the file as the manifest's is.
774///
775/// ```
776/// assert!(tabnas_proto::render_text().contains("def proto-render [input]"));
777/// ```
778pub fn render_text() -> &'static str {
779    match TRANSLATION.render {
780        Some(part) => part.source.unwrap_or_default(),
781        None => "",
782    }
783}
784
785/// The transducer part, `alchemy/transduce.alc`, the file the manifest's
786/// `translate.transduce` names: a library of alchemy definitions, with no
787/// `export`, whose entry point `proto-transduce` makes the source-ordered
788/// tree's JSON events (the ones [`parse_tree`]'s tree walks to) from the
789/// rule passes of a parser [`make`] builds. The crate embeds its own copy,
790/// `translate/transduce.alc`, held to the file as the render's is.
791///
792/// ```
793/// assert!(tabnas_proto::transduce_text().contains("def proto-transduce [input]"));
794/// ```
795pub fn transduce_text() -> &'static str {
796    match TRANSLATION.transduce {
797        Some(part) => part.source.unwrap_or_default(),
798        None => "",
799    }
800}