Skip to main content

synth_core/
wcet.rs

1//! #778 (v0.46 Wave-1 Lane 2) — the `synth-wcet-v1` static worst-case-cycle map.
2//!
3//! synth holds the EXACT final instruction sequence of every compiled function,
4//! so it is the natural owner of a SOUND static per-function worst-case execution
5//! time (WCET) bound. gale's schedulability track (spar T3/T4) computes a
6//! machine-checked response-time bound, but its per-task cost inputs (`C_i`) are
7//! only DWT high-water-marks — *observations*, not *bounds* — and a hard build
8//! gate forbids sizing budgets from DWT. This sidecar supplies the missing SOUND
9//! input: a cycle bound that is provably ≥ any real execution of the function.
10//!
11//! ## Soundness contract (the whole point)
12//!
13//! A bound that is EVER less than the real cycle count is a defect. This module
14//! is therefore deliberately conservative and DECLINES loudly rather than emit a
15//! number it cannot defend:
16//!
17//! - **Loop-free functions** get an EXACT-form bound: every instruction in the
18//!   final stream executes at most once, so the bound is the SUM of each
19//!   instruction's documented worst-case cycles. Summing every instruction
20//!   (including both arms of an `if/else`) is an over-estimate, hence sound; no
21//!   path enumeration is needed.
22//! - **Loops with statically-evident trip counts** (#778 phase 2): a canonical
23//!   counted loop — const-initialized counter, const step, const bound, single
24//!   backward branch — whose trip count synth PROVES from the final instruction
25//!   stream gets `trip × body-worst + overhead` as an upper bound; every
26//!   instruction's cost is multiplied by its proven worst-case execution count.
27//!   Nested loops multiply only when EVERY level proves.
28//! - **Everything else** — any loop synth cannot prove a trip count for
29//!   (data-dependent bounds, non-canonical shapes), any residual/external
30//!   label branch (unknown direction), any call (`Bl`/`Blx`, inter-procedural),
31//!   any op whose encoder expansion contains an internal runtime loop
32//!   (`i64` software div/rem), any unsupported core class — is DECLINED with a
33//!   machine-readable reason. gale cannot size a budget from an unsound number,
34//!   so a decline is strictly better than a guess.
35//!
36//! `--wcet-hints` (#778 phase 2, the scry seam) supplies UNTRUSTED per-loop
37//! trip-count hints; each is soundly CHECKED against synth's own induction
38//! proof before use and REJECTED with a machine reason otherwise (see
39//! [`WcetHints`] / [`WcetHintReject`]). Richer hint certificates (data-dependent
40//! bounds) and inter-procedural composition remain the named scry / spar
41//! follow-ups, explicitly OUT of scope.
42//!
43//! ## Precondition — a bound without its assumptions is not a safety input
44//!
45//! The per-instruction cycle numbers are documented worst cases for the
46//! **Cortex-M3 / Cortex-M4(F)** in-order pipeline under a **zero-wait-state**
47//! instruction memory (flash accelerator / I-cache hit). The bound is CONDITIONAL
48//! on that precondition, which is recorded in the JSON (`core_class`,
49//! `wait_states`, `memory_assumption`) so the T4 consumer knows exactly what it
50//! holds under. Cortex-M7 (dual-issue + caches with wait-states that can make
51//! actual cycles EXCEED a zero-wait straight sum) is DECLINED, not
52//! approximated — soundness over coverage.
53//!
54//! ## Schema (`synth-wcet-v1`)
55//!
56//! A JSON sidecar written next to the object (`<output>.wcet.json`). Purely
57//! additive metadata: it is derived from the already-decided instruction stream
58//! and never touches `.text`, so the emitted bytes are byte-identical whether or
59//! not the bound is emitted (frozen-safe).
60
61use serde::{Deserialize, Serialize};
62
63/// The schema version string embedded at the top of the sidecar.
64pub const SCHEMA: &str = "synth-wcet-v1";
65
66/// The schema string a `--wcet-hints` file must carry (#778 phase 2).
67pub const HINTS_SCHEMA: &str = "synth-wcet-hints-v1";
68
69/// Why a function could not receive a sound static cycle bound. Each variant is a
70/// distinct, machine-readable decline reason so a consumer (spar T4) can tell an
71/// unbounded loop from an inter-procedural edge from an unsupported core.
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(rename_all = "kebab-case")]
74pub enum WcetDecline {
75    /// A backward branch in the final instruction stream — a loop — whose trip
76    /// count synth could NOT statically prove (#778 phase 2 proves canonical
77    /// const-init/const-step/const-bound counted loops; equality-exit shapes
78    /// additionally need a verified `--wcet-hints` entry). Data-dependent
79    /// bounds remain the scry loop-bound-inference follow-up.
80    Loop,
81    /// A DIRECT call (`Bl func_N`) that could not be composed into a bound because
82    /// the callee is unbounded or unresolvable in THIS module — an external/imported
83    /// callee (a WASM import, `__meld_dispatch_import`, or an `__aeabi_*` runtime
84    /// helper: it has no per-function body in this module to sum). #778 phase 3
85    /// composes direct calls to LOCAL, bounded callees over the direct call graph;
86    /// this reason remains for the direct edges that cannot be composed.
87    Call,
88    /// A cycle in the direct call graph (self-recursion or mutual recursion). An
89    /// upper cycle bound cannot be composed from a call graph that revisits a frame
90    /// an unbounded number of times, so every function on the cycle DECLINES. This
91    /// is the #778 phase-3 decline-honesty guard: composition only bounds an acyclic
92    /// direct call graph.
93    Recursion,
94    /// An INDIRECT call (`Blx <reg>` / `call_indirect` / a function-pointer
95    /// dispatch such as `__meld_dispatch_import`): the callee is not statically
96    /// known, so its bound cannot be composed. Declined, not guessed. (#778 phase 3.)
97    IndirectCall,
98    /// A caller whose own body is bounded but that DIRECTLY calls a callee which
99    /// itself declined (transitively): a decline must PROPAGATE up the call graph —
100    /// a caller cannot be bounded while a callee it invokes is unbounded. (#778
101    /// phase 3.) The `note()` names the first unbounded callee for diagnosis.
102    CalleeUnbounded,
103    /// A residual/external label branch (`B`/`Bcc`/… still carrying a label): its
104    /// direction is not statically known here, so it cannot be proven loop-free.
105    UnresolvedBranch,
106    /// An op whose encoder expansion contains an internal RUNTIME loop (the `i64`
107    /// software div/rem shift-subtract: emitted once but executed 64×). Its body
108    /// bytes appear once in the stream, so a straight sum would undercount — a
109    /// sound bound needs a per-op `trip × body` model, a named follow-up.
110    LoopedExpansion,
111    /// The target core class is not soundly summable with a zero-wait per-op table
112    /// (Cortex-M7/M7dp: dual-issue + cache wait-states). Declined, not
113    /// approximated.
114    UnsupportedCore,
115    /// An op the cycle model has not classified. Never emitted in a released
116    /// build (the classifier is exhaustive with no wildcard) — present so the
117    /// schema can carry a conservative decline if the table is ever incomplete.
118    UnmodeledOp,
119}
120
121impl WcetDecline {
122    /// A short human-readable explanation, embedded alongside the machine reason.
123    pub fn note(&self) -> &'static str {
124        match self {
125            WcetDecline::Loop => {
126                "backward branch (loop) without a statically-proven trip count — \
127                 canonical const-bound counted loops are proven automatically; \
128                 equality-exit shapes need a verified --wcet-hints entry; \
129                 data-dependent bounds are the scry loop-bound-inference follow-up"
130            }
131            WcetDecline::Call => {
132                "direct call to an external/imported/unresolvable callee with no \
133                 per-function bound in this module — cannot compose an \
134                 inter-procedural bound (local direct calls ARE composed, #778 phase 3)"
135            }
136            WcetDecline::Recursion => {
137                "cycle in the direct call graph (self- or mutual recursion) — an \
138                 upper cycle bound cannot be composed from a recursive call graph"
139            }
140            WcetDecline::IndirectCall => {
141                "indirect call (Blx <reg> / call_indirect / function-pointer \
142                 dispatch) — the callee is not statically known, cannot compose"
143            }
144            WcetDecline::CalleeUnbounded => {
145                "a directly-called callee is itself unbounded — the decline \
146                 propagates up the call graph (a caller cannot be bounded while a \
147                 callee it invokes is unbounded)"
148            }
149            WcetDecline::UnresolvedBranch => {
150                "residual external/unresolved label branch — direction not \
151                 statically known, cannot prove loop-free"
152            }
153            WcetDecline::LoopedExpansion => {
154                "op expands to an internal runtime loop (i64 software div/rem, \
155                 executed 64×) — straight sum would undercount"
156            }
157            WcetDecline::UnsupportedCore => {
158                "core class not soundly summable with a zero-wait per-op table \
159                 (Cortex-M7 dual-issue + cache wait-states)"
160            }
161            WcetDecline::UnmodeledOp => "op not classified by the cycle model",
162        }
163    }
164}
165
166/// How a loop's trip count was established (#778 phase 2).
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168#[serde(rename_all = "kebab-case")]
169pub enum WcetLoopBoundSource {
170    /// Fully static proof: const-initialized counter, const step, const bound,
171    /// exit-guaranteeing comparison — the trip count is derived by synth alone.
172    Static,
173    /// The loop is an equality-exit shape synth only bounds under an explicit
174    /// `--wcet-hints` assertion; the hint was CHECKED against synth's own derived
175    /// trip count (divisibility + monotonicity + derived ≤ hint) before use. The
176    /// emitted trip count is still synth's DERIVED value, never the raw hint.
177    HintVerified,
178}
179
180/// One proven-bounded loop inside a bounded function (#778 phase 2). Loops are
181/// listed in ascending `head_offset` order — the SAME order `--wcet-hints`
182/// `loop_bounds` entries are matched by.
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184pub struct WcetLoopBound {
185    /// Byte offset of the loop head (backward-branch target) within the function.
186    pub head_offset: u64,
187    /// The PROVEN maximum number of body executions (full iterations).
188    pub trip_count: u64,
189    /// Number of instructions inside the loop region (head..=backward branch),
190    /// so a consumer can cross-check `cycles ≥ trip_count × region_instr_count`
191    /// (every instruction costs ≥ 1 cycle).
192    pub region_instr_count: usize,
193    /// How the trip count was established.
194    pub source: WcetLoopBoundSource,
195    /// The hint value consumed (present iff `source == HintVerified` or a
196    /// redundant hint was cross-checked against a static proof).
197    #[serde(default, skip_serializing_if = "Option::is_none")]
198    pub hint: Option<u64>,
199}
200
201/// Machine-readable reason a `--wcet-hints` entry was REJECTED (#778 phase 2).
202/// The hint file is UNTRUSTED input: a hint is only ever consumed after synth
203/// verifies the loop's induction against it; everything else lands here.
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205#[serde(rename_all = "kebab-case")]
206pub enum WcetHintReject {
207    /// The hint is SMALLER than synth's own derived trip count — a wrong hint.
208    /// Trusting it would emit a bound < a real execution (the fatal class).
209    HintBelowDerivedTrip,
210    /// synth could not verify the loop's induction against the hint (counter not
211    /// provably monotonic toward a statically-known bound ≤ hint — e.g. a
212    /// data-dependent bound register, a non-canonical shape, or an equality exit
213    /// whose step does not divide the distance). An unverifiable hint is never
214    /// trusted into a bound.
215    HintUnverifiableInduction,
216    /// The hint indexes a loop that does not exist in this function's final
217    /// instruction stream.
218    HintUnknownLoop,
219    /// A recursion-depth hint (`recursion_depth`) was offered but synth could NOT
220    /// verify the self-recursion is a single-self-call chain whose controlling
221    /// value is entry-independently bounded (a masked-slot counter decreasing by a
222    /// const step toward a base guard on the SAME masked quantity). Without an
223    /// entry-independent ceiling the true depth is runtime-unbounded, so the hint
224    /// is never trusted into a bound. (#778 phase 4 / #49.)
225    HintUnverifiableRecursion,
226    /// A recursion-depth hint is SMALLER than synth's own DERIVED maximum depth
227    /// (the entry-independent ceiling proven from the masked-slot induction). A
228    /// hint below the derived depth is a wrong oracle claim — trusting it would
229    /// emit a bound < a real execution (the fatal class). (#778 phase 4 / #49.)
230    HintBelowDerivedDepth,
231}
232
233impl WcetHintReject {
234    /// A short human-readable explanation, embedded alongside the machine reason.
235    pub fn note(&self) -> &'static str {
236        match self {
237            WcetHintReject::HintBelowDerivedTrip => {
238                "hint is below synth's derived trip count — a wrong hint; \
239                 trusting it would emit an unsound bound"
240            }
241            WcetHintReject::HintUnverifiableInduction => {
242                "loop induction not verifiable against the hint (counter not \
243                 provably monotonic toward a statically-known bound ≤ hint) — \
244                 an unverifiable hint is never trusted into a bound"
245            }
246            WcetHintReject::HintUnknownLoop => {
247                "hint indexes a loop that does not exist in the final \
248                 instruction stream"
249            }
250            WcetHintReject::HintUnverifiableRecursion => {
251                "recursion-depth hint not verifiable — the self-recursion is not a \
252                 single-self-call chain whose controlling value is entry-independently \
253                 bounded (masked-slot counter decreasing by a const step toward a base \
254                 guard on the same masked quantity); depth is runtime-unbounded, so \
255                 the hint is never trusted into a bound"
256            }
257            WcetHintReject::HintBelowDerivedDepth => {
258                "recursion-depth hint is below synth's derived maximum depth (the \
259                 entry-independent ceiling proven from the masked-slot induction) — \
260                 a wrong hint; trusting it would emit an unsound bound"
261            }
262        }
263    }
264}
265
266/// One rejected hint, recorded in the sidecar so the oracle (scry) sees exactly
267/// which of its claims synth refused and why.
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269pub struct WcetHintRejection {
270    /// Index into the function's `loop_bounds` hint array (== loop order by
271    /// ascending head offset).
272    pub loop_index: usize,
273    /// Byte offset of the loop head this hint addressed, when the loop exists.
274    #[serde(default, skip_serializing_if = "Option::is_none")]
275    pub head_offset: Option<u64>,
276    /// The rejected hint value.
277    pub hint: u64,
278    /// Machine-readable rejection reason.
279    pub reason: WcetHintReject,
280    /// Human-readable note (`reason.note()`).
281    pub note: String,
282}
283
284/// (#778 phase 4 / #49) The self-recursion record carried on a bounded function
285/// whose bound was composed via a verified recursion-depth certificate, so the
286/// sidecar states exactly how the frame count was established (and that a hint gated
287/// it — the derived depth is still synth's own).
288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
289pub struct WcetRecursionBound {
290    /// The DERIVED maximum recursion depth (entry-independent ceiling).
291    pub max_depth: u64,
292    /// The number of frames folded into the bound (`max_depth + 1`, counting the
293    /// base frame). Diagnostic — lets a consumer cross-check `cycles ≥ frames`.
294    pub frame_count: u64,
295    /// The `--wcet-hints` `recursion_depth` value that gated the certificate (the
296    /// emitted `max_depth` is synth's DERIVED value, never this raw hint).
297    pub hint: u64,
298}
299
300/// The per-function result: either a sound cycle bound or a loud decline.
301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(tag = "status", rename_all = "kebab-case")]
303pub enum WcetFunction {
304    /// A sound upper bound on this function's execution in cycles.
305    Bounded {
306        /// Function name (WASM export or generated).
307        name: String,
308        /// The sound worst-case cycle bound. For a loop-free function this is the
309        /// SUM of each instruction's documented worst-case cycles (each executes
310        /// at most once). For a function whose loops ALL have proven trip counts
311        /// (#778 phase 2) each instruction's cost is multiplied by its proven
312        /// worst-case execution count. Always ≥ any real execution under the
313        /// stated precondition.
314        cycles: u64,
315        /// Number of ARM instructions summed (diagnostic).
316        instr_count: usize,
317        /// Proven loops (empty for a loop-free function), ascending head offset.
318        #[serde(default, skip_serializing_if = "Vec::is_empty")]
319        loops: Vec<WcetLoopBound>,
320        /// (#778 phase 4 / #49) Present iff this bound was composed via a verified
321        /// self-recursion certificate; states the derived depth + frame count.
322        #[serde(default, skip_serializing_if = "Option::is_none")]
323        recursion: Option<WcetRecursionBound>,
324        /// Hints that were rejected (the static proof stands independently).
325        #[serde(default, skip_serializing_if = "Vec::is_empty")]
326        hint_rejections: Vec<WcetHintRejection>,
327    },
328    /// No bound emitted — a loud decline with a machine-readable reason. A decline
329    /// is emitted (rather than the function omitted) so the map is COMPLETE: a
330    /// consumer sees every function is either bounded or explicitly unbounded,
331    /// never silently missing.
332    Declined {
333        /// Function name.
334        name: String,
335        /// Machine-readable reason.
336        reason: WcetDecline,
337        /// Human-readable note (`reason.note()`).
338        note: String,
339        /// Hints that were offered for this function and rejected.
340        #[serde(default, skip_serializing_if = "Vec::is_empty")]
341        hint_rejections: Vec<WcetHintRejection>,
342    },
343}
344
345impl WcetFunction {
346    /// Construct a decline, filling in the note from the reason.
347    pub fn declined(name: impl Into<String>, reason: WcetDecline) -> Self {
348        let note = reason.note().to_string();
349        WcetFunction::Declined {
350            name: name.into(),
351            reason,
352            note,
353            hint_rejections: Vec::new(),
354        }
355    }
356
357    /// Construct a decline carrying rejected-hint records.
358    pub fn declined_with_rejections(
359        name: impl Into<String>,
360        reason: WcetDecline,
361        hint_rejections: Vec<WcetHintRejection>,
362    ) -> Self {
363        let note = reason.note().to_string();
364        WcetFunction::Declined {
365            name: name.into(),
366            reason,
367            note,
368            hint_rejections,
369        }
370    }
371}
372
373/// (#778 phase 4 / #49) A proven SELF-recursion certificate: the function is a
374/// single-self-call chain whose controlling value is entry-independently bounded
375/// (a masked-slot counter decreasing by a const step toward a base guard on the
376/// SAME masked quantity), so its maximum recursion DEPTH is DERIVED (not
377/// hint-supplied) as an entry-independent ceiling. The composer folds the self-edge
378/// as `frame_count × frame_cost` (`frame_count = max_depth + 1`, counting the base
379/// frame) instead of declining `Recursion`.
380///
381/// A certificate is attached ONLY after the depth was cross-checked against a
382/// `--wcet-hints` `recursion_depth` entry (the untrusted oracle asserts intent;
383/// synth's derived ceiling is what is emitted). Without a hint the recursion still
384/// declines (a bound this consequential is opt-in, mirroring the equality-exit
385/// loop-hint gate). `self_label` is the function's own `func_<idx>` self-call label
386/// so the composer can identify and special-case exactly that edge.
387#[derive(Debug, Clone, PartialEq, Eq)]
388pub struct WcetRecursionCert {
389    /// The self-call `BL` label (`func_<idx>`) this certificate authorizes.
390    pub self_label: String,
391    /// The DERIVED maximum recursion depth (entry-independent ceiling). The base
392    /// frame is NOT included here — the composer uses `max_depth + 1` frames.
393    pub max_depth: u64,
394    /// The hint value that gated this certificate (recorded for the sidecar; the
395    /// emitted depth is always the derived `max_depth`, never the raw hint).
396    pub hint: u64,
397}
398
399/// One direct call site inside a composable function (#778 phase 3). Records the
400/// callee's `BL` label (`func_<idx>` for a local/relocatable-import call) and the
401/// per-instruction execution-count multiplier of the `BL` (1 outside any loop; the
402/// enclosing loop's proven trip product when the call sits inside a proven counted
403/// loop, so a call in a loop is counted `trip` times, never once).
404#[derive(Debug, Clone, PartialEq, Eq)]
405pub struct WcetCallSite {
406    /// The `BL` target label as emitted by the selector (`func_<wasm_index>` for a
407    /// direct local/import call; any other label is a runtime helper → external).
408    pub callee_label: String,
409    /// The call site's worst-case execution count (product of enclosing proven loop
410    /// trip factors; 1 outside any loop). `u128` to survive deep nesting without
411    /// wrapping, matching the loop-multiplier domain.
412    pub multiplier: u128,
413}
414
415/// The per-function INTERMEDIATE result of the WCET pass BEFORE inter-procedural
416/// composition (#778 phase 3). The backend produces one of these per function; the
417/// module-level composer ([`crate::wcet`] consumers call `synth_backend::wcet_compose`)
418/// resolves each function's direct call sites against the whole module and emits the
419/// final [`WcetFunction`] (a composed bound, or a propagated/recursion/indirect
420/// decline).
421///
422/// Splitting the pass in two keeps composition a PURE function over already-decided
423/// per-function facts: `own_cycles` already prices every non-call instruction
424/// (including each `BL`'s branch overhead) at its proven execution count, so the
425/// composed total is `own_cycles + Σ_site multiplier_site × callee_total` — the
426/// per-site multiplier makes a call inside a proven loop sound by construction.
427#[derive(Debug, Clone, PartialEq, Eq)]
428pub enum WcetIntermediate {
429    /// The function declines for a reason INDEPENDENT of composition (an unproven
430    /// loop, an internal looped expansion, an unsupported core, an unresolved label
431    /// branch, an indirect call, or an unmodeled op). Carried straight through to a
432    /// [`WcetFunction::Declined`]; composition never rescues these.
433    Declined {
434        name: String,
435        reason: WcetDecline,
436        hint_rejections: Vec<WcetHintRejection>,
437    },
438    /// The function's own body is bounded; its final bound depends only on resolving
439    /// the recorded direct call sites against the module's other functions.
440    Composable {
441        name: String,
442        /// The summed worst-case cost of every instruction in the final stream
443        /// (each priced at its documented worst case × its proven execution-count
444        /// multiplier), INCLUDING each direct `BL`'s branch overhead. The callee
445        /// bodies are added by the composer via `call_sites`.
446        own_cycles: u64,
447        /// Number of ARM instructions summed (diagnostic, carried to the bound).
448        instr_count: usize,
449        /// The direct call sites to resolve at compose time.
450        call_sites: Vec<WcetCallSite>,
451        /// Proven loops inside this function (carried to the bound unchanged).
452        loops: Vec<WcetLoopBound>,
453        /// (#778 phase 4 / #49) A proven self-recursion certificate, when this
454        /// function is a bounded single-self-call chain with a verified depth hint.
455        /// The composer folds the self-edge as `(max_depth+1) × frame_cost` instead
456        /// of declining `Recursion`. `None` for a non-recursive function or an
457        /// unverifiable/unhinted recursion (which still declines).
458        recursion_cert: Option<WcetRecursionCert>,
459        /// Hints rejected while analyzing this function (carried to the bound).
460        hint_rejections: Vec<WcetHintRejection>,
461    },
462}
463
464impl WcetIntermediate {
465    /// The compiled function name this intermediate is for.
466    pub fn name(&self) -> &str {
467        match self {
468            WcetIntermediate::Declined { name, .. } | WcetIntermediate::Composable { name, .. } => {
469                name
470            }
471        }
472    }
473}
474
475/// The parsed `--wcet-hints` file (`synth-wcet-hints-v1`) — an UNTRUSTED oracle
476/// input (#778 phase 2, the scry integration seam). Per function, an ordered
477/// array of claimed loop-trip-count upper bounds, matched to loops by ascending
478/// head offset (entry N = N-th loop head in the function; `null` skips a loop).
479/// Every entry is soundly CHECKED before use: synth re-derives the loop's trip
480/// count from its own induction proof and consumes the hint only when the
481/// derived count is ≤ the hint. A wrong or unverifiable hint is rejected with a
482/// machine reason ([`WcetHintReject`]) — never trusted into a bound.
483#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
484pub struct WcetHints {
485    /// Must equal [`HINTS_SCHEMA`].
486    pub schema: String,
487    /// Per-function hint arrays, keyed by the compiled function name.
488    #[serde(default)]
489    pub functions: std::collections::BTreeMap<String, WcetFunctionHints>,
490}
491
492/// Per-function loop-bound hints.
493#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
494pub struct WcetFunctionHints {
495    /// Claimed trip-count upper bounds, one per loop in ascending-head-offset
496    /// order; `null` leaves that loop unhinted.
497    #[serde(default)]
498    pub loop_bounds: Vec<Option<u64>>,
499    /// (#778 phase 4 / #49) An UNTRUSTED claimed maximum SELF-recursion depth for
500    /// this function. Consulted only when synth has proven the function is a
501    /// single-self-call chain whose controlling value is entry-independently bounded
502    /// (a masked-slot counter): synth then DERIVES its own maximum depth from the
503    /// mask+step+base induction and cross-checks this hint (`hint < derived` →
504    /// `hint-below-derived-depth`). A hint on a function whose recursion synth cannot
505    /// so verify is REJECTED (`hint-unverifiable-recursion`) and never trusted. The
506    /// emitted bound always uses synth's DERIVED depth, never the raw hint.
507    #[serde(default, skip_serializing_if = "Option::is_none")]
508    pub recursion_depth: Option<u64>,
509}
510
511/// The full `synth-wcet-v1` sidecar: schema header, precondition, and per-function
512/// bounds/declines.
513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
514pub struct WcetReport {
515    /// Schema version (`synth-wcet-v1`).
516    pub schema: String,
517    /// The compiled module name (for diagnostics).
518    pub module: String,
519    /// The core class the cycle table is written for (e.g. `"cortex-m4"`). The
520    /// bound is CONDITIONAL on this core.
521    pub core_class: String,
522    /// Assumed instruction-memory wait states (0 for the sound zero-wait table).
523    pub wait_states: u32,
524    /// Human statement of the memory precondition the bound holds under.
525    pub memory_assumption: String,
526    /// Per-function bound or decline. Complete: one entry per compiled function.
527    pub functions: Vec<WcetFunction>,
528}
529
530impl WcetReport {
531    /// Start an empty report for `module`, targeting `core_class` under the sound
532    /// zero-wait precondition.
533    pub fn new(module: impl Into<String>, core_class: impl Into<String>) -> Self {
534        WcetReport {
535            schema: SCHEMA.to_string(),
536            module: module.into(),
537            core_class: core_class.into(),
538            wait_states: 0,
539            memory_assumption:
540                "zero-wait-state instruction memory (flash accelerator / I-cache hit); \
541                 in-order single-issue pipeline; documented per-instruction worst-case cycles"
542                    .to_string(),
543            functions: Vec::new(),
544        }
545    }
546
547    /// Serialize to pretty JSON.
548    pub fn to_json(&self) -> serde_json::Result<String> {
549        serde_json::to_string_pretty(self)
550    }
551
552    /// Resolve the sidecar path (`<output>.wcet.json`) next to the ELF output.
553    pub fn sidecar_path(output: &std::path::Path) -> std::path::PathBuf {
554        let mut s = output.as_os_str().to_os_string();
555        s.push(".wcet.json");
556        std::path::PathBuf::from(s)
557    }
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    #[test]
565    fn bounded_and_declined_roundtrip() {
566        let mut r = WcetReport::new("m", "cortex-m4");
567        r.functions.push(WcetFunction::Bounded {
568            name: "leaf".into(),
569            cycles: 42,
570            instr_count: 7,
571            loops: Vec::new(),
572            recursion: None,
573            hint_rejections: Vec::new(),
574        });
575        r.functions
576            .push(WcetFunction::declined("spins", WcetDecline::Loop));
577        let json = r.to_json().unwrap();
578        let back: WcetReport = serde_json::from_str(&json).unwrap();
579        assert_eq!(r, back);
580        // Decline reason is machine-readable and carries a note.
581        assert!(json.contains("\"reason\": \"loop\""));
582        assert!(json.contains("synth-wcet-v1"));
583    }
584
585    #[test]
586    fn sidecar_path_appends_suffix() {
587        let p = WcetReport::sidecar_path(std::path::Path::new("out/app.elf"));
588        assert_eq!(p, std::path::PathBuf::from("out/app.elf.wcet.json"));
589    }
590}