Skip to main content

logicaffeine_web/ui/pages/
register_alloc_viz.rs

1//! Studio easter egg — certified linear-scan register allocation, visualised.
2//!
3//! Pure data → SVG (no Z3, no JS): a basic block's variable live ranges are laid on an instruction
4//! timeline as bars, coloured by the physical register they're assigned. When the block is
5//! over-pressure, the bars that provably must spill are flagged red and the certified Hall/clique
6//! witness is reported. The allocation comes straight from the certified `register_alloc` engine,
7//! so the picture is a faithful view of a re-checkable result — the same engine that crushes Z3 on
8//! the colouring encoding, here rendered for a one-glance "watch the allocator decide" demo.
9
10use super::hardware_spec;
11use logicaffeine_proof::register_alloc::{allocate, register_pressure, Allocation, LiveRange};
12
13/// A parsed register-allocation spec: named variable live ranges + the physical register budget.
14pub struct RegSpec {
15    /// Display name per variable index.
16    pub names: Vec<String>,
17    /// Live ranges (variable index matches `names`).
18    pub ranges: Vec<LiveRange>,
19    /// Physical register budget.
20    pub registers: usize,
21}
22
23/// Parse a spec of the form (one `name: start-end` per line, plus a `registers: N` budget):
24/// ```text
25/// ## Register Allocation
26/// registers: 3
27/// a: 0-5
28/// b: 1-6
29/// ```
30/// Returns `None` if there is no register budget or no live ranges.
31pub fn parse_register_spec(spec: &str) -> Option<RegSpec> {
32    let mut registers: Option<usize> = None;
33    let mut names = Vec::new();
34    let mut ranges = Vec::new();
35    for raw in spec.lines() {
36        let line = hardware_spec::content(raw);
37        if line.is_empty() {
38            continue;
39        }
40        if let Some(rest) = hardware_spec::field_value(line, hardware_spec::REGISTERS) {
41            // Only accept a well-formed budget; never clobber a valid one with a malformed line.
42            if let Ok(r) = rest.parse::<usize>() {
43                registers = Some(r);
44            }
45            continue;
46        }
47        if let Some((name, rng)) = line.split_once(':') {
48            if let Some((s, e)) = rng.trim().split_once('-') {
49                if let (Ok(start), Ok(end)) = (s.trim().parse::<i64>(), e.trim().parse::<i64>()) {
50                    if start < end {
51                        let var = names.len();
52                        names.push(name.trim().to_string());
53                        ranges.push(LiveRange::new(var, start, end));
54                    }
55                }
56            }
57        }
58    }
59    let registers = registers?;
60    if ranges.is_empty() {
61        return None;
62    }
63    Some(RegSpec {
64        names,
65        ranges,
66        registers,
67    })
68}
69
70/// Whether `spec` is a register-allocation spec (a `registers:` budget plus at least one live range).
71/// This is the single source of truth the Studio uses to route Hardware-mode input to the allocator
72/// easter egg, so the wiring (panel visibility, output panel, viz panel) can never drift from what
73/// the parser actually accepts.
74pub fn is_register_alloc_spec(spec: &str) -> bool {
75    parse_register_spec(spec).is_some()
76}
77
78const REG_COLORS: &[&str] = &[
79    "#61afef", "#98c379", "#e5c07b", "#c678dd", "#56b6c2", "#d19a66", "#56c2a8", "#b3a0ff",
80];
81
82/// A deterministic linear-scan assignment: variable index `i` → the physical register it is given, or
83/// `None` if linear-scan must spill it (no register was free when it became live). This is the data
84/// the animated view replays — each variable becomes one bar that lights up in its register's lane
85/// while it is live. Re-checkable via [`is_valid_linear_scan`]. It spills *nothing* exactly when the
86/// block fits the budget (peak pressure ≤ `registers`), so it agrees with the certified [`allocate`]
87/// decision while also showing *which* value gets evicted when it does not.
88pub fn linear_scan_assignment(spec: &RegSpec) -> Vec<Option<usize>> {
89    let n = spec.ranges.len();
90    let mut assignment = vec![None; n];
91    // Visit variables in the order they become live (ties: the one that dies first).
92    let mut order: Vec<usize> = (0..n).collect();
93    order.sort_by_key(|&i| (spec.ranges[i].start, spec.ranges[i].end));
94    // The register file: slot `r` currently holds `Some(variable)`, or `None` when free.
95    let mut slots: Vec<Option<usize>> = vec![None; spec.registers];
96    for &i in &order {
97        let start = spec.ranges[i].start;
98        // Free every register whose occupant has already died — `[start, end)` is half-open, so an
99        // occupant with `end <= start` no longer overlaps the arriving variable.
100        for slot in slots.iter_mut() {
101            if let Some(occ) = *slot {
102                if spec.ranges[occ].end <= start {
103                    *slot = None;
104                }
105            }
106        }
107        // Take the lowest-numbered free register; if every slot is held, this variable spills.
108        if let Some(free) = slots.iter().position(Option::is_none) {
109            slots[free] = Some(i);
110            assignment[i] = Some(free);
111        }
112    }
113    assignment
114}
115
116/// Re-check a linear-scan assignment: every assigned register is within budget, and no two variables
117/// that are live at the same time are given the same register — the soundness property any register
118/// allocation must satisfy. (Spilled variables, `None`, impose no constraint: they live in memory.)
119pub fn is_valid_linear_scan(spec: &RegSpec, assignment: &[Option<usize>]) -> bool {
120    if assignment.len() != spec.ranges.len() {
121        return false;
122    }
123    if assignment.iter().flatten().any(|&r| r >= spec.registers) {
124        return false;
125    }
126    for i in 0..spec.ranges.len() {
127        for j in (i + 1)..spec.ranges.len() {
128            let (a, b) = (spec.ranges[i], spec.ranges[j]);
129            let overlap = a.start < b.end && b.start < a.end;
130            if overlap && assignment[i].is_some() && assignment[i] == assignment[j] {
131                return false;
132            }
133        }
134    }
135    true
136}
137
138/// Register pressure sampled at each instruction in `tmin..tmax`: `profile[i]` is how many variables
139/// are live at instruction `tmin + i`. Its maximum is the register pressure (the fewest registers the
140/// block could ever need), which is what the budget line is drawn against — wherever the profile rises
141/// above the budget, spilling is unavoidable.
142pub fn pressure_profile(spec: &RegSpec) -> Vec<usize> {
143    let tmin = spec.ranges.iter().map(|r| r.start).min().unwrap_or(0);
144    let tmax = spec.ranges.iter().map(|r| r.end).max().unwrap_or(0);
145    (tmin..tmax)
146        .map(|t| {
147            spec.ranges
148                .iter()
149                .filter(|r| r.start <= t && t < r.end)
150                .count()
151        })
152        .collect()
153}
154
155/// The interference graph's edges: every pair of variables `(i, j)` (`i < j`) whose live ranges
156/// overlap, so they cannot share a register. Register allocation is exactly colouring this graph; for
157/// straight-line code it is an interval graph (perfect), so its chromatic number equals the largest
158/// clique equals the register pressure.
159pub fn interference_edges(spec: &RegSpec) -> Vec<(usize, usize)> {
160    let mut edges = Vec::new();
161    for i in 0..spec.ranges.len() {
162        for j in (i + 1)..spec.ranges.len() {
163            let (a, b) = (spec.ranges[i], spec.ranges[j]);
164            if a.start < b.end && b.start < a.end {
165                edges.push((i, j));
166            }
167        }
168    }
169    edges
170}
171
172/// A looping SMIL opacity pulse: dim outside the live window `[t0, t1]` (both normalised to `0..1` of
173/// the animation cycle), bright inside it, with a fast snap at each edge — this is what makes a value
174/// "light up" in its register lane exactly while the sweep line is over it.
175fn pulse(t0: f64, t1: f64, dur: f64, dim: f64, bright: f64) -> String {
176    let a1 = t0.clamp(0.006, 0.99);
177    let a0 = (a1 - 0.004).max(0.002);
178    let b0 = t1.clamp(0.006, 0.99).max(a1 + 0.002);
179    let b1 = (b0 + 0.004).min(0.996);
180    format!(
181        r#"<animate attributeName="opacity" dur="{dur:.2}s" repeatCount="indefinite" keyTimes="0;{a0:.4};{a1:.4};{b0:.4};{b1:.4};1" values="{dim};{dim};{bright};{bright};{dim};{dim}"/>"#
182    )
183}
184
185/// Render the certified allocation of `spec` as `(svg, verdict)`. The SVG is an animated linear-scan:
186/// a live-range timeline above an animated register file, with a sweep line crossing both so you can
187/// watch each value claim and release its register (and, when over capacity, drop to a spill lane).
188/// The verdict is the plain-language, certified summary.
189pub fn render(spec: &RegSpec) -> (String, String) {
190    use std::fmt::Write as _;
191    let alloc = allocate(&spec.ranges, spec.registers);
192    let pressure = register_pressure(&spec.ranges);
193    let assignment = linear_scan_assignment(spec);
194    let spilled_any = assignment.iter().any(Option::is_none);
195    let n = spec.ranges.len();
196    let tmin = spec.ranges.iter().map(|r| r.start).min().unwrap_or(0);
197    let tmax = spec.ranges.iter().map(|r| r.end).max().unwrap_or(1);
198    let span = (tmax - tmin).max(1) as f64;
199
200    // Geometry: a variable timeline stacked above a register-file panel, sharing the instruction axis.
201    let left = 86.0_f64;
202    let plot_w = 462.0_f64;
203    let x = |t: i64| left + (t - tmin) as f64 / span * plot_w;
204    let nt = |t: i64| (t - tmin) as f64 / span; // normalised 0..1 for animation timing
205
206    let top1 = 46.0_f64;
207    let trow_h = 22.0_f64;
208    let tl_bottom = top1 + n as f64 * trow_h;
209    let rf_label_y = tl_bottom + 20.0;
210    let top_rf = tl_bottom + 30.0;
211    let lane_h = 24.0_f64;
212    let lanes = spec.registers + usize::from(spilled_any);
213    let rf_bottom = top_rf + lanes as f64 * lane_h;
214
215    // Pressure histogram panel: how many values are live at each instruction, against the budget line.
216    let profile = pressure_profile(spec);
217    let max_p = profile
218        .iter()
219        .copied()
220        .max()
221        .unwrap_or(0)
222        .max(spec.registers)
223        .max(1);
224    let pr_label_y = rf_bottom + 20.0;
225    let pr_top = rf_bottom + 28.0;
226    let pr_h = 56.0_f64;
227    let pr_bottom = pr_top + pr_h;
228
229    // Interference-graph panel: the graph register allocation is really colouring.
230    let graph_label_y = pr_bottom + 36.0;
231    let graph_top = pr_bottom + 44.0;
232    let graph_h = 188.0_f64;
233    let gcx = 300.0_f64;
234    let gcy = graph_top + graph_h / 2.0;
235    let gradius = (graph_h / 2.0 - 30.0).min(120.0);
236    let legend_y = graph_top + graph_h + 2.0;
237
238    let height = legend_y + 16.0;
239    // One animation loop sweeps the whole block; tie its length to the program length, within reason.
240    let dur = (span * 0.6).clamp(4.0, 12.0);
241
242    let mut s = String::new();
243    let _ = write!(
244        s,
245        r#"<svg viewBox="0 0 600 {height:.0}" width="600" height="{height:.0}" xmlns="http://www.w3.org/2000/svg" font-family="ui-monospace, monospace" font-size="12">"#
246    );
247    let _ = write!(
248        s,
249        r##"<rect x="0" y="0" width="600" height="{height:.0}" fill="#0f1117"/>"##
250    );
251    let _ = write!(
252        s,
253        r##"<text x="12" y="24" fill="#e5e7eb" font-size="14">Register allocation · {} registers · pressure {pressure}{}</text>"##,
254        spec.registers,
255        if spilled_any {
256            "  \u{26A0} over capacity"
257        } else {
258            ""
259        }
260    );
261
262    // Faint instruction gridlines + tick labels spanning every panel.
263    let grid_top = top1 - 6.0;
264    let grid_bot = pr_bottom + 2.0;
265    let mut t = tmin;
266    while t <= tmax {
267        let gx = x(t);
268        let _ = write!(
269            s,
270            r##"<line x1="{gx:.1}" y1="{grid_top:.0}" x2="{gx:.1}" y2="{grid_bot:.0}" stroke="#1e2230" stroke-width="1"/>"##
271        );
272        let _ = write!(
273            s,
274            r##"<text x="{gx:.1}" y="{:.0}" fill="#3b4252" font-size="9" text-anchor="middle">{t}</text>"##,
275            grid_bot + 12.0
276        );
277        t += 1;
278    }
279
280    // ---- Timeline panel: one solid bar per variable, coloured by the register it is given. ----
281    for i in 0..n {
282        let r = spec.ranges[i];
283        let y = top1 + i as f64 * trow_h;
284        let _ = write!(
285            s,
286            r##"<text x="10" y="{:.0}" fill="#abb2bf">{}</text>"##,
287            y + 14.0,
288            spec.names[i]
289        );
290        let bx = x(r.start);
291        let bw = (x(r.end) - bx).max(5.0);
292        let (fill, tag, stroke) = match assignment[i] {
293            Some(reg) => (REG_COLORS[reg % REG_COLORS.len()], format!("r{reg}"), ""),
294            None => (
295                "#e06c75",
296                "SPILL".to_string(),
297                r##" stroke="#ff5c66" stroke-width="1.5""##,
298            ),
299        };
300        let _ = write!(
301            s,
302            r#"<rect x="{bx:.1}" y="{:.0}" width="{bw:.1}" height="16" rx="4" fill="{fill}"{stroke}/>"#,
303            y + 2.0
304        );
305        let _ = write!(
306            s,
307            r##"<text x="{:.1}" y="{:.0}" fill="#10131a" font-size="11">{tag}</text>"##,
308            bx + 4.0,
309            y + 14.0
310        );
311    }
312
313    // ---- Register-file panel: a lane per register (plus MEM for spills); occupants pulse bright as
314    //       the sweep crosses their live range, so you watch each register fill and free. ----
315    let _ = write!(
316        s,
317        r##"<text x="12" y="{rf_label_y:.0}" fill="#7a8290" font-size="11" letter-spacing="0.08em">REGISTER FILE</text>"##
318    );
319    for reg in 0..spec.registers {
320        let y = top_rf + reg as f64 * lane_h;
321        let colour = REG_COLORS[reg % REG_COLORS.len()];
322        let _ = write!(
323            s,
324            r##"<rect x="{left:.0}" y="{:.1}" width="{plot_w:.0}" height="{:.1}" rx="4" fill="#161a24"/>"##,
325            y + 2.0,
326            lane_h - 6.0
327        );
328        let _ = write!(
329            s,
330            r##"<text x="12" y="{:.0}" fill="{colour}">r{reg}</text>"##,
331            y + 16.0
332        );
333        for i in 0..n {
334            if assignment[i] == Some(reg) {
335                let r = spec.ranges[i];
336                let bx = x(r.start);
337                let bw = (x(r.end) - bx).max(5.0);
338                let bar = pulse(nt(r.start), nt(r.end), dur, 0.16, 1.0);
339                let txt = pulse(nt(r.start), nt(r.end), dur, 0.25, 1.0);
340                let _ = write!(
341                    s,
342                    r#"<rect x="{bx:.1}" y="{:.1}" width="{bw:.1}" height="{:.1}" rx="4" fill="{colour}" opacity="0.16">{bar}</rect>"#,
343                    y + 3.0,
344                    lane_h - 8.0
345                );
346                let _ = write!(
347                    s,
348                    r##"<text x="{:.1}" y="{:.0}" fill="#10131a" font-size="11" opacity="0.25">{}{txt}</text>"##,
349                    bx + 5.0,
350                    y + 16.0,
351                    spec.names[i]
352                );
353            }
354        }
355    }
356    if spilled_any {
357        let y = top_rf + spec.registers as f64 * lane_h;
358        let _ = write!(
359            s,
360            r##"<rect x="{left:.0}" y="{:.1}" width="{plot_w:.0}" height="{:.1}" rx="4" fill="#2a1417"/>"##,
361            y + 2.0,
362            lane_h - 6.0
363        );
364        let _ = write!(
365            s,
366            r##"<text x="12" y="{:.0}" fill="#e06c75">MEM</text>"##,
367            y + 16.0
368        );
369        for i in 0..n {
370            if assignment[i].is_none() {
371                let r = spec.ranges[i];
372                let bx = x(r.start);
373                let bw = (x(r.end) - bx).max(5.0);
374                let bar = pulse(nt(r.start), nt(r.end), dur, 0.3, 1.0);
375                let _ = write!(
376                    s,
377                    r##"<rect x="{bx:.1}" y="{:.1}" width="{bw:.1}" height="{:.1}" rx="4" fill="#e06c75" stroke="#ff5c66" stroke-width="1.2" opacity="0.3">{bar}</rect>"##,
378                    y + 3.0,
379                    lane_h - 8.0
380                );
381                let _ = write!(
382                    s,
383                    r##"<text x="{:.1}" y="{:.0}" fill="#2a1417" font-size="11">{} SPILL</text>"##,
384                    bx + 5.0,
385                    y + 16.0,
386                    spec.names[i]
387                );
388            }
389        }
390    }
391
392    // ---- Pressure panel: a per-instruction live-count histogram against the budget line. Bars that
393    //       rise above the budget are red — exactly the instructions at which spilling is forced. ----
394    let _ = write!(
395        s,
396        r##"<text x="12" y="{pr_label_y:.0}" fill="#7a8290" font-size="11" letter-spacing="0.08em">PRESSURE</text>"##
397    );
398    let bar_y = |p: usize| pr_bottom - (p as f64 / max_p as f64) * pr_h;
399    for (i, &p) in profile.iter().enumerate() {
400        let t = tmin + i as i64;
401        let bx = x(t);
402        let bw = (x(t + 1) - bx - 1.0).max(2.0);
403        let y = bar_y(p);
404        let colour = if p > spec.registers {
405            "#ff5c66"
406        } else {
407            "#5aa0e0"
408        };
409        let _ = write!(
410            s,
411            r##"<rect x="{bx:.1}" y="{y:.1}" width="{bw:.1}" height="{:.1}" rx="1.5" fill="{colour}" opacity="0.85"/>"##,
412            pr_bottom - y
413        );
414    }
415    let by = bar_y(spec.registers);
416    let _ = write!(
417        s,
418        r##"<line x1="{left:.0}" y1="{by:.1}" x2="{:.0}" y2="{by:.1}" stroke="#e5c07b" stroke-width="1.2" stroke-dasharray="5 4"/>"##,
419        left + plot_w
420    );
421    let _ = write!(
422        s,
423        r##"<text x="8" y="{:.1}" fill="#e5c07b" font-size="9">budget {}</text>"##,
424        by + 3.0,
425        spec.registers
426    );
427
428    // ---- The sweep line: a translating beam crossing every panel, looping with the occupancy pulses.
429    let beam_top = top1 - 6.0;
430    let beam_bot = pr_bottom + 2.0;
431    let _ = write!(
432        s,
433        r##"<g><rect x="{left:.0}" y="{beam_top:.0}" width="7" height="{:.0}" fill="#f8fafc" opacity="0.10"/><line x1="{left:.0}" y1="{beam_top:.0}" x2="{left:.0}" y2="{beam_bot:.0}" stroke="#f8fafc" stroke-width="2" opacity="0.85"/><animateTransform attributeName="transform" type="translate" from="0 0" to="{plot_w:.0} 0" dur="{dur:.2}s" repeatCount="indefinite"/></g>"##,
434        beam_bot - beam_top
435    );
436
437    // ---- Interference graph: nodes = variables on a ring, edges = overlapping lifetimes; nodes are
438    //       coloured by the register they get, and the certified spill clique (if any) is ringed red.
439    //       A node glows in sync with the sweep while its value is live. ----
440    let clique: std::collections::HashSet<usize> = match &alloc {
441        Allocation::Spill { must_spill, .. } => must_spill.iter().copied().collect(),
442        Allocation::Allocated(_) => Default::default(),
443    };
444    let _ = write!(
445        s,
446        r##"<text x="12" y="{graph_label_y:.0}" fill="#7a8290" font-size="11" letter-spacing="0.08em">INTERFERENCE GRAPH · χ = {pressure} (registers needed)</text>"##
447    );
448    let mut pos: Vec<(f64, f64)> = Vec::with_capacity(n);
449    for i in 0..n {
450        if n <= 1 {
451            pos.push((gcx, gcy));
452        } else {
453            let ang =
454                -std::f64::consts::FRAC_PI_2 + 2.0 * std::f64::consts::PI * i as f64 / n as f64;
455            pos.push((gcx + gradius * ang.cos(), gcy + gradius * ang.sin()));
456        }
457    }
458    for &(i, j) in &interference_edges(spec) {
459        let (x1, y1) = pos[i];
460        let (x2, y2) = pos[j];
461        let (stroke, w, op) = if clique.contains(&i) && clique.contains(&j) {
462            ("#ff5c66", 2.5, 0.9)
463        } else {
464            ("#3a4150", 1.2, 0.55)
465        };
466        let _ = write!(
467            s,
468            r##"<line x1="{x1:.1}" y1="{y1:.1}" x2="{x2:.1}" y2="{y2:.1}" stroke="{stroke}" stroke-width="{w}" opacity="{op}"/>"##
469        );
470    }
471    for i in 0..n {
472        let (px, py) = pos[i];
473        let fill = match assignment[i] {
474            Some(reg) => REG_COLORS[reg % REG_COLORS.len()],
475            None => "#e06c75",
476        };
477        if clique.contains(&i) {
478            let _ = write!(
479                s,
480                r##"<circle cx="{px:.1}" cy="{py:.1}" r="17" fill="none" stroke="#ff5c66" stroke-width="3"/>"##
481            );
482        }
483        let glow = pulse(
484            nt(spec.ranges[i].start),
485            nt(spec.ranges[i].end),
486            dur,
487            0.5,
488            1.0,
489        );
490        let _ = write!(
491            s,
492            r##"<circle cx="{px:.1}" cy="{py:.1}" r="14" fill="{fill}" stroke="#0f1117" stroke-width="1.5" opacity="0.5">{glow}</circle>"##
493        );
494        let _ = write!(
495            s,
496            r##"<text x="{px:.1}" y="{:.1}" fill="#10131a" font-size="11" text-anchor="middle">{}</text>"##,
497            py + 4.0,
498            spec.names[i]
499        );
500    }
501
502    // ---- Legend ----
503    let mut lx = 12.0_f64;
504    for reg in 0..spec.registers.min(REG_COLORS.len()) {
505        let _ = write!(
506            s,
507            r##"<rect x="{lx:.0}" y="{:.0}" width="10" height="10" rx="2" fill="{}"/>"##,
508            legend_y - 9.0,
509            REG_COLORS[reg]
510        );
511        let _ = write!(
512            s,
513            r##"<text x="{:.0}" y="{legend_y:.0}" fill="#9aa3b2" font-size="10">r{reg}</text>"##,
514            lx + 14.0
515        );
516        lx += 42.0;
517    }
518    if spilled_any {
519        let _ = write!(
520            s,
521            r##"<rect x="{lx:.0}" y="{:.0}" width="10" height="10" rx="2" fill="#e06c75"/>"##,
522            legend_y - 9.0
523        );
524        let _ = write!(
525            s,
526            r##"<text x="{:.0}" y="{legend_y:.0}" fill="#9aa3b2" font-size="10">spill</text>"##,
527            lx + 14.0
528        );
529        lx += 50.0;
530    }
531    let _ = write!(
532        s,
533        r##"<text x="{lx:.0}" y="{legend_y:.0}" fill="#9aa3b2" font-size="10">red clique = cannot share</text>"##
534    );
535
536    let _ = write!(s, "</svg>");
537
538    let verdict = match &alloc {
539        Allocation::Allocated(_) => format!(
540            "\u{2713} Allocated with {} registers, certified: no two simultaneously-live variables share a register.",
541            spec.registers
542        ),
543        Allocation::Spill { pressure, must_spill } => {
544            let names: Vec<&str> = must_spill
545                .iter()
546                .filter_map(|v| spec.names.get(*v).map(String::as_str))
547                .collect();
548            format!(
549                "\u{26A0} Must spill: {pressure} variables are live at once but only {} registers exist. {{{}}} all mutually interfere, so they cannot share {} registers (certified clique).",
550                spec.registers,
551                names.join(", "),
552                spec.registers
553            )
554        }
555    };
556    (s, verdict)
557}
558
559/// A textual allocation report for the Studio output panel: the physical register assigned to each
560/// variable, or — when the block is over-pressure — the spill verdict naming its mutually-interfering
561/// clique. This is the "compiler back-end output" view that pairs with the [`render`] timeline; the
562/// per-variable registers come from the same [`linear_scan_assignment`] the animation replays, and
563/// the feasibility/clique verdict from the certified [`allocate`] result, so the two views agree.
564pub fn allocation_report(spec: &RegSpec) -> String {
565    use std::fmt::Write as _;
566    let mut out = String::new();
567    match allocate(&spec.ranges, spec.registers) {
568        Allocation::Allocated(_) => {
569            let assignment = linear_scan_assignment(spec);
570            let _ = writeln!(
571                out,
572                "Allocated {} variable{} into {} register{}, certified: no two simultaneously-live variables share a register.",
573                spec.names.len(),
574                if spec.names.len() == 1 { "" } else { "s" },
575                spec.registers,
576                if spec.registers == 1 { "" } else { "s" },
577            );
578            for (i, name) in spec.names.iter().enumerate() {
579                if let Some(reg) = assignment.get(i).copied().flatten() {
580                    let _ = writeln!(out, "  {name} \u{2192} r{reg}");
581                }
582            }
583        }
584        Allocation::Spill {
585            pressure,
586            must_spill,
587        } => {
588            let clique: Vec<&str> = must_spill
589                .iter()
590                .filter_map(|v| spec.names.get(*v).map(String::as_str))
591                .collect();
592            let _ = writeln!(
593                out,
594                "Must spill: {pressure} variables are live at once but only {} register{} exist.",
595                spec.registers,
596                if spec.registers == 1 { "" } else { "s" },
597            );
598            let _ = write!(
599                out,
600                "Certified clique (all mutually interfere): {}",
601                clique.join(", ")
602            );
603        }
604    }
605    out
606}
607
608#[cfg(test)]
609#[path = "../../../../../crates/logicaffeine_tests/unit/logicaffeine_web/ui/pages/register_alloc_viz/tests.rs"]
610mod tests;