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
// Copyright (c) 2026 Richard Rodger and other contributors, 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`. This crate boxes it inside `ProtoError`
// for that reason; the allow covers the engine's own `Result` where it
// surfaces here.
//! Parse Protocol Buffers `.proto` IDL into FileDescriptorProto-shaped
//! values.
//!
//! proto2, proto3 and editions 2023 and 2024, with the version detected
//! from the file's `syntax` or `edition` declaration. The parser is an
//! [ABNF](https://github.com/tabnas/abnf) grammar driving the
//! [`tabnas`](https://github.com/tabnas/parser) engine rather than a
//! hand-written parser: `proto-grammar/*.abnf` at the repository root is
//! the single source of truth, embedded into every runtime by
//! `ts/embed-grammar.js`.
//!
//! ```
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let file = tabnas_proto::parse("syntax = \"proto3\";\nmessage M { int32 a = 1; }", None)?;
//! assert_eq!(file.syntax.as_deref(), Some("proto3"));
//! assert_eq!(file.message_type[0].name, "M");
//! assert_eq!(file.message_type[0].field[0].number, 1.0);
//! Ok(())
//! }
//! ```
//!
//! TypeScript is canonical: `ts/src` defines behaviour, and the shared
//! fixtures in `test/spec/*.tsv` are the parity contract across
//! TypeScript, Go and Rust. Where this port cannot match the canonical
//! value, `DIVERGENCE.md` at the repository root records it.
//!
//! A parsed `.proto` file is DATA, never instructions. Schema files
//! arrive from outside the system, and every string in a descriptor,
//! `import` paths and `type_name`s included, is untrusted text. See the
//! repository `AGENTS.md`.
/// 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.
use OnceLock;
use IndexMap;
use Deserialize;
use ;
use ;
pub use ;
pub use ;
pub use ;
pub use ProtoError;
pub use GRAMMAR_TEXT;
pub use ;
/// 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/proto.ts` and
/// `const VERSION` in `go/proto.go`.
pub const VERSION: &str = "0.6.2";
/// The plugin's name on an instance, and the key its option bag hangs
/// under.
pub const PLUGIN_NAME: &str = "Proto";
/// The engine's retained backtracking history, as the canonical
/// `new Tabnas({ rewind: { history: 8192 } })` sets it.
///
/// The union grammar backtracks across whole statements, and the engine's
/// default of 64 consumed tokens is not enough to rewind one. This is a
/// parse-affecting setting, not a tuning knob: lower it and documents
/// that should parse stop parsing.
pub const REWIND_HISTORY: usize = 8192;
/// How a `.proto` document is read.
///
/// Mirrors the canonical `ProtoOptions`. The defaults auto-detect the
/// version from the file's declaration and refuse an explicit version
/// that disagrees with it.
/// Install the union proto grammar on an engine instance, so it can parse
/// `.proto` source into a `{rule, src, kids}` CST.
///
/// Use [`to_descriptor`] to turn that CST into a [`FileDescriptorProto`].
/// The Rust spelling of the canonical `tn.use(Proto)`.
///
/// Driving the engine's own `parse` skips the nesting [`preflight`], so
/// a caller handing it untrusted source runs that check first; see
/// [`preflight`] for what the tree costs without it.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut parser = tabnas_proto::engine();
/// tabnas_proto::proto(&mut parser)?;
/// let source = "syntax = \"proto3\";";
/// tabnas_proto::preflight(source)?;
/// let cst = parser.parse(source)?;
/// let file = tabnas_proto::to_descriptor(&cst, None)?;
/// assert_eq!(file.syntax.as_deref(), Some("proto3"));
/// Ok(())
/// }
/// ```
/// The plugin form of [`proto`], for [`Tabnas::use_plugin`].
///
/// Installed this way the grammar is re-applied to derived instances, as
/// every native plugin is.
/// A bare engine configured the way this plugin needs it, with no grammar
/// installed yet.
///
/// The canonical `new Tabnas({ rewind: { history: 8192 } })`. See
/// [`REWIND_HISTORY`] for why the setting is not optional.
/// Build a proto parser: [`engine`] with this plugin installed, the
/// counterpart of `new Tabnas().use(Proto)` and the Go `Proto(j)`.
///
/// Compiling the grammar dominates a parse, so build one and reuse it.
/// Read each document through [`parse_with`], which runs the nesting
/// [`preflight`] the engine's own `parse` does not.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let parser = tabnas_proto::make();
/// let file = tabnas_proto::parse_with(&parser, "message M {}", None)?;
/// // No declaration and no option: protoc's default is proto2.
/// assert_eq!(file.syntax.as_deref(), Some("proto2"));
/// Ok(())
/// }
/// ```
/// The shared default parser.
///
/// Compiling the grammar dominates a parse by orders of magnitude, and
/// the plugin keeps no per-parse state on the instance, so one instance
/// serves every call to [`parse`]. Parsing builds a fresh context and
/// only reads instance state, so it is safe for concurrent use.
/// Turn a parsed proto CST into a [`FileDescriptorProto`], resolving the
/// version from the file's declaration and the supplied options.
///
/// The walk refuses a CST nesting past [`MAX_NESTING_DEPTH`], but by
/// then the tree EXISTS, and a `tabnas::Value` that deep aborts the
/// process when it drops. A caller who parsed the source itself runs
/// [`preflight`] on that source first; [`parse_with`] does both.
/// Refuse a `.proto` source that nests deeper than
/// [`MAX_NESTING_DEPTH`], before anything builds a tree that deep.
///
/// [`parse`] and [`parse_with`] run this themselves. It is public for
/// the caller who drives the engine directly, through [`make`] or
/// [`proto`] on an instance of their own: the engine's `parse` builds a
/// [`tabnas::Value`] tree that mirrors the document, and that value
/// DROPS recursively, so a deep enough document aborts the process even
/// when the descriptor walk refuses it. An abort cannot be caught, so
/// the check has to come before the tree exists.
///
/// The depth is counted in braces, skipping the string literals and
/// comments the lexer skips. Over-counting is safe here and
/// under-counting is not, so an unterminated string or comment counts
/// every brace inside it; the engine rejects that source anyway.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let cap = tabnas_proto::MAX_NESTING_DEPTH;
/// let parser = tabnas_proto::make();
///
/// let deep = format!("{}{}", "message M {".repeat(cap + 1), "}".repeat(cap + 1));
/// assert!(tabnas_proto::preflight(&deep).is_err());
///
/// // At the cap the document is accepted, and the engine may run.
/// let ok = format!("{}{}", "message M {".repeat(cap), "}".repeat(cap));
/// tabnas_proto::preflight(&ok)?;
/// let cst = parser.parse(&ok)?;
/// assert_eq!(tabnas_proto::nrule(&cst), "proto");
/// Ok(())
/// }
/// ```
/// Parse a `.proto` source string on a parser the caller holds.
///
/// The high-throughput path. Compiling the grammar dominates a parse by
/// orders of magnitude, so a caller reading many documents builds one
/// instance with [`make`] and passes it here, rather than driving the
/// engine directly: this runs the same [`preflight`] [`parse`] runs, and
/// the engine's own `parse` does not.
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let parser = tabnas_proto::make();
/// for source in ["syntax = \"proto2\";", "edition = \"2023\";"] {
/// let file = tabnas_proto::parse_with(&parser, source, None)?;
/// assert!(file.syntax.is_some());
/// }
/// Ok(())
/// }
/// ```
/// Parse a `.proto` source string to a [`FileDescriptorProto`].
///
/// ```
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let source = "syntax = \"proto2\";\nmessage M { required int32 id = 1; }";
/// let file = tabnas_proto::parse(source, None)?;
/// let field = &file.message_type[0].field[0];
/// assert_eq!(field.label, Some(tabnas_proto::FieldLabel::Required));
/// assert_eq!(field.r#type, Some(tabnas_proto::FieldType::Int32));
/// Ok(())
/// }
/// ```
///
/// A document nesting deeper than [`MAX_NESTING_DEPTH`] is refused before
/// the engine builds a tree that deep; see that constant.