Skip to main content

chipi_core/
lib.rs

1//! # chipi-core
2//!
3//! Core library for the chipi instruction decoder generator.
4//!
5//! This crate provides the parser, validation, IR, and code generation backends.
6//! It is consumed by `chipi-cli` (the standalone CLI tool) and `chipi-build`
7//! (the `build.rs` helper for Rust projects).
8//!
9//! ## Crate structure
10//!
11//! - [`parser`]: parses `.chipi` files into a raw AST ([`types::DecoderDef`])
12//! - [`validate`]: validates and lowers the AST into a language-agnostic IR ([`types::ValidatedDef`])
13//! - [`tree`]: builds an optimal decision tree for instruction dispatch
14//! - [`backend`]: code generation backends (currently Rust only)
15//! - [`config`]: TOML config schema and [`config::Dispatch`] enum
16//! - [`codegen`]: Rust decoder/disassembler code generation
17//! - [`lut_gen`]: Rust emulator dispatch LUT generation
18//! - [`instr_gen`]: Rust instruction newtype generation
19//!
20//! ## Quick start
21//!
22//! For `build.rs` usage, prefer `chipi-build` which wraps this library with
23//! `cargo:rerun-if-changed` support. For CLI usage, use `chipi-cli`.
24//! Use `chipi-core` directly only when you need low-level control.
25//!
26//! ```ignore
27//! // Decoder/disassembler generation
28//! chipi_core::CodegenBuilder::new("dsp.chipi")
29//!     .type_map("reg5", "crate::dsp::DspReg")
30//!     .decoder_dispatch("GcDspExt", chipi_core::Dispatch::JumpTable)
31//!     .output("out.rs")
32//!     .run()?;
33//!
34//! // Emulator dispatch LUT (programmatic)
35//! chipi_core::LutBuilder::new("cpu.chipi")
36//!     .handler_mod("crate::cpu::interpreter")
37//!     .ctx_type("crate::Cpu")
38//!     .group("alu", ["addi", "addis"])
39//!     .build_lut("out/lut.rs")?;
40//!
41//! // Emulator dispatch LUT (from chipi.toml config)
42//! let cfg = chipi_core::config::load_config(Path::new("chipi.toml"))?;
43//! for target in &cfg.lut {
44//!     chipi_core::LutBuilder::run_target(target)?;
45//! }
46//! ```
47
48pub mod backend;
49pub mod codegen;
50pub mod codegen_binja;
51pub mod codegen_cpp;
52pub mod codegen_ida;
53pub mod codegen_python;
54pub mod config;
55pub mod error;
56pub mod format_parser;
57pub mod instr_gen;
58pub mod lut_gen;
59pub mod parser;
60pub mod tree;
61pub mod types;
62pub mod validate;
63
64use std::collections::HashMap;
65use std::fs;
66use std::path::Path;
67
68use error::Errors;
69use types::DecoderDef;
70
71/// Parse a `.chipi` file from a file path and return the decoder definition.
72///
73/// # Errors
74///
75/// Returns an error if the file cannot be read or parsed.
76///
77/// # Example
78///
79/// ```ignore
80/// let def = chipi::parse("thumb.chipi")?;
81/// ```
82pub fn parse(input: &str) -> Result<DecoderDef, Box<dyn std::error::Error>> {
83    let path = Path::new(input);
84    // Use include-aware parsing from file path
85    parser::parse_file(path).map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)
86}
87
88/// Parse source text directly without reading from a file.
89///
90/// # Arguments
91///
92/// * `source`: `.chipi` source code
93/// * `filename`: name used in error messages
94pub fn parse_str(source: &str, filename: &str) -> Result<DecoderDef, Vec<error::Error>> {
95    parser::parse(source, filename)
96}
97
98/// Validate a parsed definition and write generated Rust code to a file.
99///
100/// # Errors
101///
102/// Returns validation or I/O errors.
103pub fn emit(def: &DecoderDef, output: &str) -> Result<(), Box<dyn std::error::Error>> {
104    let validated = validate::validate(def)
105        .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
106
107    let tree = tree::build_tree(&validated);
108    let code = codegen::generate_code(&validated, &tree, &HashMap::new(), &HashMap::new());
109
110    fs::write(output, code)?;
111    Ok(())
112}
113
114/// Full pipeline: parse a `.chipi` file and generate a Rust decoder.
115///
116/// # Example
117///
118/// ```ignore
119/// chipi::generate("thumb.chipi", "thumb_decoder.rs")?;
120/// ```
121pub fn generate(input: &str, output: &str) -> Result<(), Box<dyn std::error::Error>> {
122    let def = parse(input)?;
123    emit(&def, output)?;
124    Ok(())
125}
126
127/// Generate a function-pointer LUT from a `.chipi` spec file.
128///
129/// Produces a Rust source file containing:
130/// - `pub type Handler = fn(&mut Ctx, u32)`
131/// - Static dispatch tables (`_T0`, `_T1`, ...) indexed by opcode bit ranges
132/// - `pub fn dispatch(ctx: &mut Ctx, opcode: u32)`
133///
134/// `handler_mod` is the module path where handler functions live, e.g.
135/// `"crate::cpu::interpreter"`Each instruction `foo` in the spec must have
136/// a corresponding `pub fn foo(ctx: &mut Ctx, opcode: u32)` there.
137///
138/// `ctx_type` is the mutable context passed to every handler, e.g.
139/// `"crate::gekko::Gekko"`.
140///
141/// # Example (build.rs)
142///
143/// ```ignore
144/// chipi::generate_lut(
145///     "cpu.chipi",
146///     out_dir.join("cpu_lut.rs").to_str().unwrap(),
147///     "crate::cpu::interpreter",
148///     "crate::Cpu",
149/// )?;
150/// ```
151pub fn generate_lut(
152    input: &str,
153    output: &str,
154    handler_mod: &str,
155    ctx_type: &str,
156) -> Result<(), Box<dyn std::error::Error>> {
157    let def = parse(input)?;
158    let validated = validate::validate(&def)
159        .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
160    let t = tree::build_tree(&validated);
161    let code = lut_gen::generate_lut_code(
162        &validated,
163        &t,
164        handler_mod,
165        ctx_type,
166        &HashMap::new(),
167        None,
168        None,
169        Dispatch::FnPtrLut,
170    );
171    fs::write(output, code)?;
172    Ok(())
173}
174
175/// Generate an instruction newtype with field accessor methods from a `.chipi` spec.
176///
177/// Collects all unique fields across all instructions and generates a
178/// `pub struct Name(pub u32)` with one `#[inline]` accessor method per field.
179///
180/// Fields with the same name but conflicting definitions (different bit ranges
181/// or types) generate separate accessors with bit range suffixes (e.g., `d_15_0`
182/// and `d_11_0`).
183///
184/// # Example
185///
186/// ```ignore
187/// chipi::generate_instr_type("cpu.chipi", "out/instruction.rs", "Instruction")?;
188/// ```
189///
190/// Then in your code:
191///
192/// ```ignore
193/// mod cpu {
194///     include!(concat!(env!("OUT_DIR"), "/instruction.rs"));
195/// }
196/// ```
197pub fn generate_instr_type(
198    input: &str,
199    output: &str,
200    struct_name: &str,
201) -> Result<(), Box<dyn std::error::Error>> {
202    let def = parse(input)?;
203    let validated = validate::validate(&def)
204        .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
205    let (code, warnings) = instr_gen::generate_instr_type(&validated, struct_name);
206
207    // Print warnings to stderr (visible during cargo build)
208    for warning in &warnings {
209        eprintln!("warning: {}", warning);
210    }
211
212    fs::write(output, code)?;
213    Ok(())
214}
215
216/// Builder for generating a function-pointer LUT and handler stubs,
217/// with optional grouping of instructions under shared const-generic handlers.
218///
219/// Use this when you want multiple instructions to share one handler function
220/// via a `const OP: u32` generic parameter. See the crate documentation for
221/// the full pattern.
222///
223/// # Example (build.rs)
224///
225/// ```ignore
226/// chipi::LutBuilder::new("cpu.chipi")
227///     .handler_mod("crate::cpu::interpreter")
228///     .ctx_type("crate::Cpu")
229///     .lut_mod("crate::cpu::lut")
230///     .group("alu", ["addi", "addis", "ori", "oris"])
231///     .group("mem", ["lwz", "stw", "lbz", "stb"])
232///     .build_lut(out_dir.join("cpu_lut.rs").to_str().unwrap())?;
233///
234/// ```
235#[derive(Default)]
236pub struct LutBuilder {
237    input: String,
238    handler_mod: String,
239    ctx_type: String,
240    /// instruction name -> group fn name
241    instr_to_group: HashMap<String, String>,
242    /// group fn name -> instruction names (for stubs)
243    group_to_instrs: HashMap<String, Vec<String>>,
244    lut_mod: Option<String>,
245    /// Type of the second parameter of every handler (default: `u32`).
246    instr_type: Option<String>,
247    /// Expression to extract the raw `u32` from the instr local (default: `"instr.0"`
248    /// when `instr_type` is set, `"opcode"` otherwise).
249    raw_expr: Option<String>,
250    /// Dispatch strategy (default: `FnPtrLut`).
251    dispatch: Dispatch,
252    /// Sub-decoder groups: sub-decoder name -> { instr_name -> group_fn_name }
253    subdecoder_groups: HashMap<String, HashMap<String, String>>,
254}
255
256impl LutBuilder {
257    /// Create a new builder targeting the given `.chipi` spec file.
258    pub fn new(input: impl Into<String>) -> Self {
259        Self {
260            input: input.into(),
261            ..Default::default()
262        }
263    }
264
265    /// Set the Rust module path where handler functions live (e.g. `"crate::cpu::interpreter"`).
266    pub fn handler_mod(mut self, m: impl Into<String>) -> Self {
267        self.handler_mod = m.into();
268        self
269    }
270
271    /// Set the mutable context type passed to every handler (e.g. `"crate::Cpu"`).
272    pub fn ctx_type(mut self, t: impl Into<String>) -> Self {
273        self.ctx_type = t.into();
274        self
275    }
276
277    /// Set the Rust module path where the generated `OP_*` constants live
278    /// (e.g. `"crate::cpu::lut"`). Required when using groups so that stubs
279    /// can `use {lut_mod}::*` to import the constants.
280    pub fn lut_mod(mut self, path: impl Into<String>) -> Self {
281        self.lut_mod = Some(path.into());
282        self
283    }
284
285    /// Override the type of the second parameter of every handler function.
286    ///
287    /// Defaults to `u32` (raw opcode word). Set to a wrapper type such as
288    /// `"crate::cpu::semantics::Instruction"` to have handlers receive a
289    /// richer type instead. You must also call [`Self::raw_expr`] to tell
290    /// chipi how to extract the underlying `u32` for table indexing.
291    pub fn instr_type(mut self, t: impl Into<String>) -> Self {
292        self.instr_type = Some(t.into());
293        self
294    }
295
296    /// Expression that yields a `u32` from the `instr` local inside a generated
297    /// dispatch function. Only meaningful when [`Self::instr_type`] is set.
298    ///
299    /// For a newtype `struct Instruction(pub u32)` this is `"instr.0"` (the default
300    /// when `instr_type` is set). For a struct with a `raw()` method use `"instr.raw()"`.
301    pub fn raw_expr(mut self, expr: impl Into<String>) -> Self {
302        self.raw_expr = Some(expr.into());
303        self
304    }
305
306    /// Set the dispatch strategy.
307    ///
308    /// - [`Dispatch::FnPtrLut`] (default): static `[Handler; N]` arrays with indirect
309    ///   calls. Each tree level gets its own table.
310    /// - [`Dispatch::JumpTable`]: a single `#[inline(always)]` function with nested
311    ///   match statements. The compiler can inline handler calls for zero-overhead
312    ///   dispatch when handlers are also `#[inline(always)]`.
313    pub fn dispatch(mut self, strategy: Dispatch) -> Self {
314        self.dispatch = strategy;
315        self
316    }
317
318    /// Register a group: `name` is the shared handler function name (e.g. `"alu"`),
319    /// `instrs` lists the instruction names that route to it.
320    ///
321    /// Each instruction in `instrs` will appear in the LUT as
322    /// `handler_mod::alu::<{ OP_INSTR }>` instead of `handler_mod::instr`.
323    /// The generated stub is `pub fn alu<const OP: u32>(...)` with a `match OP` body.
324    pub fn group(
325        mut self,
326        name: impl Into<String>,
327        instrs: impl IntoIterator<Item = impl Into<String>>,
328    ) -> Self {
329        let name = name.into();
330        let instrs: Vec<String> = instrs.into_iter().map(|s| s.into()).collect();
331        for instr in &instrs {
332            self.instr_to_group.insert(instr.clone(), name.clone());
333        }
334        self.group_to_instrs.insert(name, instrs);
335        self
336    }
337
338    /// Create a `LutBuilder` from a [`config::LutTarget`].
339    pub fn from_config(target: &config::LutTarget) -> Self {
340        let mut builder = Self::new(&target.input)
341            .handler_mod(&target.handler_mod)
342            .ctx_type(&target.ctx_type)
343            .dispatch(target.dispatch);
344
345        if let Some(ref lut_mod) = target.lut_mod {
346            builder = builder.lut_mod(lut_mod);
347        }
348        if let Some(ref instr_type) = target.instr_type {
349            builder = builder.instr_type(instr_type);
350        }
351        if let Some(ref raw_expr) = target.raw_expr {
352            builder = builder.raw_expr(raw_expr);
353        }
354        for (name, instrs) in &target.groups {
355            builder = builder.group(name, instrs.iter().map(|s| s.as_str()));
356        }
357        // Build sub-decoder groups: sd_name -> { instr_name -> group_fn_name }
358        for (sd_name, groups) in &target.subdecoder_groups {
359            let mut instr_to_group = HashMap::new();
360            for (group_name, instrs) in groups {
361                for instr in instrs {
362                    instr_to_group.insert(instr.clone(), group_name.clone());
363                }
364            }
365            builder
366                .subdecoder_groups
367                .insert(sd_name.clone(), instr_to_group);
368        }
369        builder
370    }
371
372    /// Run all outputs defined in a [`config::LutTarget`].
373    ///
374    /// Generates the LUT file, and optionally the instruction type and stubs
375    /// if configured. Stubs are only generated if the target file does not exist.
376    pub fn run_target(target: &config::LutTarget) -> Result<(), Box<dyn std::error::Error>> {
377        let builder = Self::from_config(target);
378
379        builder.build_lut(&target.output)?;
380
381        if let Some(ref instr_output) = target.instr_type_output {
382            builder.build_instr_type(instr_output)?;
383        }
384
385        Ok(())
386    }
387
388    /// Generate the LUT source file.
389    pub fn build_lut(&self, output: &str) -> Result<(), Box<dyn std::error::Error>> {
390        let def = parse(&self.input)?;
391        let validated = validate::validate(&def)
392            .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
393        let t = tree::build_tree(&validated);
394        let mut code = lut_gen::generate_lut_code(
395            &validated,
396            &t,
397            &self.handler_mod,
398            &self.ctx_type,
399            &self.instr_to_group,
400            self.instr_type.as_deref(),
401            self.raw_expr.as_deref(),
402            self.dispatch,
403        );
404
405        // Generate dispatch functions for sub-decoders that have groups configured
406        for sd in &validated.sub_decoders {
407            if let Some(groups) = self.subdecoder_groups.get(&sd.name) {
408                code.push('\n');
409                code.push_str(&lut_gen::generate_subdecoder_dispatch(
410                    &validated,
411                    sd,
412                    &self.handler_mod,
413                    &self.ctx_type,
414                    groups,
415                ));
416            }
417        }
418
419        fs::write(output, code)?;
420        Ok(())
421    }
422
423    /// Generate an instruction newtype with field accessor methods.
424    ///
425    /// Collects all unique fields from the spec and generates a
426    /// `pub struct Name(pub u32)` with one `#[inline]` accessor per field.
427    ///
428    /// The struct name is derived from the last path segment of `.instr_type()`
429    /// (e.g., `"crate::cpu::Instruction"` -> `"Instruction"`), or defaults to
430    /// `"Instruction"` if `.instr_type()` was not called.
431    ///
432    /// Fields with conflicting definitions across instructions generate separate
433    /// accessors with bit range suffixes (e.g., `d_15_0` and `d_11_0`).
434    ///
435    /// # Example
436    ///
437    /// ```ignore
438    /// chipi::LutBuilder::new("cpu.chipi")
439    ///     .instr_type("crate::cpu::Instruction")
440    ///     .build_instr_type(out_dir.join("instruction.rs").to_str().unwrap())?;
441    /// ```
442    pub fn build_instr_type(&self, output: &str) -> Result<(), Box<dyn std::error::Error>> {
443        let def = parse(&self.input)?;
444        let validated = validate::validate(&def)
445            .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
446
447        // Derive struct name from instr_type path or default to "Instruction"
448        let struct_name = self
449            .instr_type
450            .as_deref()
451            .and_then(|t| t.rsplit("::").next())
452            .unwrap_or("Instruction");
453
454        let (code, warnings) = instr_gen::generate_instr_type(&validated, struct_name);
455
456        // Print warnings to stderr (visible during cargo build)
457        for warning in &warnings {
458            eprintln!("cargo:warning={}", warning);
459        }
460
461        fs::write(output, code)?;
462        Ok(())
463    }
464}
465
466/// Parse, validate, and generate code from source text. Returns the
467/// generated Rust code as a `String`.
468///
469/// # Errors
470///
471/// Returns parse or validation errors.
472pub fn generate_from_str(
473    source: &str,
474    filename: &str,
475) -> Result<String, Box<dyn std::error::Error>> {
476    let def = parser::parse(source, filename)
477        .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
478
479    let validated = validate::validate(&def)
480        .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
481
482    let tree = tree::build_tree(&validated);
483    let code = codegen::generate_code(&validated, &tree, &HashMap::new(), &HashMap::new());
484
485    Ok(code)
486}
487
488pub use config::Dispatch;
489
490/// Builder for generating a decoder with type mappings and dispatch strategy control.
491///
492/// Use this when you need to map chipi type names to Rust wrapper types (replacing
493/// the removed `import`/`as` syntax) or control the dispatch strategy per decoder.
494///
495/// # Example (build.rs)
496///
497/// ```ignore
498/// chipi::CodegenBuilder::new("src/gcdsp.chipi")
499///     .type_map("reg5", "crate::dsp::DspReg")
500///     .decoder_dispatch("GcDsp", chipi::Dispatch::FnPtrLut)
501///     .decoder_dispatch("GcDspExt", chipi::Dispatch::JumpTable)
502///     .output("src/generated/gcdsp.rs")
503///     .run();
504/// ```
505#[derive(Default)]
506pub struct CodegenBuilder {
507    input: String,
508    type_maps: HashMap<String, String>,
509    dispatch_overrides: HashMap<String, Dispatch>,
510    output: Option<String>,
511}
512
513impl CodegenBuilder {
514    /// Create a new builder targeting the given `.chipi` spec file.
515    pub fn new(input: impl Into<String>) -> Self {
516        Self {
517            input: input.into(),
518            ..Default::default()
519        }
520    }
521
522    /// Map a chipi type name to a Rust type path.
523    ///
524    /// Fields declared with this type name in the `.chipi` file will use the
525    /// given Rust type in generated code. The codegen emits a `use` statement
526    /// for paths containing `::`.
527    ///
528    /// # Example
529    ///
530    /// ```ignore
531    /// .type_map("reg5", "crate::dsp::DspReg")
532    /// ```
533    pub fn type_map(mut self, chipi_type: &str, rust_path: &str) -> Self {
534        self.type_maps
535            .insert(chipi_type.to_string(), rust_path.to_string());
536        self
537    }
538
539    /// Set the dispatch strategy for a specific decoder or sub-decoder.
540    ///
541    /// Defaults: `JumpTable` for sub-decoders, decision tree for main decoders.
542    pub fn decoder_dispatch(mut self, decoder_name: &str, strategy: Dispatch) -> Self {
543        self.dispatch_overrides
544            .insert(decoder_name.to_string(), strategy);
545        self
546    }
547
548    /// Set the output file path.
549    pub fn output(mut self, path: &str) -> Self {
550        self.output = Some(path.to_string());
551        self
552    }
553
554    /// Run the full pipeline: parse, validate, and generate code.
555    pub fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
556        let def = parse(&self.input)?;
557        let validated = validate::validate(&def)
558            .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
559
560        let tree = tree::build_tree(&validated);
561        let code =
562            codegen::generate_code(&validated, &tree, &self.type_maps, &self.dispatch_overrides);
563
564        if let Some(ref output) = self.output {
565            fs::write(output, code)?;
566        }
567
568        Ok(())
569    }
570}