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