Skip to main content

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 cst;
44mod expr_grammar;
45mod fallback;
46mod members;
47mod refs;
48mod refs_ext;
49mod refs_forms;
50mod refs_newpath;
51mod refs_stmt;
52mod rt;
53mod sets;
54mod state;
55mod tokens;
56mod trivia;
57
58pub mod matchers;
59
60pub use cst::{realize, REALIZE_DEPTH_CAP};
61pub use members::{member, member_names};
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.6.2";
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    // Compiler-specific attribute spec syntax
264    "attribute_spec_gcc",
265    "attribute_spec_msvc",
266];
267
268/// Install the C grammar on a parser that already carries the jsonic
269/// base grammar.
270///
271/// Returns early when the instance already has the `translation_unit`
272/// rule, so a second install does not give it a second copy of every
273/// alternate, and refuses a bare engine outright: this plugin hangs its
274/// expression alternates on the base grammar's `val` rule, and on an
275/// instance without one there is nothing to hang them on.
276pub fn c(parser: &mut Tabnas, options: &COptions) -> Result<(), PluginError> {
277    let rules = parser.rule_names();
278    if rules.iter().any(|name| name == "translation_unit") {
279        return Ok(());
280    }
281    if !rules.iter().any(|name| name == "val") {
282        return Err(PluginError(
283            "c: the jsonic base grammar is required (no `val` rule on this instance); \
284             install tabnas_jsonic first"
285                .to_string(),
286        ));
287    }
288
289    let tins = register_tokens(parser);
290    apply_options(parser, &tins)?;
291    // The grammar document, with the armed fallback's alternates given to
292    // the rules below `external_declaration` (`crate::fallback`), first:
293    // which refs the fallback wraps and fences is read from it.
294    let (document, fallback) = grammar_document(options)?;
295    // Every reference the grammar names has its handler
296    // (`every_reference_the_grammar_names_has_a_handler`); a name left
297    // over gets a no-op, which that test refuses.
298    refs::register(parser, options, &fallback);
299    // C's expressions are read by tabnas-expr, from the rule named `val`
300    // that jsonic's grammar has too. Clear jsonic's, alternates and actions
301    // both, so that expr's and C's are the only ones
302    // (`crate::expr_grammar`).
303    parser.define_rule("val", |spec| {
304        spec.clear();
305    });
306    install_grammar(parser, document)?;
307    expr_grammar::install(parser)?;
308    // The rules expr reads an expression with, its own and the jsonic ones
309    // it pushes (an implicit list inside a paren), are below every external
310    // declaration too.
311    fallback::with_rule_fallback(parser, expr_grammar::EXPR_RULES);
312    Ok(())
313}
314
315/// Register every token name the parser uses, so each has a stable
316/// identity before the grammar document resolves names to it.
317fn register_tokens(parser: &mut Tabnas) -> matchers::Tins {
318    let mut tins = matchers::Tins::default();
319    // Punctuators and keywords carry their source as a fixed token.
320    // The built-in fixed matcher is switched off below, so registering
321    // them only mints the identity: an identifier such as `int_value`
322    // is never cut at the `int` keyword.
323    for (name, source) in tokens::PUNCTUATORS {
324        tins.insert(name, parser.token_with_source(*name, *source));
325    }
326    for keyword in tokens::C23_KEYWORDS
327        .iter()
328        .chain(tokens::EXT_KEYWORDS.iter())
329    {
330        let name = tokens::keyword_token_name_unchecked(keyword);
331        tins.insert(&name, parser.token_with_source(name.clone(), *keyword));
332    }
333    for name in tokens::SPECIAL_TOKENS {
334        tins.insert(name, parser.token(name.to_string()));
335    }
336    for name in ["#SP", "#LN", "#CM", "#ZZ"] {
337        tins.insert(name, parser.token(name.to_string()));
338    }
339    tins
340}
341
342fn owned(names: &[&str]) -> Vec<String> {
343    names.iter().map(|name| (*name).to_string()).collect()
344}
345
346/// The per-instance engine options, mirroring the `jsonic.options(...)`
347/// calls in `ts/src/c.ts`.
348fn apply_options(parser: &mut Tabnas, tins: &matchers::Tins) -> Result<(), PluginError> {
349    let ignore = [
350        "#SP",
351        "#LN",
352        "#CM",
353        "TRIVIA_LINE_COMMENT",
354        "TRIVIA_BLOCK_COMMENT",
355        "TRIVIA_LINE_CONT",
356    ];
357    let token_sets: Vec<(&str, Vec<String>)> = vec![
358        (
359            "IGNORE",
360            ignore.iter().map(|name| (*name).to_string()).collect(),
361        ),
362        ("ANY_C_TOKEN", tokens::any_c_token_names()),
363        (
364            "SIMPLE_TYPE_HEAD",
365            sets::SIMPLE_TYPE_HEAD
366                .iter()
367                .map(|n| n.to_string())
368                .collect(),
369        ),
370        (
371            "STORAGE_PREFIX",
372            sets::STORAGE_PREFIX.iter().map(|n| n.to_string()).collect(),
373        ),
374        ("DECL_HEAD", owned(sets::DECL_HEAD)),
375        ("ASSIGN_OP", owned(sets::ASSIGN_OP)),
376        ("BINARY_OP", owned(sets::BINARY_OP)),
377        ("INCDEC", owned(sets::INCDEC)),
378        ("UNARY_OP", owned(sets::UNARY_OP)),
379        ("MEMBER_NAME", owned(sets::MEMBER_NAME)),
380        ("STORAGE_STD", owned(sets::STORAGE_STD)),
381        ("STORAGE_EXT", owned(sets::STORAGE_EXT)),
382        ("SPEC_KEYWORD", owned(sets::SPEC_KEYWORD)),
383        ("SPEC_KEYWORD_EXT", owned(sets::SPEC_KEYWORD_EXT)),
384        ("PAREN_SPEC", owned(sets::PAREN_SPEC)),
385        ("PAREN_SPEC_EXT", owned(sets::PAREN_SPEC_EXT)),
386        ("PTR_QUALIFIER", owned(sets::PTR_QUALIFIER)),
387        ("PTR_QUALIFIER_EXT", owned(sets::PTR_QUALIFIER_EXT)),
388        ("ASM_KEYWORD", owned(sets::ASM_KEYWORD)),
389        ("JUXTAPOSED", owned(sets::JUXTAPOSED)),
390        ("KW_TOKEN", tokens::keyword_token_names()),
391        (
392            "SIZEOF_KW",
393            sets::SIZEOF_KW.iter().map(|n| n.to_string()).collect(),
394        ),
395    ];
396
397    let matcher_tins = tins.clone();
398    parser
399        .set_options(move |options: &mut Options| {
400            options.fixed.lex = false;
401            options.space.lex = false;
402            options.line.lex = false;
403            options.text.lex = false;
404            options.number.lex = false;
405            options.string.lex = false;
406            options.comment.lex = false;
407            options.value.lex = false;
408            options.match_lex = true;
409
410            for (name, members) in &token_sets {
411                let members: Vec<i32> = members
412                    .iter()
413                    .map(|member| {
414                        options
415                            .token(member)
416                            .unwrap_or_else(|| options.register_token(member.clone()))
417                    })
418                    .collect();
419                options.token_set.insert((*name).to_string(), members);
420            }
421
422            for (name, order) in matchers::MATCHER_ORDER {
423                options.lex.matchers.insert(
424                    (*name).to_string(),
425                    LexMatcher {
426                        name: (*name).to_string(),
427                        order: *order,
428                        matcher: None,
429                        imperative: Some(matchers::make(name, matcher_tins.clone())),
430                        factory: None,
431                    },
432                );
433            }
434
435            // The C punctuator identities must come FIRST in the fixed
436            // table. `Tabnas::fixed(source)` answers with the first
437            // entry carrying that source, and the base grammar already
438            // registers `,`, `:`, `[`, `]`, `{` and `}` under its own
439            // names; the expr plugin resolves each operator's source
440            // through that lookup, so without this it would bind the
441            // comma operator to the base grammar's `#CA` and wait for a
442            // token this lexer never emits. The canonical engine's
443            // source-to-identity map is written last-wins and the C
444            // tokens are registered last, which is the same answer.
445            let mut ordered: IndexMap<String, tabnas::FixedToken> = IndexMap::new();
446            for (name, token) in options.fixed.tokens.iter() {
447                if name.starts_with("#PUNC_") || name.starts_with("#KW_") {
448                    ordered.insert(name.clone(), token.clone());
449                }
450            }
451            for (name, token) in options.fixed.tokens.iter() {
452                if !ordered.contains_key(name) {
453                    ordered.insert(name.clone(), token.clone());
454                }
455            }
456            options.fixed.tokens = ordered;
457
458            options.rule.start = "translation_unit".to_string();
459            options.rule.finish = false;
460        })
461        .map_err(|error| PluginError(format!("c: options: {}", error.0)))?;
462
463    // Every parse starts from a clean symbol table, macro table, lexer
464    // mode and tree arena. The canonical plugin installs a `cmeta`
465    // object on `ctx.meta` from the same hook.
466    parser
467        .set_options(|options: &mut Options| {
468            options
469                .parse
470                .prepare
471                .push(tabnas::ParsePrepare::Context(std::sync::Arc::new(
472                    |context: &mut tabnas::Context| {
473                        state::reset();
474                        seed_from_meta(&context.meta);
475                    },
476                )));
477        })
478        .map_err(|error| PluginError(format!("c: prepare: {}", error.0)))?;
479
480    // The sub-lex hook. See `crate::trivia`.
481    parser.subscribe_lex(|token, _rule, _context| trivia::on_lex_token(token));
482
483    Ok(())
484}
485
486/// Parse the embedded grammar text into a serialized document, as the
487/// canonical `parseGrammar` does with a vanilla jsonic instance, strip
488/// the extension rules in plain mode, and give the rules below
489/// `external_declaration` the armed fallback.
490fn grammar_document(
491    options: &COptions,
492) -> Result<(serde_json::Value, fallback::Fallback), PluginError> {
493    let parsed = tabnas_jsonic::parse(GRAMMAR_TEXT)
494        .map_err(|error| PluginError(format!("c-grammar.jsonic: {error}")))?;
495    let mut document = parsed.to_json();
496    if !document.is_object() || document.get("rule").is_none() {
497        return Err(PluginError(
498            "c-grammar.jsonic: expected a JSON object with a `rule` table".to_string(),
499        ));
500    }
501    integral(&mut document);
502    if !options.extended {
503        if let Some(rules) = document
504            .get_mut("rule")
505            .and_then(serde_json::Value::as_object_mut)
506        {
507            for name in EXTENSION_RULES {
508                rules.remove(*name);
509            }
510        }
511    }
512    let fallback = fallback::with_fallback(&mut document);
513    Ok((document, fallback))
514}
515
516/// Install the grammar document.
517fn install_grammar(parser: &mut Tabnas, document: serde_json::Value) -> Result<(), PluginError> {
518    let spec = GrammarSpec::from_value(document).map_err(|error| PluginError(error.0))?;
519    parser
520        .grammar(&spec)
521        .map_err(|error| PluginError(error.0))?;
522    Ok(())
523}
524
525/// jsonic yields every number as a float; the grammar loader reads `b`
526/// and `n` with `as_u64`, so a whole number has to arrive as an
527/// integer.
528fn integral(value: &mut serde_json::Value) {
529    match value {
530        serde_json::Value::Number(number) => {
531            if let Some(float) = number.as_f64() {
532                if float >= 0.0 && float.fract() == 0.0 && float <= u64::MAX as f64 {
533                    *value = serde_json::Value::from(float as u64);
534                }
535            }
536        }
537        serde_json::Value::Array(items) => items.iter_mut().for_each(integral),
538        serde_json::Value::Object(entries) => entries.values_mut().for_each(integral),
539        _ => {}
540    }
541}
542
543/// The plugin, for `use_plugin`.
544pub fn plugin() -> Plugin {
545    Plugin::new(PLUGIN_NAME, |parser: &mut Tabnas, options: &Value| {
546        c(parser, &COptions::from_value(options))
547    })
548    .with_defaults(Value::object(indexmap::IndexMap::new()))
549}
550
551/// A parser carrying the jsonic base grammar and the C grammar.
552pub fn make() -> Tabnas {
553    make_with(&COptions::default())
554}
555
556/// A parser built with the given plugin options.
557pub fn make_with(options: &COptions) -> Tabnas {
558    make_on(tabnas_jsonic::make(), options)
559}
560
561/// Install the C grammar on `parser`, jsonic's base, and declare
562/// `lex.window`, so that [`Tabnas::parse_reader`] reads a reader a window
563/// at a time rather than whole (admin ADR-30). C's matchers read the
564/// source only through the window, filling it where a scan reaches its
565/// end (`matchers`), and its actions read only the tokens. The window is
566/// declared here, on the parser this crate makes whole, and not in [`c`],
567/// which a host may install beneath matchers of its own; the setting comes
568/// last, after everything the base and the grammar set.
569fn make_on(mut parser: Tabnas, options: &COptions) -> Tabnas {
570    c(&mut parser, options).expect("c: the grammar installs on a jsonic instance");
571    parser
572        .set_options(|options| options.lex.window = true)
573        .expect("lex.window sets");
574    parser
575}
576
577/// The parser a host streams a C document through: its rule passes,
578/// which C's transducer part (`alchemy/transduce.alc`) reads, are
579/// [`make`]'s, alternate for alternate and token for token, it ends a
580/// document where [`make`] does, and it keeps nothing of a declaration it
581/// has closed.
582///
583/// Its rules make the decisions [`make`]'s make, by the same handlers,
584/// which build each external declaration's nodes as [`make`]'s do, since
585/// a decision reads them (whether a line opens a conditional group, the
586/// typedef names a declaration binds). But the translation unit, a
587/// conditional group and its branches keep no declaration or branch that
588/// has closed, and as each declaration of an items loop starts, the arena
589/// lets go of the nodes, token lists and tokens the loop's earlier items
590/// made (`state::reclaim`): what a parse holds is the declaration being
591/// read, its tokens, the conditional groups open around it, and the names
592/// that decide how a token lexes (typedef names and macros). The engine
593/// bounds the rule history at three predecessors already. Its value is a
594/// translation unit with no children, not the tree: for a tree, take
595/// [`make`]. It declares `lex.window`, as [`make`] does. The counterpart of
596/// TypeScript's `makeStreaming()` and Go's `MakeStreaming`.
597pub fn make_streaming() -> Tabnas {
598    make_streaming_with(&COptions::default())
599}
600
601/// The streaming parser built with the given plugin options.
602pub fn make_streaming_with(options: &COptions) -> Tabnas {
603    let mut parser = make_on(tabnas_jsonic::make(), options);
604    // After the plugin's own prepare hook, which resets the parse state.
605    parser
606        .set_options(|options: &mut Options| {
607            options
608                .parse
609                .prepare
610                .push(tabnas::ParsePrepare::Context(std::sync::Arc::new(
611                    |_context: &mut tabnas::Context| {
612                        state::with_state(|state| state.stream = true);
613                    },
614                )));
615        })
616        .expect("the streaming parser's prepare hook sets");
617    parser
618}
619
620#[cfg(test)]
621mod reference_tests {
622    /// The grammar document names no condition or action this port does
623    /// not implement: `refs::register` stubs a name it has no handler for
624    /// with a no-op, and a no-op where TypeScript and Go run a handler is
625    /// a parse that differs from theirs.
626    #[test]
627    fn every_reference_the_grammar_names_has_a_handler() {
628        for extended in [false, true] {
629            let options = super::COptions::new().with_extended(extended);
630            let mut parser = tabnas_jsonic::make();
631            let tins = super::register_tokens(&mut parser);
632            super::apply_options(&mut parser, &tins).expect("options apply");
633            let (_, fallback) = super::grammar_document(&options).expect("grammar document");
634            let stubbed = super::refs::register(&mut parser, &options, &fallback);
635            assert!(stubbed.is_empty(), "no handler for {stubbed:?}");
636        }
637    }
638}
639
640#[cfg(test)]
641mod window_tests {
642    /// The parser's own setting wins over its base's: a base that declares
643    /// no window comes out with it, and the grammar alone declares none.
644    #[test]
645    fn a_base_without_the_window_comes_out_with_it() {
646        let mut base = tabnas_jsonic::make();
647        base.set_options(|options| options.lex.window = false)
648            .expect("lex.window sets");
649        assert!(!base.options.lex.window);
650        let mut alone = tabnas_jsonic::make();
651        alone
652            .set_options(|options| options.lex.window = false)
653            .expect("lex.window sets");
654        super::c(&mut alone, &super::COptions::default()).expect("c installs");
655        assert!(!alone.options.lex.window);
656        let parser = super::make_on(base, &super::COptions::default());
657        assert!(parser.options.lex.window);
658        assert!(super::make().options.lex.window);
659        assert!(super::parse_with(&parser, "int main(void) { return 0; }").is_ok());
660    }
661}
662
663#[cfg(test)]
664mod streaming_tests {
665    use crate::state::with_state;
666
667    /// What the arena holds once a parse ends: its nodes, tokens and token
668    /// lists.
669    fn held() -> (usize, usize, usize) {
670        with_state(|state| (state.nodes.len(), state.tokens.held(), state.lists.len()))
671    }
672
673    /// A document of `n` items, each a comment, a declaration whose
674    /// initializer links brackets, commas and a conditional's `:`, and a
675    /// function, inside an include guard when `guarded`.
676    fn document(n: usize, guarded: bool) -> String {
677        let mut out = String::new();
678        if guarded {
679            out.push_str("#ifndef GUARD\n#define GUARD 1\n");
680        }
681        for i in 0..n {
682            out.push_str(&format!(
683                "/* item {i} */\nint x{i} = f({i}, ({i} ? 1 : 2), a[{i}]);\nint g{i}(int b) {{ if (b) {{ return b + {i}; }} return 0; }}\n"
684            ));
685        }
686        if guarded {
687            out.push_str("#endif\n");
688        }
689        out
690    }
691
692    /// The streaming parser holds as much after ten times the items: the
693    /// declarations it has closed are gone from its arena, a conditional
694    /// group open around them or not, where `make()`'s holds them all.
695    #[test]
696    fn a_streaming_parse_holds_no_declaration_it_has_closed() {
697        for guarded in [false, true] {
698            let stream = crate::make_streaming();
699            stream.parse(&document(100, guarded)).expect("it parses");
700            let small = held();
701            stream.parse(&document(1000, guarded)).expect("it parses");
702            let large = held();
703            assert_eq!(small, large, "guarded {guarded}");
704            assert!(
705                small.0 < 100 && small.1 < 200,
706                "guarded {guarded}: {small:?}"
707            );
708
709            let tree = crate::make();
710            tree.parse(&document(100, guarded)).expect("it parses");
711            let whole = held();
712            tree.parse(&document(1000, guarded)).expect("it parses");
713            let ten = held();
714            assert!(
715                ten.0 > 9 * whole.0 && ten.1 > 9 * whole.1,
716                "{whole:?}, then {ten:?}"
717            );
718        }
719    }
720}
721
722/// Parse C source with a shared default parser.
723///
724/// Building a parser costs far more than a small parse, so the
725/// instance is built once and reused. For anything but a one-off call,
726/// build one with [`make`] and keep it.
727pub fn parse(source: &str) -> Result<Value, TabnasError> {
728    static DEFAULT: OnceLock<Tabnas> = OnceLock::new();
729    let parser = DEFAULT.get_or_init(make);
730    parse_with(parser, source)
731}
732
733/// Parse with a parser the caller built, realizing the tree into plain
734/// engine values.
735///
736/// A parse builds its tree in a per-thread arena and the value the
737/// engine returns is a handle into it, so a caller driving a `tabnas`
738/// instance directly must call [`realize`] on the result before the
739/// next parse on that thread. This function does it for you.
740pub fn parse_with(parser: &Tabnas, source: &str) -> Result<Value, TabnasError> {
741    let value = parser.parse(source)?;
742    realized(source, &value)
743}
744
745/// Realize a parsed tree, failing the parse when the walk ran out of
746/// depth.
747///
748/// A tree deeper than [`cst::REALIZE_DEPTH_CAP`], or one that is not a
749/// tree at all, would otherwise come back with a hole in it where the
750/// walk stopped. The engine's own budget exhaustion reports `cancel`,
751/// so a limit reached here reports the same code rather than inventing
752/// one: this package declares no error codes of its own.
753fn realized(source: &str, value: &Value) -> Result<Value, TabnasError> {
754    let realized = realize(value);
755    if cst::realize_truncated() || state::with_state(|inner| inner.gave_up) {
756        return Err(TabnasError::new("cancel", "", source, 0, 1, 1));
757    }
758    Ok(realized)
759}
760
761/// Parse with names the source never declares itself: the typedef and
762/// macro names a header would have introduced.
763///
764/// This is the Rust spelling of the canonical `jsonic.parse(src,
765/// { cmeta })` and of the Go port's `ParseMeta(src, map[string]any{
766/// "cmeta": cm})`. Without it a corpus of `#include <stdint.h>`
767/// programs parses `uint32_t` as a declared name rather than a type.
768pub fn parse_with_meta(parser: &Tabnas, source: &str, meta: &CMeta) -> Result<Value, TabnasError> {
769    let value = parser.parse_with_meta(source, meta.to_value())?;
770    realized(source, &value)
771}
772
773/// One optional alchemy translation source and its explicit entry point.
774#[derive(Clone, Copy, Debug, Eq, PartialEq)]
775pub struct TranslationPart {
776    /// The definition a host calls after linking the source.
777    pub entry: &'static str,
778    /// The source text, or `None` for an entry supplied by alchemy.
779    pub source: Option<&'static str>,
780}
781
782/// The package-local structural translation interface.
783#[derive(Clone, Copy, Debug, Eq, PartialEq)]
784pub struct TranslationParts {
785    /// The complete `tabnas.plugin.json` text.
786    pub manifest: &'static str,
787    /// An optional lift from the grammar's events to its first read shape.
788    pub lift: Option<TranslationPart>,
789    /// An optional embedding of a plain tree in the format's schema, with its reverse.
790    pub embed: Option<TranslationPart>,
791    /// An optional render from the write shape to text.
792    pub render: Option<TranslationPart>,
793    /// An optional transducer: the format's JSON events from its parser's
794    /// rule passes, for a host that reads parser events.
795    pub transduce: Option<TranslationPart>,
796}
797
798const TRANSLATION: TranslationParts = TranslationParts {
799    manifest: include_str!("../translate/manifest.json"),
800    lift: None,
801    embed: None,
802    render: Some(TranslationPart {
803        entry: "c-render",
804        source: Some(include_str!("../translate/render.alc")),
805    }),
806    transduce: Some(TranslationPart {
807        entry: "c-transduce",
808        source: Some(include_str!("../translate/transduce.alc")),
809    }),
810};
811
812/// Return the translation parts of C source: the manifest, the render that
813/// writes the reader's tree, a concrete syntax tree, back as C source that
814/// reads back as the same tree, and the transducer part, `c-transduce`,
815/// that makes the reader's tree as JSON events from the grammar's rule
816/// passes, for a host that reads parser events. There is no lift, and no
817/// embed: the tree is the reader's own shape, the schema `c`, which a host
818/// renders only from a source of the same schema or from a program that
819/// builds the tree.
820///
821/// ```
822/// let parts = tabnas_c::translate().expect("c carries translation parts");
823/// assert_eq!(parts.render.map(|part| part.entry), Some("c-render"));
824/// assert_eq!(parts.transduce.map(|part| part.entry), Some("c-transduce"));
825/// assert_eq!(parts.embed, None);
826/// ```
827#[must_use]
828pub const fn translate() -> Option<TranslationParts> {
829    Some(TRANSLATION)
830}
831
832/// The plugin's manifest, `tabnas.plugin.json`, as the repository carries
833/// it. Its `translate` object is what a host that translates reads: the
834/// shape the format is read as and written from (`tree`), the schema of
835/// that tree (`c`), the root the render needs (`object`), the file that
836/// holds the render, and the sentences that say what a written file does
837/// not keep. The crate embeds its own copy, `translate/manifest.json`,
838/// since a packaged crate holds nothing outside `rs/`;
839/// `tests/translate_test.rs` holds the copy to the file.
840///
841/// ```
842/// assert!(tabnas_c::manifest_text().contains("\"schema\": \"c\""));
843/// ```
844pub fn manifest_text() -> &'static str {
845    TRANSLATION.manifest
846}
847
848/// The render, `alchemy/render.alc`, the file the manifest's
849/// `translate.render` names: a library of alchemy definitions, with no
850/// `export`, whose entry point `c-render` writes the reader's tree's events
851/// as C source that reads back as the same tree. A host links it with its
852/// own program. The crate embeds its own copy, `translate/render.alc`, held
853/// to the file as the manifest's is.
854///
855/// ```
856/// assert!(tabnas_c::render_text().contains("def c-render [input]"));
857/// ```
858pub fn render_text() -> &'static str {
859    match TRANSLATION.render {
860        Some(part) => part.source.unwrap_or_default(),
861        None => "",
862    }
863}