synth_core/backend.rs
1//! Backend trait and registry for multi-backend compilation
2//!
3//! Every compiler backend (ARM, aWsm, wasker, w2c2) implements the `Backend`
4//! trait, allowing the CLI and verification framework to treat them uniformly.
5
6use crate::target::TargetSpec;
7use crate::wasm_decoder::DecodedModule;
8use crate::wasm_op::WasmOp;
9use crate::wsc_facts::WscFact;
10use std::collections::HashMap;
11use thiserror::Error;
12
13/// Errors from backend compilation
14#[derive(Debug, Error)]
15pub enum BackendError {
16 #[error("compilation failed: {0}")]
17 CompilationFailed(String),
18
19 #[error("backend not available: {0}")]
20 NotAvailable(String),
21
22 #[error("unsupported configuration: {0}")]
23 UnsupportedConfig(String),
24
25 #[error("external tool error: {0}")]
26 ExternalToolError(String),
27}
28
29/// Memory-bounds safety strategy. Phase 1 of `docs/binary-safety-design.md` §3.1.
30///
31/// - `Mpu`/PMP: rely on hardware (ARM MPU or RV32 PMP) — no inline check.
32/// - `Software`: emit a `CMP/BHS Trap_Handler` (ARM) or `bgeu addr, mem_size, ebreak` (RV32)
33/// before every load/store.
34/// - `Mask`: emit `AND addr, addr, #(mem_size - 1)` — only valid when memory size
35/// is a power of two. Wraps on OOB rather than trapping (fuzz-profile semantics).
36/// - `None`: no bounds enforcement.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum SafetyBounds {
39 /// No bounds check (caller assumes the WASM module is trusted)
40 #[default]
41 None,
42 /// ARM MPU / RV32 PMP — hardware enforcement, no inline guard
43 Mpu,
44 /// Software CMP/BHS (ARM) or BGEU+EBREAK (RV32) per access
45 Software,
46 /// AND-mask, requires power-of-two memory size
47 Mask,
48}
49
50impl SafetyBounds {
51 /// Parse the `--safety-bounds` argument value.
52 pub fn parse(s: &str) -> std::result::Result<Self, String> {
53 match s {
54 "none" => Ok(SafetyBounds::None),
55 "mpu" | "pmp" => Ok(SafetyBounds::Mpu),
56 "software" | "soft" => Ok(SafetyBounds::Software),
57 "mask" | "masking" => Ok(SafetyBounds::Mask),
58 other => Err(format!(
59 "unknown --safety-bounds value '{}'; expected one of: none, mpu, software, mask",
60 other
61 )),
62 }
63 }
64
65 /// String form used in the safety manifest.
66 pub fn as_str(self) -> &'static str {
67 match self {
68 SafetyBounds::None => "none",
69 SafetyBounds::Mpu => "mpu",
70 SafetyBounds::Software => "software",
71 SafetyBounds::Mask => "mask",
72 }
73 }
74}
75
76/// Configuration for a compilation run
77#[derive(Debug, Clone)]
78pub struct CompileConfig {
79 /// Optimization level (0 = none, 1 = fast, 2 = default, 3 = aggressive)
80 pub opt_level: u8,
81 /// Target specification
82 pub target: TargetSpec,
83 /// Legacy: enable software bounds checking for memory operations.
84 /// Deprecated in favor of `safety_bounds`. When set, equivalent to
85 /// `SafetyBounds::Software`. Kept for backwards compatibility with
86 /// callers that haven't migrated yet.
87 pub bounds_check: bool,
88 /// Phase-1 unified safety-bounds knob. If `bounds_check` is `true` and
89 /// this is `None`, the legacy field wins (back-compat). If both are set,
90 /// `safety_bounds` wins.
91 pub safety_bounds: SafetyBounds,
92 /// Hardware profile name (e.g. "nrf52840", "stm32f407")
93 pub hardware: String,
94 /// Skip optimization passes (direct instruction selection)
95 pub no_optimize: bool,
96 /// Use Loom-compatible optimization preset
97 pub loom_compat: bool,
98 /// Number of imported functions (calls to indices below this use Meld dispatch)
99 pub num_imports: u32,
100 /// AAPCS integer-argument count per function, indexed by full WASM function
101 /// index (imports first, then locals). Lets `Call` marshal the right number
102 /// of operand-stack values into R0–R3 (issue #195). Empty = pass no args
103 /// (pre-#195 behaviour).
104 pub func_arg_counts: Vec<u32>,
105 /// AAPCS integer-argument count per function type, indexed by type index.
106 /// Used by `call_indirect` (issue #195).
107 pub type_arg_counts: Vec<u32>,
108 /// Produce relocatable (ET_REL) host-link output. When set, the backend
109 /// uses the direct instruction selector (`select_with_stack`) rather than
110 /// the optimized path: the optimizer materializes an *absolute* linear-
111 /// memory base (0x20000100) and does not preserve caller-saved registers
112 /// across calls, both wrong for a host-linked object where the linmem base
113 /// is supplied via `fp` at runtime and callees follow AAPCS. Imports are
114 /// also emitted as direct `func_N` BLs (resolved to the wasm field name)
115 /// instead of `__meld_dispatch_import`. (#197 — follow-up to #188/#171.)
116 pub relocatable: bool,
117
118 /// #237: emit wasm function-static data as a base-independent `.data`
119 /// section (`__synth_wasm_data`) addressed via MOVW/MOVT symbol relocations,
120 /// so a host-pointer drop-in (linmem base = 0 for native `*ptr` derefs)
121 /// doesn't mis-resolve the statics. Off by default — only the leaves'
122 /// base-relative `[R11+const]` path is used unless explicitly requested.
123 pub native_pointer_abi: bool,
124
125 /// #237: wasm linear-memory minimum size in bytes — the full static-data
126 /// extent (initialized `(data)` segments plus the zero-init/BSS region).
127 /// Under `native_pointer_abi`, a const memory address below this is a wasm
128 /// static → symbol-relative; any address beyond it is a runtime host pointer
129 /// → `[R11=0 + addr]`.
130 pub linear_memory_bytes: u32,
131
132 /// #237: the wasm stack-pointer global as `(index, init_value)`, if the
133 /// module has one. Under `native_pointer_abi` the backend register-promotes
134 /// it: `global.get` materializes `__synth_wasm_data + init` (the real stack
135 /// top) and the init value doubles as the static-data base that separates
136 /// pointer consts (`>= init`) from frame-size scalars (`< init`).
137 pub stack_pointer_global: Option<(u32, i32)>,
138 /// #311: per-function (full index) / per-type "returns i64" — the call
139 /// lowering must tag i64 results as a register pair or the hi half is
140 /// invisible to liveness.
141 pub func_ret_i64: Vec<bool>,
142 pub type_ret_i64: Vec<bool>,
143 /// #643: byte width of each defined global's storage slot, indexed by
144 /// global index — 4 for i32/f32, 8 for i64/f64, 16 for v128 (from the
145 /// module's global section). The globals table is laid out by SUMMING
146 /// these widths: an i64 global needs a register-PAIR store/load at
147 /// `[R9, off]`/`[R9, off+4]`, and every later global's offset shifts.
148 /// Empty ⇒ every global assumed 4 bytes (the legacy `idx * 4` layout;
149 /// hand-built op streams and i32-only modules are byte-identical).
150 pub global_widths: Vec<u32>,
151 /// #359: declared parameter widths per *function* (full index, imports
152 /// first): `func_params_i64[f][k]` is true when param `k` of function `f` is
153 /// i64/f64. The AAPCS stack-argument path needs the *declared* widths
154 /// (op-stream inference can't see an unused i64 param that still shifts the
155 /// incoming-stack layout). The source of truth — a per-function driver loop
156 /// (`compile_module` / the CLI loop) indexes it by `func.index` and copies
157 /// the slice into [`current_func_params_i64`] before each `compile_function`.
158 /// Empty → every param assumed i32 (the legacy path; keeps every function
159 /// with <=4 params, or all-i32 params, byte-identical).
160 pub func_params_i64: Vec<Vec<bool>>,
161 /// #359: declared parameter widths of the function CURRENTLY being compiled
162 /// — `current_func_params_i64[k]` is true when param `k` is i64/f64. Set per
163 /// function (a cheap clone of the config) from [`func_params_i64`] by the
164 /// driver loop, because `compile_function` is shared across backends and
165 /// carries no function index. Empty → assume i32.
166 pub current_func_params_i64: Vec<bool>,
167 /// #457: DECLARED parameter count of the function CURRENTLY being compiled,
168 /// from the module's type section (`func_arg_counts[func.index]`). Set per
169 /// function by the driver loops like [`current_func_params_i64`].
170 ///
171 /// The backends otherwise INFER the param count from local-access patterns
172 /// (`count_params`: a local whose first access is a read is assumed to be a
173 /// param) — which cannot distinguish a param from a read-before-write
174 /// non-param local. WASM zero-initializes non-param locals, so such a local
175 /// must read 0; the inference instead homed it in a parameter register and
176 /// read caller garbage (#457). The backends cap the inferred count at this
177 /// declared count when it is present, which reclassifies exactly the
178 /// read-before-write locals (an inferred count can only exceed the declared
179 /// one via a read-first index >= the declared count) and leaves every other
180 /// function's codegen byte-identical.
181 ///
182 /// `None` → declared signature unknown (hand-built op streams, direct
183 /// `compile_function` callers) → pure inference, the legacy behaviour.
184 pub current_func_param_count: Option<u32>,
185 /// #509: blocktype-arity side-table of the function CURRENTLY being compiled
186 /// — `(param_count, result_count)` of the k-th `Block`/`Loop`/`If` in its op
187 /// stream (ordinal-keyed; see [`FunctionOps::block_arity`]). Set per function
188 /// by the driver loop (like [`current_func_params_i64`]). The direct selector
189 /// uses it to land a value carried by `br`/`br_if`/`br_table` in the target
190 /// block's designated result register instead of dropping it. Empty → every
191 /// block treated as void (the legacy lowering; hand-built op streams).
192 ///
193 /// [`FunctionOps::block_arity`]: crate::wasm_decoder::FunctionOps::block_arity
194 pub current_func_block_arity: Vec<(u8, u8)>,
195
196 /// #543 Phase 1 — integrator-marked volatile linear-memory segments (the DMA
197 /// transfer window). Each range `[base, base+len)` names a region of the fused
198 /// linear memory that an EXTERNAL agent (the DMA engine, modelled by gale as a
199 /// Component-Model `own<buffer>` handoff — gale decision `DD-DMA-REGION-001`,
200 /// gale#124) rewrites out-of-band. Loads and stores whose address falls inside
201 /// a marked range must eventually be treated as VOLATILE: not cached, hoisted,
202 /// or reordered across the transfer boundary.
203 ///
204 /// PHASE-2 CONTRACT (implemented — issue #543): the optimizer's
205 /// address-caching passes HONOR these ranges. Consumption points:
206 /// - the #468 base-CSE / const-address-fold
207 /// (`optimizer_bridge::plan_base_cse`, DEFAULT-ON, opt-out
208 /// `SYNTH_BASE_CSE=0`): a const-address access whose 4-byte window
209 /// intersects a marked range is EXCLUDED from the fold set — it keeps
210 /// its verbatim per-access materialize-and-access codegen, while
211 /// accesses outside the range still fold;
212 /// - const-CSE (`liveness::apply_const_cse` wired in `arm_backend.rs`,
213 /// DEFAULT-ON, opt-out `SYNTH_CONST_CSE=0`; the former bridge-level
214 /// inline cache is retired, #242): declines WHOLESALE while any range is
215 /// marked — a cached constant cannot be classified address-vs-data at
216 /// that level, so the conservative stance for statically-unknown
217 /// addressing is to re-materialize every constant at each occurrence.
218 ///
219 /// Passes that only touch SP-relative frame slots (stack-reload forwarding,
220 /// frame-slot DCE, spill re-choice) are unaffected by design: these ranges
221 /// are LINEAR-MEMORY addresses, and frame slots are never linmem. Nothing on
222 /// the pipeline deletes, forwards, or reorders a linear-memory access (IR CSE
223 /// deliberately never CSEs `MemLoad`s; DCE removes only unreachable blocks),
224 /// so every marked access is issued verbatim, in program order.
225 ///
226 /// Empty (the default): zero behavior change by construction — every gate
227 /// reduces to the pre-#543 path, so the emitted `.text` is byte-identical
228 /// with or without this code (the frozen-codegen gate holds). See rivet
229 /// `VCR-DMA-001`.
230 pub volatile_segments: Vec<VolatileRange>,
231
232 /// VCR-PERF-002 Phase 1 (#494) — proven invariants forwarded by loom in
233 /// the `wsc.facts` custom section (encoding:
234 /// `docs/design/wsc-facts-encoding.md`; program:
235 /// `docs/design/proof-carrying-specialization.md`), whole-module table
236 /// keyed by `(func_index, value_id)`. The compile driver copies the
237 /// current function's slice into [`current_func_facts`] (the
238 /// `func_params_i64` → `current_func_params_i64` pattern), because
239 /// `compile_function` carries no function index.
240 ///
241 /// PHASE-1 CONTRACT: threaded but NOT consumed — no codegen path reads
242 /// facts, so emitted bytes are unchanged whether or not the module
243 /// carries the section (locked by `wsc_facts_ingestion_494.rs`). Phase 2
244 /// turns each fact into a premise for a flag-gated (`SYNTH_FACT_SPEC`),
245 /// per-elision ordeal-validated specialization; the facts-absent compile
246 /// stays byte-identical by construction (empty ⇒ every gate vacuous).
247 ///
248 /// [`current_func_facts`]: CompileConfig::current_func_facts
249 pub wsc_facts: Vec<WscFact>,
250 /// VCR-PERF-002 Phase 1 (#494): the `wsc.facts` invariants of the function
251 /// CURRENTLY being compiled (`fact.func_index == func.index`), set per
252 /// function by the driver loops like [`current_func_params_i64`]. This is
253 /// the field a Phase-2 selector pass will read its premises from. Empty →
254 /// no facts → no specialization may ever fire (the fail-safe default).
255 ///
256 /// [`current_func_params_i64`]: CompileConfig::current_func_params_i64
257 pub current_func_facts: Vec<WscFact>,
258 /// VCR-PERF-002 Phase 2b (#494, divisor-nonzero): op indices (into the op
259 /// stream passed to `compile_function`) of `div`/`rem` ops whose
260 /// DIVIDE-BY-ZERO trap guard is proven dead — the fact-spec pass
261 /// discharged `UNSAT(P ∧ divisor == 0)` per site through the
262 /// certificate-checked ordeal solver BEFORE the driver set this field.
263 /// Consumed by the ARM direct selector (`select_with_stack`); every other
264 /// path ignores it (guards stay — sound). Empty (the default) ⇒ every
265 /// guard is emitted, byte-identical to today.
266 pub fact_div_zero_elide: Vec<usize>,
267 /// VCR-PERF-002 Phase 2b (#494): op indices of `div_s` ops whose
268 /// `INT_MIN / -1` OVERFLOW trap guard is proven dead — a SEPARATE
269 /// obligation (`UNSAT(P ∧ dividend == INT_MIN ∧ divisor == -1)`). A
270 /// divisor-nonzero fact alone NEVER lands here: divisor ≠ 0 does not
271 /// exclude -1 (#633/#634 two-guard distinction). Empty ⇒ guard emitted.
272 pub fact_div_ovf_elide: Vec<usize>,
273 /// #642: `call_indirect` guard inputs — the compile-time table size for
274 /// the runtime bounds check and the per-expected-type closed-world type
275 /// verdicts — computed from the decoded module by
276 /// [`crate::wasm_decoder::DecodedModule::call_indirect_guards`] and set by
277 /// the driver loops. The default (`table_size: None`, empty verdicts)
278 /// DECLINES every `call_indirect` lowering: an unchecked indirect branch
279 /// is never emitted (WASM Core §4.4.8 requires OOB/type-mismatch traps).
280 pub call_indirect_guards: crate::wasm_decoder::CallIndirectGuards,
281}
282
283/// #543 — an integrator-marked volatile linear-memory segment (the DMA transfer
284/// window): the half-open byte range `[base, base + len)` of the fused linear
285/// memory that an external agent rewrites out-of-band. Parsed from the CLI
286/// `--volatile-segment <base>:<len>` flag. See [`CompileConfig::volatile_segments`]
287/// for the Phase-1/Phase-2 split.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub struct VolatileRange {
290 /// Start address of the volatile region, in linear-memory bytes.
291 pub base: u32,
292 /// Length of the volatile region, in bytes. The region is `[base, base+len)`.
293 pub len: u32,
294}
295
296impl CompileConfig {
297 /// Resolve the effective safety-bounds setting, honouring the legacy
298 /// `bounds_check` field as a fallback. Used by backends to pick the
299 /// inline-check shape.
300 pub fn effective_safety_bounds(&self) -> SafetyBounds {
301 match (self.safety_bounds, self.bounds_check) {
302 (SafetyBounds::None, true) => SafetyBounds::Software,
303 (s, _) => s,
304 }
305 }
306}
307
308impl Default for CompileConfig {
309 fn default() -> Self {
310 Self {
311 opt_level: 2,
312 target: TargetSpec::cortex_m4(),
313 bounds_check: false,
314 safety_bounds: SafetyBounds::None,
315 hardware: String::new(),
316 no_optimize: false,
317 loom_compat: false,
318 num_imports: 0,
319 func_arg_counts: Vec::new(),
320 type_arg_counts: Vec::new(),
321 relocatable: false,
322 native_pointer_abi: false,
323 linear_memory_bytes: 0,
324 stack_pointer_global: None,
325 func_ret_i64: Vec::new(),
326 type_ret_i64: Vec::new(),
327 // #643: empty ⇒ legacy all-4-byte global slots (i32-only modules).
328 global_widths: Vec::new(),
329 func_params_i64: Vec::new(),
330 current_func_params_i64: Vec::new(),
331 // #457: None ⇒ declared signature unknown ⇒ param-count inference
332 // only (unit tests / hand-built op streams); driver loops fill it.
333 current_func_param_count: None,
334 // #509: empty ⇒ legacy void-block lowering (unit tests / hand-built
335 // op streams); the driver loops fill it per function.
336 current_func_block_arity: Vec::new(),
337 // #543 Phase 1: no volatile segments unless the CLI flag names them.
338 // Empty ⇒ inert ⇒ emitted bytes unchanged.
339 volatile_segments: Vec::new(),
340 // VCR-PERF-002 Phase 1 (#494): no facts unless the module carries
341 // a parseable `wsc.facts` section. Empty ⇒ inert (and Phase 1 has
342 // no consumer anyway) ⇒ emitted bytes unchanged.
343 wsc_facts: Vec::new(),
344 current_func_facts: Vec::new(),
345 // VCR-PERF-002 Phase 2b (#494): no guard-elision marks unless the
346 // fact-spec pass discharged the per-site obligations. Empty ⇒
347 // every div/rem trap guard is emitted, byte-identical.
348 fact_div_zero_elide: Vec::new(),
349 fact_div_ovf_elide: Vec::new(),
350 // #642: no guard inputs ⇒ every call_indirect lowering declines
351 // loudly (never an unchecked indirect branch). Driver loops fill
352 // this from the decoded module.
353 call_indirect_guards: crate::wasm_decoder::CallIndirectGuards::default(),
354 }
355 }
356}
357
358/// A relocation entry produced during compilation
359///
360/// Records that a BL instruction at `offset` bytes into the function's code
361/// targets an external symbol (e.g., `__meld_dispatch_import`). The linker
362/// resolves these when combining the Synth object with the Kiln bridge.
363#[derive(Debug, Clone, Copy, PartialEq, Eq)]
364pub enum RelocKind {
365 /// R_ARM_THM_CALL — a Thumb BL call site (the default; #167).
366 ThmCall,
367 /// R_ARM_MOVW_ABS_NC — the MOVW half of a symbol-relative address (#237).
368 MovwAbs,
369 /// R_ARM_MOVT_ABS — the MOVT half of a symbol-relative address (#237).
370 MovtAbs,
371 /// R_ARM_ABS32 — a 32-bit absolute address held in a `.text` literal-pool
372 /// word, loaded via `LDR rX, [pc, #off]` (#345). The link-survivable
373 /// replacement for the inline-immediate MOVW/MOVT-ABS pair: `ld`/bfd patches
374 /// the data word at link time (`S + A`, the addend living in the word, REL
375 /// semantics), which survives placement into a large multi-object image —
376 /// whereas an inline-instruction MOVW_ABS immediate can be mangled.
377 Abs32,
378}
379
380#[derive(Debug, Clone, PartialEq, Eq)]
381pub struct CodeRelocation {
382 /// Byte offset within the function's machine code where the reloc applies
383 pub offset: u32,
384 /// Target symbol name (e.g., "__meld_dispatch_import", "__synth_wasm_data")
385 pub symbol: String,
386 /// Which ARM relocation type to emit for this site.
387 pub kind: RelocKind,
388}
389
390/// VCR-DBG-001: a per-instruction source map — `(machine_offset_within_code,
391/// wasm_op_index)` pairs, one per emitted machine instruction. A `None` op-index
392/// marks an instruction with no originating wasm op (prologue/epilogue, literal
393/// pool). Consumed by the DWARF `.debug_line` emitter; empty when no source map
394/// was produced.
395pub type LineMap = Vec<(u32, Option<usize>)>;
396
397/// A single compiled function
398#[derive(Debug, Clone)]
399pub struct CompiledFunction {
400 /// Function name (from WASM export or generated)
401 pub name: String,
402 /// Raw machine code bytes
403 pub code: Vec<u8>,
404 /// Original WASM ops (retained for verification)
405 pub wasm_ops: Vec<WasmOp>,
406 /// Relocations for external symbol references (BL to bridge functions)
407 pub relocations: Vec<CodeRelocation>,
408 /// VCR-DBG-001: per-instruction source map for DWARF `.debug_line` emission —
409 /// `(machine_offset_within_code, wasm_op_index)` captured at encode time, one
410 /// entry per emitted machine instruction. A `None` op-index marks an
411 /// instruction with no originating wasm op (prologue/epilogue, literal-pool
412 /// word). This is purely additive metadata: it is never serialized unless
413 /// `.debug_line` emission is requested, so the emitted `.text` is
414 /// byte-identical with or without it. Empty for backends/paths that do not
415 /// yet produce a source map (RISC-V, the optimized ARM path).
416 pub line_map: LineMap,
417}
418
419/// Result of compiling a full module
420#[derive(Debug)]
421pub struct CompilationResult {
422 /// Compiled functions
423 pub functions: Vec<CompiledFunction>,
424 /// Complete ELF binary (if backend produces one directly)
425 pub elf: Option<Vec<u8>>,
426 /// Name of the backend that produced this result
427 pub backend_name: String,
428}
429
430/// What a backend can and cannot do
431#[derive(Debug, Clone)]
432pub struct BackendCapabilities {
433 /// Backend produces complete ELF files (external backends like aWsm)
434 pub produces_elf: bool,
435 /// Backend supports per-rule verification (only our custom ARM backend)
436 pub supports_rule_verification: bool,
437 /// Backend supports binary-level verification (all backends via disassembly)
438 pub supports_binary_verification: bool,
439 /// Backend is an external tool (not a library)
440 pub is_external: bool,
441}
442
443/// Trait that every compilation backend implements
444pub trait Backend: Send + Sync {
445 /// Human-readable backend name
446 fn name(&self) -> &str;
447
448 /// What this backend can do
449 fn capabilities(&self) -> BackendCapabilities;
450
451 /// Which targets this backend supports
452 fn supported_targets(&self) -> Vec<TargetSpec>;
453
454 /// Compile an entire decoded WASM module
455 fn compile_module(
456 &self,
457 module: &DecodedModule,
458 config: &CompileConfig,
459 ) -> std::result::Result<CompilationResult, BackendError>;
460
461 /// Compile a single function from WASM ops to machine code
462 fn compile_function(
463 &self,
464 name: &str,
465 ops: &[WasmOp],
466 config: &CompileConfig,
467 ) -> std::result::Result<CompiledFunction, BackendError>;
468
469 /// Check if this backend is available (external tools installed, etc.)
470 fn is_available(&self) -> bool;
471}
472
473/// Registry of available backends
474pub struct BackendRegistry {
475 backends: HashMap<String, Box<dyn Backend>>,
476}
477
478impl BackendRegistry {
479 pub fn new() -> Self {
480 Self {
481 backends: HashMap::new(),
482 }
483 }
484
485 /// Register a backend under its name
486 pub fn register(&mut self, backend: Box<dyn Backend>) {
487 let name = backend.name().to_string();
488 self.backends.insert(name, backend);
489 }
490
491 /// Get a backend by name
492 pub fn get(&self, name: &str) -> Option<&dyn Backend> {
493 self.backends.get(name).map(|b| b.as_ref())
494 }
495
496 /// List all registered backends
497 pub fn list(&self) -> Vec<&dyn Backend> {
498 self.backends.values().map(|b| b.as_ref()).collect()
499 }
500
501 /// List backends that are actually available (installed and working)
502 pub fn available(&self) -> Vec<&dyn Backend> {
503 self.backends
504 .values()
505 .filter(|b| b.is_available())
506 .map(|b| b.as_ref())
507 .collect()
508 }
509}
510
511impl Default for BackendRegistry {
512 fn default() -> Self {
513 Self::new()
514 }
515}
516
517#[cfg(test)]
518mod tests {
519 use super::*;
520
521 #[test]
522 fn test_registry_empty() {
523 let reg = BackendRegistry::new();
524 assert!(reg.list().is_empty());
525 assert!(reg.available().is_empty());
526 assert!(reg.get("arm").is_none());
527 }
528
529 #[test]
530 fn test_compile_config_default() {
531 let config = CompileConfig::default();
532 assert_eq!(config.opt_level, 2);
533 assert!(!config.bounds_check);
534 assert_eq!(config.safety_bounds, SafetyBounds::None);
535 assert!(!config.no_optimize);
536 }
537
538 #[test]
539 fn safety_bounds_parse_round_trip() {
540 for s in ["none", "mpu", "software", "mask"] {
541 let sb = SafetyBounds::parse(s).unwrap();
542 assert_eq!(sb.as_str(), s);
543 }
544 assert_eq!(SafetyBounds::parse("pmp").unwrap(), SafetyBounds::Mpu);
545 assert_eq!(SafetyBounds::parse("soft").unwrap(), SafetyBounds::Software);
546 assert!(SafetyBounds::parse("nonsense").is_err());
547 }
548
549 #[test]
550 fn effective_safety_bounds_legacy_promotes_to_software() {
551 let cfg = CompileConfig {
552 bounds_check: true,
553 ..Default::default()
554 };
555 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Software);
556 }
557
558 #[test]
559 fn effective_safety_bounds_new_field_wins() {
560 let cfg = CompileConfig {
561 bounds_check: true,
562 safety_bounds: SafetyBounds::Mpu,
563 ..Default::default()
564 };
565 assert_eq!(cfg.effective_safety_bounds(), SafetyBounds::Mpu);
566 }
567}