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}
253
254impl LutBuilder {
255 /// Create a new builder targeting the given `.chipi` spec file.
256 pub fn new(input: impl Into<String>) -> Self {
257 Self {
258 input: input.into(),
259 ..Default::default()
260 }
261 }
262
263 /// Set the Rust module path where handler functions live (e.g. `"crate::cpu::interpreter"`).
264 pub fn handler_mod(mut self, m: impl Into<String>) -> Self {
265 self.handler_mod = m.into();
266 self
267 }
268
269 /// Set the mutable context type passed to every handler (e.g. `"crate::Cpu"`).
270 pub fn ctx_type(mut self, t: impl Into<String>) -> Self {
271 self.ctx_type = t.into();
272 self
273 }
274
275 /// Set the Rust module path where the generated `OP_*` constants live
276 /// (e.g. `"crate::cpu::lut"`). Required when using groups so that stubs
277 /// can `use {lut_mod}::*` to import the constants.
278 pub fn lut_mod(mut self, path: impl Into<String>) -> Self {
279 self.lut_mod = Some(path.into());
280 self
281 }
282
283 /// Override the type of the second parameter of every handler function.
284 ///
285 /// Defaults to `u32` (raw opcode word). Set to a wrapper type such as
286 /// `"crate::cpu::semantics::Instruction"` to have handlers receive a
287 /// richer type instead. You must also call [`Self::raw_expr`] to tell
288 /// chipi how to extract the underlying `u32` for table indexing.
289 pub fn instr_type(mut self, t: impl Into<String>) -> Self {
290 self.instr_type = Some(t.into());
291 self
292 }
293
294 /// Expression that yields a `u32` from the `instr` local inside a generated
295 /// dispatch function. Only meaningful when [`Self::instr_type`] is set.
296 ///
297 /// For a newtype `struct Instruction(pub u32)` this is `"instr.0"` (the default
298 /// when `instr_type` is set). For a struct with a `raw()` method use `"instr.raw()"`.
299 pub fn raw_expr(mut self, expr: impl Into<String>) -> Self {
300 self.raw_expr = Some(expr.into());
301 self
302 }
303
304 /// Set the dispatch strategy.
305 ///
306 /// - [`Dispatch::FnPtrLut`] (default): static `[Handler; N]` arrays with indirect
307 /// calls. Each tree level gets its own table.
308 /// - [`Dispatch::JumpTable`]: a single `#[inline(always)]` function with nested
309 /// match statements. The compiler can inline handler calls for zero-overhead
310 /// dispatch when handlers are also `#[inline(always)]`.
311 pub fn dispatch(mut self, strategy: Dispatch) -> Self {
312 self.dispatch = strategy;
313 self
314 }
315
316 /// Register a group: `name` is the shared handler function name (e.g. `"alu"`),
317 /// `instrs` lists the instruction names that route to it.
318 ///
319 /// Each instruction in `instrs` will appear in the LUT as
320 /// `handler_mod::alu::<{ OP_INSTR }>` instead of `handler_mod::instr`.
321 /// The generated stub is `pub fn alu<const OP: u32>(...)` with a `match OP` body.
322 pub fn group(
323 mut self,
324 name: impl Into<String>,
325 instrs: impl IntoIterator<Item = impl Into<String>>,
326 ) -> Self {
327 let name = name.into();
328 let instrs: Vec<String> = instrs.into_iter().map(|s| s.into()).collect();
329 for instr in &instrs {
330 self.instr_to_group.insert(instr.clone(), name.clone());
331 }
332 self.group_to_instrs.insert(name, instrs);
333 self
334 }
335
336 /// Create a `LutBuilder` from a [`config::LutTarget`].
337 pub fn from_config(target: &config::LutTarget) -> Self {
338 let mut builder = Self::new(&target.input)
339 .handler_mod(&target.handler_mod)
340 .ctx_type(&target.ctx_type)
341 .dispatch(target.dispatch);
342
343 if let Some(ref lut_mod) = target.lut_mod {
344 builder = builder.lut_mod(lut_mod);
345 }
346 if let Some(ref instr_type) = target.instr_type {
347 builder = builder.instr_type(instr_type);
348 }
349 if let Some(ref raw_expr) = target.raw_expr {
350 builder = builder.raw_expr(raw_expr);
351 }
352 for (name, instrs) in &target.groups {
353 builder = builder.group(name, instrs.iter().map(|s| s.as_str()));
354 }
355 builder
356 }
357
358 /// Run all outputs defined in a [`config::LutTarget`].
359 ///
360 /// Generates the LUT file, and optionally the instruction type and stubs
361 /// if configured. Stubs are only generated if the target file does not exist.
362 pub fn run_target(target: &config::LutTarget) -> Result<(), Box<dyn std::error::Error>> {
363 let builder = Self::from_config(target);
364
365 builder.build_lut(&target.output)?;
366
367 if let Some(ref instr_output) = target.instr_type_output {
368 builder.build_instr_type(instr_output)?;
369 }
370
371 Ok(())
372 }
373
374 /// Generate the LUT source file.
375 pub fn build_lut(&self, output: &str) -> Result<(), Box<dyn std::error::Error>> {
376 let def = parse(&self.input)?;
377 let validated = validate::validate(&def)
378 .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
379 let t = tree::build_tree(&validated);
380 let code = lut_gen::generate_lut_code(
381 &validated,
382 &t,
383 &self.handler_mod,
384 &self.ctx_type,
385 &self.instr_to_group,
386 self.instr_type.as_deref(),
387 self.raw_expr.as_deref(),
388 self.dispatch,
389 );
390 fs::write(output, code)?;
391 Ok(())
392 }
393
394 /// Generate an instruction newtype with field accessor methods.
395 ///
396 /// Collects all unique fields from the spec and generates a
397 /// `pub struct Name(pub u32)` with one `#[inline]` accessor per field.
398 ///
399 /// The struct name is derived from the last path segment of `.instr_type()`
400 /// (e.g., `"crate::cpu::Instruction"` -> `"Instruction"`), or defaults to
401 /// `"Instruction"` if `.instr_type()` was not called.
402 ///
403 /// Fields with conflicting definitions across instructions generate separate
404 /// accessors with bit range suffixes (e.g., `d_15_0` and `d_11_0`).
405 ///
406 /// # Example
407 ///
408 /// ```ignore
409 /// chipi::LutBuilder::new("cpu.chipi")
410 /// .instr_type("crate::cpu::Instruction")
411 /// .build_instr_type(out_dir.join("instruction.rs").to_str().unwrap())?;
412 /// ```
413 pub fn build_instr_type(&self, output: &str) -> Result<(), Box<dyn std::error::Error>> {
414 let def = parse(&self.input)?;
415 let validated = validate::validate(&def)
416 .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
417
418 // Derive struct name from instr_type path or default to "Instruction"
419 let struct_name = self
420 .instr_type
421 .as_deref()
422 .and_then(|t| t.rsplit("::").next())
423 .unwrap_or("Instruction");
424
425 let (code, warnings) = instr_gen::generate_instr_type(&validated, struct_name);
426
427 // Print warnings to stderr (visible during cargo build)
428 for warning in &warnings {
429 eprintln!("cargo:warning={}", warning);
430 }
431
432 fs::write(output, code)?;
433 Ok(())
434 }
435}
436
437/// Parse, validate, and generate code from source text. Returns the
438/// generated Rust code as a `String`.
439///
440/// # Errors
441///
442/// Returns parse or validation errors.
443pub fn generate_from_str(
444 source: &str,
445 filename: &str,
446) -> Result<String, Box<dyn std::error::Error>> {
447 let def = parser::parse(source, filename)
448 .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
449
450 let validated = validate::validate(&def)
451 .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
452
453 let tree = tree::build_tree(&validated);
454 let code = codegen::generate_code(&validated, &tree, &HashMap::new(), &HashMap::new());
455
456 Ok(code)
457}
458
459pub use config::Dispatch;
460
461/// Builder for generating a decoder with type mappings and dispatch strategy control.
462///
463/// Use this when you need to map chipi type names to Rust wrapper types (replacing
464/// the removed `import`/`as` syntax) or control the dispatch strategy per decoder.
465///
466/// # Example (build.rs)
467///
468/// ```ignore
469/// chipi::CodegenBuilder::new("src/gcdsp.chipi")
470/// .type_map("reg5", "crate::dsp::DspReg")
471/// .decoder_dispatch("GcDsp", chipi::Dispatch::FnPtrLut)
472/// .decoder_dispatch("GcDspExt", chipi::Dispatch::JumpTable)
473/// .output("src/generated/gcdsp.rs")
474/// .run();
475/// ```
476#[derive(Default)]
477pub struct CodegenBuilder {
478 input: String,
479 type_maps: HashMap<String, String>,
480 dispatch_overrides: HashMap<String, Dispatch>,
481 output: Option<String>,
482}
483
484impl CodegenBuilder {
485 /// Create a new builder targeting the given `.chipi` spec file.
486 pub fn new(input: impl Into<String>) -> Self {
487 Self {
488 input: input.into(),
489 ..Default::default()
490 }
491 }
492
493 /// Map a chipi type name to a Rust type path.
494 ///
495 /// Fields declared with this type name in the `.chipi` file will use the
496 /// given Rust type in generated code. The codegen emits a `use` statement
497 /// for paths containing `::`.
498 ///
499 /// # Example
500 ///
501 /// ```ignore
502 /// .type_map("reg5", "crate::dsp::DspReg")
503 /// ```
504 pub fn type_map(mut self, chipi_type: &str, rust_path: &str) -> Self {
505 self.type_maps
506 .insert(chipi_type.to_string(), rust_path.to_string());
507 self
508 }
509
510 /// Set the dispatch strategy for a specific decoder or sub-decoder.
511 ///
512 /// Defaults: `JumpTable` for sub-decoders, decision tree for main decoders.
513 pub fn decoder_dispatch(mut self, decoder_name: &str, strategy: Dispatch) -> Self {
514 self.dispatch_overrides
515 .insert(decoder_name.to_string(), strategy);
516 self
517 }
518
519 /// Set the output file path.
520 pub fn output(mut self, path: &str) -> Self {
521 self.output = Some(path.to_string());
522 self
523 }
524
525 /// Run the full pipeline: parse, validate, and generate code.
526 pub fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
527 let def = parse(&self.input)?;
528 let validated = validate::validate(&def)
529 .map_err(|errs| Box::new(Errors(errs)) as Box<dyn std::error::Error>)?;
530
531 let tree = tree::build_tree(&validated);
532 let code =
533 codegen::generate_code(&validated, &tree, &self.type_maps, &self.dispatch_overrides);
534
535 if let Some(ref output) = self.output {
536 fs::write(output, code)?;
537 }
538
539 Ok(())
540 }
541}