Skip to main content

oxidized_yacc/
lib.rs

1//! # oxidized-yacc — Zainium Dynamics LALR(1) parser generator
2//!
3//! Product of **Zainium Dynamics**. Converts annotated context-free grammars
4//! (Yacc/Bison-class `.y` files) into LALR(1) parsers.
5//!
6//! ```text
7//! reader → reduce → derives/nullable → LR(0) → LALR(1) → conflicts → tables → output
8//! ```
9//!
10//! ## Library usage
11//!
12//! ```rust,no_run
13//! use oxidized_yacc::{run, config::Config};
14//! use std::path::PathBuf;
15//!
16//! let mut cfg = Config::default();
17//! cfg.grammar_file = PathBuf::from("grammar.y");
18//! cfg.header = true;
19//! cfg.verbose = true;
20//! run(&cfg).expect("oxidized-yacc failed");
21//! ```
22
23/// LR(0)/LALR(1)/canonical-LR(1)/IELR automaton construction and conflict resolution.
24pub mod automaton;
25/// Command-line argument parsing (`clap`-based) into a [`config::Config`].
26pub mod cli;
27/// Parser source/header generation for the C, C++, Java, and D skeletons.
28pub mod codegen;
29/// Shared source locations, diagnostics, and the crate's error type.
30pub mod common;
31/// Run configuration: CLI flags, `%define`s, and their resolved defaults.
32pub mod config;
33/// Grammar, symbol, state, and token data structures shared across phases.
34pub mod models;
35/// Grammar-file scanning and parsing into a [`models::Grammar`].
36pub mod parser;
37/// `*.output` / DOT / XML / HTML report rendering.
38pub mod report;
39/// LALR/LR action and goto table construction.
40pub mod tables;
41/// Small shared helpers (versioning, path defaults, array formatting).
42pub mod utils;
43
44use crate::common::{OxidizedYaccError, Diagnostics, Result};
45use crate::config::{Config, TraceFlags};
46use crate::models::{Automaton, Grammar, ParserTables};
47use std::path::PathBuf;
48use std::time::Instant;
49
50/// Full result of an oxidized-yacc run (useful for tests and tooling).
51#[derive(Debug)]
52pub struct CompileResult {
53    /// The parsed (and reduced/augmented) grammar.
54    pub grammar: Grammar,
55    /// The constructed LR automaton.
56    pub automaton: Automaton,
57    /// The generated action/goto tables.
58    pub tables: ParserTables,
59    /// Every diagnostic collected during the run.
60    pub diagnostics: Diagnostics,
61    /// Where the parser source was written, unless `--feature=syntax-only`.
62    pub source_path: Option<PathBuf>,
63    /// Where the header was written, if one was generated.
64    pub header_path: Option<PathBuf>,
65}
66
67/// Run the complete Zainium Dynamics parser-generator pipeline.
68pub fn run(config: &Config) -> Result<CompileResult> {
69    let mut config = config.clone();
70    let mut diags = Diagnostics::new();
71    let t0 = Instant::now();
72
73    if config.trace.contains(TraceFlags::TIME) || config.trace.contains(TraceFlags::GRAMMAR) {
74        eprintln!("{} {}", utils::PRODUCT, utils::version());
75    }
76
77    // 1. Read grammar
78    let t_read = Instant::now();
79    let mut grammar = parser::read_grammar(&config.grammar_file, &mut diags)?;
80    merge_grammar_into_config(&grammar, &mut config);
81    merge_config_into_grammar(&config, &mut grammar);
82    if config.trace.contains(TraceFlags::TIME) {
83        eprintln!("reader: {:?}", t_read.elapsed());
84    }
85    if config.trace.contains(TraceFlags::GRAMMAR) {
86        eprintln!("{grammar}");
87    }
88    if diags.has_errors() {
89        diags.emit_all_with_color(config.color);
90        return Err(OxidizedYaccError::Failed(diags.error_count()));
91    }
92
93    // 2–5. Automaton
94    let t_auto = Instant::now();
95    let auto_opts = automaton::AutomatonOptions {
96        lr_type: config.lr_type,
97        glr: config.glr || grammar.glr,
98    };
99    let automaton = automaton::build_automaton_with(&mut grammar, &mut diags, auto_opts);
100    if config.trace.contains(TraceFlags::TIME) {
101        eprintln!("automaton: {:?}", t_auto.elapsed());
102    }
103    if config.trace.contains(TraceFlags::AUTOMATON) {
104        eprintln!(
105            "states={} sr={} rr={} lr={:?} glr={}",
106            automaton.nstates(),
107            automaton.sr_conflicts,
108            automaton.rr_conflicts,
109            config.lr_type,
110            auto_opts.glr
111        );
112    }
113
114    // 6. Tables
115    let t_tab = Instant::now();
116    let tables = tables::generate_tables_with(
117        &grammar,
118        &automaton,
119        tables::TableOptions {
120            glr: auto_opts.glr,
121            lr_type: config.lr_type,
122        },
123    );
124    if config.trace.contains(TraceFlags::TIME) {
125        eprintln!("tables: {:?}", t_tab.elapsed());
126    }
127
128    // Reports / graph / xml / html
129    if config.resolve_report_path().is_some() {
130        report::write_report(&config, &grammar, &automaton, &tables)?;
131    }
132
133    if config.graph {
134        let path = config.graph_file.clone().unwrap_or_else(|| {
135            let mut p = config.grammar_file.clone();
136            p.set_extension("dot");
137            p
138        });
139        codegen::write_dot(&path, &grammar, &automaton)?;
140    }
141
142    if config.xml {
143        let path = config.xml_file.clone().unwrap_or_else(|| {
144            let mut p = config.grammar_file.clone();
145            p.set_extension("xml");
146            p
147        });
148        report::write_xml(&path, &grammar, &automaton)?;
149    }
150
151    if config.html {
152        let path = config.html_file.clone().unwrap_or_else(|| {
153            let mut p = config.grammar_file.clone();
154            p.set_extension("html");
155            p
156        });
157        report::write_html(&path, &config, &grammar, &automaton, &tables)?;
158    }
159
160    if diags.has_errors() {
161        diags.emit_all_with_color(config.color);
162        return Err(OxidizedYaccError::Failed(diags.error_count()));
163    }
164
165    let mut source_path = None;
166    let mut header_path = None;
167
168    if !config.syntax_only() {
169        let t_out = Instant::now();
170        let generated = codegen::generate(&config, &grammar, &automaton, &tables)?;
171        generated.write_all()?;
172        source_path = Some(generated.source_path.clone());
173        header_path = generated.header_path.clone();
174        if config.trace.contains(TraceFlags::TIME) {
175            eprintln!("output: {:?}", t_out.elapsed());
176        }
177    }
178
179    // Caret / source snippets for diagnostics
180    if config.feature.contains(config::FeatureFlags::CARET)
181        || config.feature.contains(config::FeatureFlags::ALL)
182    {
183        diags.attach_carets_from_file(&config.grammar_file);
184    }
185    diags.emit_all_with_color(config.color);
186
187    if config.warnings_as_errors && diags.warning_count() > 0 {
188        return Err(OxidizedYaccError::Message(format!(
189            "{} warning(s) treated as errors",
190            diags.warning_count()
191        )));
192    }
193
194    if config.trace.contains(TraceFlags::TIME) {
195        eprintln!("total: {:?}", t0.elapsed());
196    }
197
198    Ok(CompileResult {
199        grammar,
200        automaton,
201        tables,
202        diagnostics: diags,
203        source_path,
204        header_path,
205    })
206}
207
208/// Compile a grammar from an in-memory string (tests).
209pub fn run_str(name: &str, src: &str, mut config: Config) -> Result<CompileResult> {
210    config.grammar_file = PathBuf::from(name);
211    let mut diags = Diagnostics::new();
212    let mut grammar = parser::read_grammar_str(name, src, &mut diags)?;
213    merge_grammar_into_config(&grammar, &mut config);
214    merge_config_into_grammar(&config, &mut grammar);
215    if diags.has_errors() {
216        diags.emit_all();
217        return Err(OxidizedYaccError::Failed(diags.error_count()));
218    }
219    let auto_opts = automaton::AutomatonOptions {
220        lr_type: config.lr_type,
221        glr: config.glr || grammar.glr,
222    };
223    let automaton = automaton::build_automaton_with(&mut grammar, &mut diags, auto_opts);
224    let tables = tables::generate_tables_with(
225        &grammar,
226        &automaton,
227        tables::TableOptions {
228            glr: auto_opts.glr,
229            lr_type: config.lr_type,
230        },
231    );
232    if diags.has_errors() {
233        diags.emit_all();
234        return Err(OxidizedYaccError::Failed(diags.error_count()));
235    }
236    Ok(CompileResult {
237        grammar,
238        automaton,
239        tables,
240        diagnostics: diags,
241        source_path: None,
242        header_path: None,
243    })
244}
245
246fn merge_grammar_into_config(grammar: &Grammar, config: &mut Config) {
247    if let Some(p) = grammar.defines.get("api.prefix") {
248        let p = p.trim().trim_matches('"').trim_matches('{').trim_matches('}');
249        if !p.is_empty() {
250            config.api_prefix = Some(p.to_string());
251        }
252    }
253    if grammar.debug {
254        config.debug = true;
255    }
256    if grammar.locations {
257        config.locations = true;
258    }
259    if grammar.token_table {
260        config.token_table = true;
261    }
262    if grammar.verbose {
263        config.verbose = true;
264        if config.report.is_empty() {
265            config.report = config::ReportFlags::STATES;
266        }
267    }
268    if grammar.pure {
269        config.pure = true;
270    }
271    if grammar.glr {
272        config.glr = true;
273    }
274    if let Some(n) = grammar.expect_sr {
275        config.expect_sr = Some(n);
276    }
277    if let Some(n) = grammar.expect_rr {
278        config.expect_rr = Some(n);
279    }
280}
281
282fn merge_config_into_grammar(config: &Config, grammar: &mut Grammar) {
283    if config.debug {
284        grammar.debug = true;
285    }
286    if config.locations {
287        grammar.locations = true;
288    }
289    if config.token_table {
290        grammar.token_table = true;
291    }
292    if config.verbose {
293        grammar.verbose = true;
294    }
295    if let Some(n) = config.expect_sr {
296        grammar.expect_sr = Some(n);
297    }
298    if let Some(n) = config.expect_rr {
299        grammar.expect_rr = Some(n);
300    }
301    if config.glr {
302        grammar.glr = true;
303    }
304    if config.pure {
305        grammar.pure = true;
306    }
307}