tabnas_c/lib.rs
1/* Copyright (c) 2026 Richard Rodger and 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`. The engine allows the lint at its own
6// crate root for the same reason; boxing here would make `parse` return
7// a different shape from `Tabnas::parse` and from the other two ports.
8#![allow(clippy::result_large_err)]
9
10//! The C grammar plugin for the `tabnas` parsing engine.
11//!
12//! Parses C23 source, plus the common GCC, Clang and MSVC extensions,
13//! into a CONCRETE syntax tree: every token, comment, macro definition,
14//! macro use and compiler extension is kept verbatim, so the tree can
15//! be walked back to the source it came from.
16//!
17//! ```
18//! fn main() -> Result<(), Box<dyn std::error::Error>> {
19//! let value = tabnas_c::parse("int x = 1;")?;
20//! assert_eq!(value.to_json()["kind"], "translation_unit");
21//! Ok(())
22//! }
23//! ```
24//!
25//! The plugin layers on the relaxed-JSON grammar of
26//! [`tabnas_jsonic`] (the DSL the grammar document is authored in) and
27//! on [`tabnas_expr`] for Pratt-style expression parsing, exactly as
28//! the canonical TypeScript plugin layers on `@tabnas/jsonic` and
29//! `@tabnas/expr`.
30//!
31//! TypeScript is canonical: `ts/src/c.ts` defines behaviour, option
32//! names and defaults, and `ts/c-grammar.jsonic` defines the rule
33//! chain, embedded here as the same text. The shared fixtures in
34//! `test/spec/*.tsv` are the parity contract across TypeScript, Go and
35//! Rust.
36
37use std::sync::OnceLock;
38
39use indexmap::IndexMap;
40
41use tabnas::{GrammarSpec, LexMatcher, Options, Plugin, PluginError, Tabnas, TabnasError, Value};
42
43mod conditional_groups;
44mod cst;
45mod expr_grammar;
46mod legacy_expr;
47mod refs;
48mod refs_ext;
49mod refs_forms;
50mod refs_newpath;
51mod refs_stmt;
52mod rt;
53mod sets;
54mod state;
55mod structure;
56mod tokens;
57mod trivia;
58
59pub mod matchers;
60
61pub use cst::{realize, REALIZE_DEPTH_CAP};
62
63/// The symbol and macro tables, re-exported so a caller can seed a
64/// parse with names a header would have introduced. The canonical
65/// plugin exports the same pair from `ts/src/symbols.ts`, and the Go
66/// port exports them as `SymbolTable` and `MacroTable`.
67pub use state::{Binding, MacroDef, MacroTable, Scope, ScopeKind, SymbolTable, TagKind};
68
69/// This crate's version. It MUST equal `ts/package.json` "version": the
70/// release orchestrator rewrites both, and `tests/version_test.rs`
71/// fails the build if they drift. Mirrors `VERSION` in `ts/src/c.ts`
72/// and `const VERSION` in `go/c.go`.
73pub const VERSION: &str = "0.5.13";
74
75/// The plugin's name, as `use_plugin` records it.
76pub const PLUGIN_NAME: &str = "C";
77
78/// The README's Rust examples run as doctests, so a stale one fails the
79/// gate rather than misleading the reader. Its `toml` and `bash` fences
80/// are skipped; rustdoc runs only the `rust` ones.
81#[cfg(doctest)]
82#[doc = include_str!("../README.md")]
83mod readme_examples {}
84
85/// The error a failed parse produces, re-exported so callers need not
86/// depend on the engine crate directly.
87pub use tabnas::TabnasError as CError;
88
89/// The declarative grammar, the single source of truth for the rule
90/// shapes. `ts/embed-grammar.js` copies `ts/c-grammar.jsonic` here, as
91/// it copies it to `go/c-grammar.jsonic` for `//go:embed`.
92pub const GRAMMAR_TEXT: &str = include_str!("../c-grammar.jsonic");
93
94/// Plugin options. `extended` turns on the GCC, Clang and MSVC
95/// extension constructs and the legacy fallback that covers the
96/// long-tail declarator shapes; plain C23, the whole preprocessor
97/// included, is the default.
98#[derive(Debug, Clone, Default, PartialEq, Eq)]
99pub struct COptions {
100 pub extended: bool,
101}
102
103impl COptions {
104 pub fn new() -> Self {
105 Self::default()
106 }
107
108 pub fn with_extended(mut self, extended: bool) -> Self {
109 self.extended = extended;
110 self
111 }
112
113 /// Read the options out of the JSON bag `use_plugin` merges over
114 /// the declared defaults. Only `extended === true` turns the
115 /// extensions on, as `resolveOptions` in `ts/src/c.ts` does.
116 pub fn from_value(value: &Value) -> Self {
117 let extended = match value {
118 Value::Object(entries) => entries.get("extended") == Some(&Value::Bool(true)),
119 Value::MapRef(map) => map.value.get("extended") == Some(&Value::Bool(true)),
120 _ => false,
121 };
122 Self { extended }
123 }
124}
125
126/// The key `meta` carries the pre-bound names under, as the canonical
127/// plugin reads `ctx.meta.cmeta` and the Go port reads
128/// `ctx.Meta["cmeta"]`.
129pub const META_KEY: &str = "cmeta";
130
131/// Names a parse should already know.
132///
133/// The parser does not follow `#include`, so a translation unit that
134/// uses `uint32_t` has no way to learn that it is a typedef name, and
135/// `uint32_t x;` would parse `uint32_t` as the DECLARED name. The
136/// canonical plugin solves this by letting a caller build a `cmeta` and
137/// bind the names into it before the parse; this is the same thing.
138///
139/// ```
140/// fn main() -> Result<(), Box<dyn std::error::Error>> {
141/// let parser = tabnas_c::make();
142/// let mut meta = tabnas_c::CMeta::new();
143/// meta.symbols.bind_typedef("uint32_t");
144/// let value = tabnas_c::parse_with_meta(&parser, "uint32_t x;", &meta)?;
145/// assert_eq!(value.to_json()["kind"], "translation_unit");
146/// Ok(())
147/// }
148/// ```
149#[derive(Debug, Clone, Default)]
150pub struct CMeta {
151 /// The typedef names, and anything else bound, that the parse
152 /// starts with.
153 pub symbols: SymbolTable,
154 /// The macro names the parse starts with.
155 pub macros: MacroTable,
156}
157
158impl CMeta {
159 /// An empty table pair, as `makeCMeta()` returns in the canonical
160 /// plugin and `MakeCMeta()` in the Go port.
161 pub fn new() -> Self {
162 Self::default()
163 }
164
165 /// The engine `meta` value this builds.
166 ///
167 /// A `Value` cannot hold a native handle, so the tables travel as
168 /// the NAMES they hold rather than as themselves; the parse rebuilds
169 /// its own tables from them at file scope. A binding made in an
170 /// inner scope of a hand-built table therefore arrives at file
171 /// scope, which is where a header's names belong anyway.
172 pub fn to_value(&self) -> Value {
173 let mut inner: IndexMap<String, Value> = IndexMap::new();
174 inner.insert(
175 "typedefs".to_string(),
176 Value::array(
177 self.symbols
178 .typedef_names()
179 .into_iter()
180 .map(Value::String)
181 .collect::<Vec<_>>(),
182 ),
183 );
184 inner.insert(
185 "macros".to_string(),
186 Value::array(
187 self.macros
188 .names()
189 .into_iter()
190 .map(Value::String)
191 .collect::<Vec<_>>(),
192 ),
193 );
194 let mut outer: IndexMap<String, Value> = IndexMap::new();
195 outer.insert(META_KEY.to_string(), Value::object(inner));
196 Value::object(outer)
197 }
198}
199
200/// Bind the names a caller put on `meta` into the fresh parse state.
201fn seed_from_meta(meta: &Value) {
202 let Some(cmeta) = entry(meta, META_KEY) else {
203 return;
204 };
205 let typedefs = names_at(&cmeta, "typedefs");
206 let macros = names_at(&cmeta, "macros");
207 if typedefs.is_empty() && macros.is_empty() {
208 return;
209 }
210 state::with_state(|inner| {
211 for name in typedefs {
212 inner.symbols.bind_typedef(&name);
213 }
214 for name in macros {
215 inner.macros.define(MacroDef {
216 name,
217 ..MacroDef::default()
218 });
219 }
220 });
221}
222
223/// One entry of an engine object, whichever of the two object shapes it
224/// is.
225fn entry(value: &Value, key: &str) -> Option<Value> {
226 match value {
227 Value::Object(entries) => entries.get(key).cloned(),
228 Value::MapRef(map) => map.value.get(key).cloned(),
229 _ => None,
230 }
231}
232
233/// The strings in the array at `key`, ignoring anything that is not one.
234fn names_at(value: &Value, key: &str) -> Vec<String> {
235 let items = match entry(value, key) {
236 Some(Value::Array(items)) => items.to_vec(),
237 Some(Value::ListRef(list)) => list.value.to_vec(),
238 _ => return Vec::new(),
239 };
240 items
241 .into_iter()
242 .filter_map(|item| match item {
243 Value::String(name) => Some(name),
244 _ => None,
245 })
246 .collect()
247}
248
249/// Extension-only grammar rule names. With `extended: false` the
250/// plugin strips these from the parsed grammar document before
251/// installing it. This is the physical companion to the
252/// `c: '@extended-on'` dispatch gating: the gates already make the
253/// rules unreachable, and deleting them outright makes plain-C mode
254/// self-evidently free of extension grammar.
255const EXTENSION_RULES: &[&str] = &[
256 // GCC inline assembly
257 "asm_statement",
258 "asm_template",
259 "asm_section",
260 "asm_operand",
261 "asm_clobber",
262 "asm_label_ref",
263 // Preprocessor (in-body opaque and top-level structured)
264 "preprocessor_line",
265 "preprocessor_directive",
266 "define_directive",
267 "macro_parameter_list",
268 "macro_body",
269 "undef_directive",
270 "include_directive",
271 "header_form",
272 "conditional_directive",
273 "simple_directive",
274 // Compiler-specific attribute spec syntax
275 "attribute_spec_gcc",
276 "attribute_spec_msvc",
277];
278
279/// Install the C grammar on a parser that already carries the jsonic
280/// base grammar.
281///
282/// Returns early when the instance already has the `translation_unit`
283/// rule, so a second install does not give it a second copy of every
284/// alternate, and refuses a bare engine outright: this plugin hangs its
285/// expression alternates on the base grammar's `val` rule, and on an
286/// instance without one there is nothing to hang them on.
287pub fn c(parser: &mut Tabnas, options: &COptions) -> Result<(), PluginError> {
288 let rules = parser.rule_names();
289 if rules.iter().any(|name| name == "translation_unit") {
290 return Ok(());
291 }
292 if !rules.iter().any(|name| name == "val") {
293 return Err(PluginError(
294 "c: the jsonic base grammar is required (no `val` rule on this instance); \
295 install tabnas_jsonic first"
296 .to_string(),
297 ));
298 }
299
300 let tins = register_tokens(parser);
301 apply_options(parser, &tins)?;
302 let stubbed = refs::register(parser, options);
303 let _ = stubbed;
304 install_grammar(parser, options)?;
305 expr_grammar::install(parser)?;
306 Ok(())
307}
308
309/// Register every token name the parser uses, so each has a stable
310/// identity before the grammar document resolves names to it.
311fn register_tokens(parser: &mut Tabnas) -> matchers::Tins {
312 let mut tins = matchers::Tins::default();
313 // Punctuators and keywords carry their source as a fixed token.
314 // The built-in fixed matcher is switched off below, so registering
315 // them only mints the identity: an identifier such as `int_value`
316 // is never cut at the `int` keyword.
317 for (name, source) in tokens::PUNCTUATORS {
318 tins.insert(name, parser.token_with_source(*name, *source));
319 }
320 for keyword in tokens::C23_KEYWORDS
321 .iter()
322 .chain(tokens::EXT_KEYWORDS.iter())
323 {
324 let name = tokens::keyword_token_name_unchecked(keyword);
325 tins.insert(&name, parser.token_with_source(name.clone(), *keyword));
326 }
327 for name in tokens::SPECIAL_TOKENS {
328 tins.insert(name, parser.token(name.to_string()));
329 }
330 for name in ["#SP", "#LN", "#CM", "#ZZ"] {
331 tins.insert(name, parser.token(name.to_string()));
332 }
333 tins
334}
335
336/// The per-instance engine options, mirroring the `jsonic.options(...)`
337/// calls in `ts/src/c.ts`.
338fn apply_options(parser: &mut Tabnas, tins: &matchers::Tins) -> Result<(), PluginError> {
339 let ignore = [
340 "#SP",
341 "#LN",
342 "#CM",
343 "TRIVIA_LINE_COMMENT",
344 "TRIVIA_BLOCK_COMMENT",
345 "TRIVIA_LINE_CONT",
346 ];
347 let token_sets: Vec<(&str, Vec<String>)> = vec![
348 (
349 "IGNORE",
350 ignore.iter().map(|name| (*name).to_string()).collect(),
351 ),
352 ("ANY_C_TOKEN", tokens::any_c_token_names()),
353 (
354 "SIMPLE_TYPE_HEAD",
355 sets::SIMPLE_TYPE_HEAD
356 .iter()
357 .map(|n| n.to_string())
358 .collect(),
359 ),
360 (
361 "STORAGE_PREFIX",
362 sets::STORAGE_PREFIX.iter().map(|n| n.to_string()).collect(),
363 ),
364 (
365 "C_ATOM",
366 sets::C_ATOM.iter().map(|n| n.to_string()).collect(),
367 ),
368 (
369 "C_PAREN_OPEN",
370 sets::C_PAREN_OPEN.iter().map(|n| n.to_string()).collect(),
371 ),
372 ("KW_TOKEN", tokens::keyword_token_names()),
373 (
374 "SIZEOF_KW",
375 sets::SIZEOF_KW.iter().map(|n| n.to_string()).collect(),
376 ),
377 ];
378
379 let matcher_tins = tins.clone();
380 parser
381 .set_options(move |options: &mut Options| {
382 options.fixed.lex = false;
383 options.space.lex = false;
384 options.line.lex = false;
385 options.text.lex = false;
386 options.number.lex = false;
387 options.string.lex = false;
388 options.comment.lex = false;
389 options.value.lex = false;
390 options.match_lex = true;
391
392 for (name, members) in &token_sets {
393 let members: Vec<i32> = members
394 .iter()
395 .map(|member| {
396 options
397 .token(member)
398 .unwrap_or_else(|| options.register_token(member.clone()))
399 })
400 .collect();
401 options.token_set.insert((*name).to_string(), members);
402 }
403
404 for (name, order) in matchers::MATCHER_ORDER {
405 options.lex.matchers.insert(
406 (*name).to_string(),
407 LexMatcher {
408 name: (*name).to_string(),
409 order: *order,
410 matcher: None,
411 imperative: Some(matchers::make(name, matcher_tins.clone())),
412 factory: None,
413 },
414 );
415 }
416
417 // The C punctuator identities must come FIRST in the fixed
418 // table. `Tabnas::fixed(source)` answers with the first
419 // entry carrying that source, and the base grammar already
420 // registers `,`, `:`, `[`, `]`, `{` and `}` under its own
421 // names; the expr plugin resolves each operator's source
422 // through that lookup, so without this it would bind the
423 // comma operator to the base grammar's `#CA` and wait for a
424 // token this lexer never emits. The canonical engine's
425 // source-to-identity map is written last-wins and the C
426 // tokens are registered last, which is the same answer.
427 let mut ordered: IndexMap<String, tabnas::FixedToken> = IndexMap::new();
428 for (name, token) in options.fixed.tokens.iter() {
429 if name.starts_with("#PUNC_") || name.starts_with("#KW_") {
430 ordered.insert(name.clone(), token.clone());
431 }
432 }
433 for (name, token) in options.fixed.tokens.iter() {
434 if !ordered.contains_key(name) {
435 ordered.insert(name.clone(), token.clone());
436 }
437 }
438 options.fixed.tokens = ordered;
439
440 options.rule.start = "translation_unit".to_string();
441 options.rule.finish = false;
442 })
443 .map_err(|error| PluginError(format!("c: options: {}", error.0)))?;
444
445 // Every parse starts from a clean symbol table, macro table, lexer
446 // mode and tree arena. The canonical plugin installs a `cmeta`
447 // object on `ctx.meta` from the same hook.
448 parser
449 .set_options(|options: &mut Options| {
450 options
451 .parse
452 .prepare
453 .push(tabnas::ParsePrepare::Context(std::sync::Arc::new(
454 |context: &mut tabnas::Context| {
455 state::reset();
456 seed_from_meta(&context.meta);
457 },
458 )));
459 })
460 .map_err(|error| PluginError(format!("c: prepare: {}", error.0)))?;
461
462 // The sub-lex hook. See `crate::trivia`.
463 parser.subscribe_lex(|token, _rule, _context| trivia::on_lex_token(token));
464
465 Ok(())
466}
467
468/// Parse the embedded grammar text into a serialized document, as the
469/// canonical `parseGrammar` does with a vanilla jsonic instance, and
470/// install it.
471fn install_grammar(parser: &mut Tabnas, options: &COptions) -> Result<(), PluginError> {
472 let parsed = tabnas_jsonic::parse(GRAMMAR_TEXT)
473 .map_err(|error| PluginError(format!("c-grammar.jsonic: {error}")))?;
474 let mut document = parsed.to_json();
475 if !document.is_object() || document.get("rule").is_none() {
476 return Err(PluginError(
477 "c-grammar.jsonic: expected a JSON object with a `rule` table".to_string(),
478 ));
479 }
480 integral(&mut document);
481 if !options.extended {
482 if let Some(rules) = document
483 .get_mut("rule")
484 .and_then(serde_json::Value::as_object_mut)
485 {
486 for name in EXTENSION_RULES {
487 rules.remove(*name);
488 }
489 }
490 }
491 let spec = GrammarSpec::from_value(document).map_err(|error| PluginError(error.0))?;
492 parser
493 .grammar(&spec)
494 .map_err(|error| PluginError(error.0))?;
495 Ok(())
496}
497
498/// jsonic yields every number as a float; the grammar loader reads `b`
499/// and `n` with `as_u64`, so a whole number has to arrive as an
500/// integer.
501fn integral(value: &mut serde_json::Value) {
502 match value {
503 serde_json::Value::Number(number) => {
504 if let Some(float) = number.as_f64() {
505 if float >= 0.0 && float.fract() == 0.0 && float <= u64::MAX as f64 {
506 *value = serde_json::Value::from(float as u64);
507 }
508 }
509 }
510 serde_json::Value::Array(items) => items.iter_mut().for_each(integral),
511 serde_json::Value::Object(entries) => entries.values_mut().for_each(integral),
512 _ => {}
513 }
514}
515
516/// The plugin, for `use_plugin`.
517pub fn plugin() -> Plugin {
518 Plugin::new(PLUGIN_NAME, |parser: &mut Tabnas, options: &Value| {
519 c(parser, &COptions::from_value(options))
520 })
521 .with_defaults(Value::object(indexmap::IndexMap::new()))
522}
523
524/// A parser carrying the jsonic base grammar and the C grammar.
525pub fn make() -> Tabnas {
526 make_with(&COptions::default())
527}
528
529/// A parser built with the given plugin options.
530pub fn make_with(options: &COptions) -> Tabnas {
531 let mut parser = tabnas_jsonic::make();
532 c(&mut parser, options).expect("c: the grammar installs on a jsonic instance");
533 parser
534}
535
536/// Parse C source with a shared default parser.
537///
538/// Building a parser costs far more than a small parse, so the
539/// instance is built once and reused. For anything but a one-off call,
540/// build one with [`make`] and keep it.
541pub fn parse(source: &str) -> Result<Value, TabnasError> {
542 static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
543 let parser = DEFAULT.get_or_init(make);
544 parse_with(parser, source)
545}
546
547/// Parse with a parser the caller built, realizing the tree into plain
548/// engine values.
549///
550/// A parse builds its tree in a per-thread arena and the value the
551/// engine returns is a handle into it, so a caller driving a `tabnas`
552/// instance directly must call [`realize`] on the result before the
553/// next parse on that thread. This function does it for you.
554pub fn parse_with(parser: &Tabnas, source: &str) -> Result<Value, TabnasError> {
555 let value = parser.parse(source)?;
556 realized(source, &value)
557}
558
559/// Realize a parsed tree, failing the parse when the walk ran out of
560/// depth.
561///
562/// A tree deeper than [`cst::REALIZE_DEPTH_CAP`], or one that is not a
563/// tree at all, would otherwise come back with a hole in it where the
564/// walk stopped. The engine's own budget exhaustion reports `cancel`,
565/// so a limit reached here reports the same code rather than inventing
566/// one: this package declares no error codes of its own.
567fn realized(source: &str, value: &Value) -> Result<Value, TabnasError> {
568 let realized = realize(value);
569 if cst::realize_truncated() || state::with_state(|inner| inner.gave_up) {
570 return Err(TabnasError::new("cancel", "", source, 0, 1, 1));
571 }
572 Ok(realized)
573}
574
575/// Parse with names the source never declares itself: the typedef and
576/// macro names a header would have introduced.
577///
578/// This is the Rust spelling of the canonical `jsonic.parse(src,
579/// { cmeta })` and of the Go port's `ParseMeta(src, map[string]any{
580/// "cmeta": cm})`. Without it a corpus of `#include <stdint.h>`
581/// programs parses `uint32_t` as a declared name rather than a type.
582pub fn parse_with_meta(parser: &Tabnas, source: &str, meta: &CMeta) -> Result<Value, TabnasError> {
583 let value = parser.parse_with_meta(source, meta.to_value())?;
584 realized(source, &value)
585}