chipi_core/config.rs
1//! Configuration types for chipi code generation.
2//!
3//! Defines the TOML config schema (`chipi.toml`) and the target types
4//! that carry all settings for code generation runs.
5
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8
9use serde::{Deserialize, Serialize};
10
11/// Top-level chipi.toml configuration.
12///
13/// A single config file can define multiple generation targets of both kinds.
14#[derive(Debug, Clone, Default, Deserialize, Serialize)]
15pub struct ChipiConfig {
16 /// Decoder/disassembler generation targets.
17 #[serde(rename = "gen", default)]
18 pub targets: Vec<GenTarget>,
19
20 /// Emulator dispatch LUT generation targets.
21 #[serde(default)]
22 pub lut: Vec<LutTarget>,
23}
24
25/// A single decoder/disassembler code generation target.
26#[derive(Debug, Clone, Deserialize, Serialize)]
27pub struct GenTarget {
28 /// Path to the input `.chipi` file.
29 /// Relative paths are resolved from the TOML file's directory.
30 /// Supports `$VAR` / `${VAR}` environment variable expansion (e.g. `$OUT_DIR`).
31 pub input: String,
32
33 /// Target language backend. Currently only `"rust"` is supported.
34 pub lang: String,
35
36 /// Output file path.
37 /// Relative paths are resolved from the TOML file's directory.
38 /// Supports `$VAR` / `${VAR}` environment variable expansion (e.g. `$OUT_DIR`).
39 pub output: String,
40
41 /// Whether to run a language-appropriate formatter on the output.
42 #[serde(default)]
43 pub format: bool,
44
45 /// Default dispatch strategy for all decoders/sub-decoders.
46 #[serde(default)]
47 pub dispatch: Dispatch,
48
49 /// Per-decoder dispatch strategy overrides.
50 #[serde(default)]
51 pub dispatch_overrides: HashMap<String, Dispatch>,
52
53 /// Type mappings: chipi type name -> language-specific type path.
54 #[serde(default)]
55 pub type_map: HashMap<String, String>,
56
57 /// Reserved for language-specific settings.
58 #[serde(default)]
59 pub lang_options: Option<toml::Value>,
60}
61
62impl GenTarget {
63 /// Create a new `GenTarget` with the given input, lang, and output.
64 pub fn new(input: impl Into<String>, lang: impl Into<String>, output: impl Into<String>) -> Self {
65 Self {
66 input: input.into(),
67 lang: lang.into(),
68 output: output.into(),
69 format: false,
70 dispatch: Dispatch::default(),
71 dispatch_overrides: HashMap::new(),
72 type_map: HashMap::new(),
73 lang_options: None,
74 }
75 }
76}
77
78/// A single emulator dispatch LUT generation target.
79#[derive(Debug, Clone, Deserialize, Serialize)]
80pub struct LutTarget {
81 /// Path to the input `.chipi` file.
82 /// Supports `$VAR` expansion and relative paths (resolved from the TOML file's directory).
83 pub input: String,
84
85 /// Output file path for the LUT dispatch code.
86 /// Supports `$VAR` expansion (e.g. `$OUT_DIR/lut.rs`).
87 pub output: String,
88
89 /// Rust module path where handler functions live.
90 pub handler_mod: String,
91
92 /// Mutable context type passed to every handler.
93 pub ctx_type: String,
94
95 /// Dispatch strategy.
96 #[serde(default)]
97 pub dispatch: Dispatch,
98
99 /// Instruction groups: group name -> list of instruction names.
100 /// Instructions in a group share one const-generic handler function.
101 #[serde(default)]
102 pub groups: HashMap<String, Vec<String>>,
103
104 /// Rust module path where the generated OP_* constants live.
105 /// Required when using groups so stubs can import the constants.
106 #[serde(default)]
107 pub lut_mod: Option<String>,
108
109 /// Override the type of the second handler parameter (default: width-derived u8/u16/u32).
110 /// Set to a wrapper type like `"crate::cpu::Instruction"`.
111 #[serde(default)]
112 pub instr_type: Option<String>,
113
114 /// Expression to extract the raw integer from the instr local.
115 /// Default: `"instr.0"` when `instr_type` is set, `"opcode"` otherwise.
116 #[serde(default)]
117 pub raw_expr: Option<String>,
118
119 /// Output file path for the instruction newtype with field accessors.
120 /// Supports `$VAR` expansion.
121 /// If set, generates a `pub struct Name(pub u32)` with accessor methods.
122 #[serde(default)]
123 pub instr_type_output: Option<String>,
124
125}
126
127/// Dispatch strategy for code generation.
128///
129/// Controls how decoders, sub-decoders, and emulator LUTs dispatch to handlers.
130/// The names are language-neutral; each backend maps them to the appropriate
131/// language construct.
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
133#[serde(rename_all = "snake_case")]
134pub enum Dispatch {
135 /// `#[inline(always)]` match statement (Rust), `switch` (C++), etc.
136 JumpTable,
137 /// Static function pointer lookup table.
138 #[default]
139 FnPtrLut,
140}
141
142/// Load a `ChipiConfig` from a TOML file.
143pub fn load_config(path: &Path) -> Result<ChipiConfig, ConfigError> {
144 let content = std::fs::read_to_string(path)
145 .map_err(|e| ConfigError::Io(path.to_path_buf(), e))?;
146 let config: ChipiConfig = toml::from_str(&content)
147 .map_err(|e| ConfigError::Parse(path.to_path_buf(), e))?;
148 Ok(config)
149}
150
151/// Expand environment variables (`$VAR` or `${VAR}`) in a string.
152/// Unresolved variables are left as-is.
153fn expand_env(s: &str) -> String {
154 let mut result = String::with_capacity(s.len());
155 let mut chars = s.chars().peekable();
156 while let Some(c) = chars.next() {
157 if c == '$' {
158 let braced = chars.peek() == Some(&'{');
159 if braced {
160 chars.next();
161 }
162 let mut name = String::new();
163 if braced {
164 while let Some(&c) = chars.peek() {
165 if c == '}' {
166 chars.next();
167 break;
168 }
169 name.push(c);
170 chars.next();
171 }
172 } else {
173 while let Some(&c) = chars.peek() {
174 if c.is_ascii_alphanumeric() || c == '_' {
175 name.push(c);
176 chars.next();
177 } else {
178 break;
179 }
180 }
181 }
182 if let Ok(val) = std::env::var(&name) {
183 result.push_str(&val);
184 } else if braced {
185 result.push_str(&format!("${{{}}}", name));
186 } else {
187 result.push('$');
188 result.push_str(&name);
189 }
190 } else {
191 result.push(c);
192 }
193 }
194 result
195}
196
197/// Resolve a path: expand env vars, then make relative paths relative to base_dir.
198fn resolve_path(path: &str, base_dir: &Path) -> String {
199 let expanded = expand_env(path);
200 let p = Path::new(&expanded);
201 if p.is_absolute() {
202 expanded
203 } else {
204 base_dir.join(&expanded).to_string_lossy().into_owned()
205 }
206}
207
208/// Resolve paths in a `GenTarget` relative to a base directory.
209/// Supports `$OUT_DIR`, `$CARGO_MANIFEST_DIR`, etc. in paths.
210pub fn resolve_gen_paths(target: &mut GenTarget, base_dir: &Path) {
211 target.input = resolve_path(&target.input, base_dir);
212 target.output = resolve_path(&target.output, base_dir);
213}
214
215/// Resolve paths in a `LutTarget` relative to a base directory.
216/// Supports `$OUT_DIR`, `$CARGO_MANIFEST_DIR`, etc. in paths.
217pub fn resolve_lut_paths(target: &mut LutTarget, base_dir: &Path) {
218 target.input = resolve_path(&target.input, base_dir);
219 target.output = resolve_path(&target.output, base_dir);
220 if let Some(ref mut p) = target.instr_type_output {
221 *p = resolve_path(p, base_dir);
222 }
223}
224
225#[derive(Debug)]
226pub enum ConfigError {
227 Io(PathBuf, std::io::Error),
228 Parse(PathBuf, toml::de::Error),
229}
230
231impl std::fmt::Display for ConfigError {
232 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
233 match self {
234 ConfigError::Io(path, e) => write!(f, "failed to read {}: {}", path.display(), e),
235 ConfigError::Parse(path, e) => {
236 write!(f, "failed to parse {}: {}", path.display(), e)
237 }
238 }
239 }
240}
241
242impl std::error::Error for ConfigError {}