Skip to main content

bitloom_viz/
lib.rs

1//! HTML dump of FrozenHir for debugging and product visualize/doc (FR38 / FR49).
2//!
3//! Delivers: module/port HTML + instance hierarchy (list + Mermaid).
4//! Also: browsable timing HTML from tick samples / VCD (FR49 wave path).
5//! LSP: product server is `bitloom-lsp` (FR99 / Epic 44); HTML hierarchy ≠ LSP.
6
7use std::collections::BTreeMap;
8
9use bitloom_hir::{FrozenHir, GroundType, PortDirection, Stmt};
10
11/// One time-step of signal values for the product timing view.
12#[derive(Clone, Debug, Default)]
13pub struct WaveSample {
14    pub time: u64,
15    pub values: BTreeMap<String, u64>,
16}
17
18/// Render FrozenHir as a self-contained HTML hierarchy document (Bitloom product view).
19pub fn to_html(hir: &FrozenHir) -> String {
20    let mut out = String::from(
21        "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Bitloom hierarchy</title>\n\
22         <style>body{font-family:system-ui,sans-serif;margin:1.5rem;line-height:1.45}\n\
23         h1{font-size:1.4rem} h2{font-size:1.1rem;margin-top:1.5rem}\n\
24         .brand{color:#0b3d5c;font-weight:700;letter-spacing:.02em}\n\
25         pre.mermaid{background:#f6f8fa;padding:1rem;overflow:auto;border-radius:4px}\n\
26         </style></head><body>\n",
27    );
28    out.push_str("<p class=\"brand\">Bitloom</p>\n");
29    out.push_str(&format!(
30        "<h1>Hierarchy — {}</h1>\n",
31        escape_html(&hir.abi_name)
32    ));
33    out.push_str("<h2>Modules and ports</h2>\n<ul>\n");
34    for m in &hir.circuit().modules {
35        out.push_str(&format!(
36            "<li><strong>{}</strong><ul>\n",
37            escape_html(&m.name)
38        ));
39        for p in &m.ports {
40            out.push_str(&format!(
41                "<li>port {} {:?} {:?}</li>\n",
42                escape_html(&p.name),
43                p.direction,
44                p.ty
45            ));
46        }
47        out.push_str("</ul></li>\n");
48    }
49    out.push_str("</ul>\n");
50
51    out.push_str("<h2>Instance hierarchy</h2>\n<ul>\n");
52    let edges = instance_edges(hir);
53    if edges.is_empty() {
54        out.push_str("<li><em>(no instances)</em></li>\n");
55    } else {
56        for (parent, name, module) in &edges {
57            out.push_str(&format!(
58                "<li>{parent} → <strong>{name}</strong> : {module}</li>\n",
59                parent = escape_html(parent),
60                name = escape_html(name),
61                module = escape_html(module)
62            ));
63        }
64    }
65    out.push_str("</ul>\n");
66
67    out.push_str("<h2>Hierarchy diagram (Mermaid)</h2>\n");
68    out.push_str("<pre class=\"mermaid\">\n");
69    out.push_str(&mermaid_hierarchy(hir));
70    out.push_str("</pre>\n");
71    out.push_str(
72        "<p>LSP: see <code>bitloom-lsp</code> / docs/fr99-bitloom-lsp.md (FR99); HTML hierarchy ≠ LSP — docs/fr38-viz-lsp.md</p>\n\
73         <p>Unrelated to <code>samitbasu/rhdl</code>.</p>\n</body></html>\n",
74    );
75    out
76}
77
78/// Interactive waveform HTML (FR104): browse / zoom·pan / signal search.
79///
80/// Self-contained product viewer — **not** static `timing.html` alone and **not**
81/// GTKWave-only. Sibling of FR49 `timing_html`; signal names match VCD/`tick` dump.
82pub fn interactive_wave_html(title: &str, samples: &[WaveSample]) -> String {
83    let mut signal_names: Vec<String> = samples
84        .iter()
85        .flat_map(|s| s.values.keys().cloned())
86        .collect();
87    signal_names.sort();
88    signal_names.dedup();
89
90    let mut times: Vec<u64> = samples.iter().map(|s| s.time).collect();
91    times.sort_unstable();
92    times.dedup();
93
94    // Embed samples as JSON: { "times": [...], "signals": { name: [v,...] } }
95    let mut json = String::from("{\"times\":[");
96    for (i, t) in times.iter().enumerate() {
97        if i > 0 {
98            json.push(',');
99        }
100        json.push_str(&t.to_string());
101    }
102    json.push_str("],\"signals\":{");
103    for (si, name) in signal_names.iter().enumerate() {
104        if si > 0 {
105            json.push(',');
106        }
107        json.push('"');
108        json.push_str(&escape_js_string(name));
109        json.push_str("\":[");
110        for (ti, t) in times.iter().enumerate() {
111            if ti > 0 {
112                json.push(',');
113            }
114            let v = samples
115                .iter()
116                .find(|s| s.time == *t)
117                .and_then(|s| s.values.get(name))
118                .copied()
119                .unwrap_or(0);
120            json.push_str(&v.to_string());
121        }
122        json.push(']');
123    }
124    json.push_str("}}");
125
126    let mut out = String::from(
127        "<!DOCTYPE html><html><head><meta charset=\"utf-8\">\
128         <title>Bitloom interactive wave</title>\n\
129         <style>\n\
130         body{font-family:system-ui,sans-serif;margin:1rem;line-height:1.4;background:#f7fafc;color:#122}\n\
131         .brand{color:#0b3d5c;font-weight:700;letter-spacing:.02em}\n\
132         .toolbar{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin:0.75rem 0}\n\
133         .toolbar input[type=search]{min-width:12rem;padding:.35rem .5rem}\n\
134         .toolbar button{padding:.35rem .75rem;cursor:pointer}\n\
135         #wave-canvas{display:block;width:100%;max-width:100%;background:#fff;\
136         border:1px solid #c5d0da;border-radius:4px;cursor:crosshair;touch-action:none}\n\
137         .hint{font-size:.85rem;color:#456}\n\
138         </style></head><body>\n",
139    );
140    out.push_str("<p class=\"brand\">Bitloom</p>\n");
141    out.push_str(&format!(
142        "<h1>Interactive wave — {}</h1>\n",
143        escape_html(title)
144    ));
145    out.push_str(
146        "<p class=\"hint\">FR104 interactive viewer (browse / zoom·pan / search). \
147         Static <code>timing.html</code> alone is <strong>not</strong> this path; \
148         GTKWave/Surfer remain optional for sibling <code>wave.vcd</code> (AD-5/24), \
149         not the sole completion path.</p>\n",
150    );
151
152    if samples.is_empty() || signal_names.is_empty() {
153        out.push_str(
154            "<div id=\"root\" data-bitloom-interactive-wave=\"empty\"><p><em>(no samples)</em></p></div>\n\
155             </body></html>\n",
156        );
157        return out;
158    }
159
160    out.push_str(
161        "<div id=\"root\" class=\"bitloom-interactive-wave\" data-bitloom-interactive-wave=\"1\">\n\
162         <div class=\"toolbar\">\n\
163         <label for=\"signal-search\">Search signals </label>\n\
164         <input type=\"search\" id=\"signal-search\" placeholder=\"filter by name\" \
165          aria-label=\"signal search filter\" />\n\
166         <button type=\"button\" id=\"zoom-in\" title=\"zoom in\">Zoom +</button>\n\
167         <button type=\"button\" id=\"zoom-out\" title=\"zoom out\">Zoom −</button>\n\
168         <button type=\"button\" id=\"pan-left\" title=\"pan left\">Pan ←</button>\n\
169         <button type=\"button\" id=\"pan-right\" title=\"pan right\">Pan →</button>\n\
170         <button type=\"button\" id=\"zoom-fit\" title=\"fit all\">Fit</button>\n\
171         <span id=\"viewport-label\" class=\"hint\"></span>\n\
172         </div>\n\
173         <canvas id=\"wave-canvas\" class=\"wave-canvas timeline\" width=\"960\" height=\"360\" \
174          role=\"img\" aria-label=\"waveform timeline canvas\"></canvas>\n\
175         </div>\n",
176    );
177    out.push_str("<script id=\"wave-data\" type=\"application/json\">");
178    out.push_str(&json);
179    out.push_str("</script>\n<script>\n");
180    out.push_str(INTERACTIVE_WAVE_JS);
181    out.push_str("\n</script>\n");
182    out.push_str("<p>Unrelated to <code>samitbasu/rhdl</code>.</p>\n</body></html>\n");
183    out
184}
185
186const INTERACTIVE_WAVE_JS: &str = include_str!("interactive_wave.js");
187const TYPED_WAVE_JS: &str = include_str!("typed_wave.js");
188
189fn escape_js_string(s: &str) -> String {
190    s.replace('\\', "\\\\")
191        .replace('"', "\\\"")
192        .replace('\n', "\\n")
193        .replace('\r', "\\r")
194}
195
196/// Structured signal metadata for FR117 typed IDE waveform (subset B).
197#[derive(Clone, Debug, PartialEq, Eq)]
198pub struct TypedSignal {
199    pub name: String,
200    /// Human-readable type, e.g. `UInt<8>`, `Clock`.
201    pub ty: String,
202    /// Role: `port:input`, `port:output`, `port:inout`, `reg`, `wire`.
203    pub kind: String,
204    pub module: String,
205    pub width: u32,
206}
207
208fn format_ground_type(ty: &GroundType) -> String {
209    match ty {
210        GroundType::UInt { width } => format!("UInt<{width}>"),
211        GroundType::SInt { width } => format!("SInt<{width}>"),
212        GroundType::Clock => "Clock".into(),
213        GroundType::Reset => "Reset".into(),
214        GroundType::Bool => "Bool".into(),
215        GroundType::Analog => "Analog".into(),
216    }
217}
218
219fn width_of_ty(ty: &GroundType) -> u32 {
220    match ty {
221        GroundType::UInt { width } | GroundType::SInt { width } => *width,
222        GroundType::Clock | GroundType::Reset | GroundType::Bool | GroundType::Analog => 1,
223    }
224}
225
226fn port_kind(dir: PortDirection) -> &'static str {
227    match dir {
228        PortDirection::Input => "port:input",
229        PortDirection::Output => "port:output",
230        PortDirection::InOut => "port:inout",
231    }
232}
233
234/// Extract typed signal hierarchy from FrozenHir (ports / wires / regs).
235pub fn typed_signals_from_hir(hir: &FrozenHir) -> Vec<TypedSignal> {
236    let mut out = Vec::new();
237    for m in &hir.circuit().modules {
238        for p in &m.ports {
239            out.push(TypedSignal {
240                name: p.name.clone(),
241                ty: format_ground_type(&p.ty),
242                kind: port_kind(p.direction).into(),
243                module: m.name.clone(),
244                width: width_of_ty(&p.ty),
245            });
246        }
247        for stmt in &m.body {
248            match stmt {
249                Stmt::WireDecl { name, ty, .. } => out.push(TypedSignal {
250                    name: name.clone(),
251                    ty: format_ground_type(ty),
252                    kind: "wire".into(),
253                    module: m.name.clone(),
254                    width: width_of_ty(ty),
255                }),
256                Stmt::RegDecl { name, ty, .. } => out.push(TypedSignal {
257                    name: name.clone(),
258                    ty: format_ground_type(ty),
259                    kind: "reg".into(),
260                    module: m.name.clone(),
261                    width: width_of_ty(ty),
262                }),
263                _ => {}
264            }
265        }
266    }
267    out
268}
269
270/// Machine-readable typed wave sidecar (`wave.typed.json`).
271pub fn typed_wave_json(title: &str, samples: &[WaveSample], typed: &[TypedSignal]) -> String {
272    let mut times: Vec<u64> = samples.iter().map(|s| s.time).collect();
273    times.sort_unstable();
274    times.dedup();
275
276    let mut json = String::from("{\n  \"product\": \"Bitloom\",\n  \"fr\": \"FR117\",\n");
277    json.push_str(&format!(
278        "  \"title\": \"{}\",\n  \"signals\": [\n",
279        escape_js_string(title)
280    ));
281    for (i, s) in typed.iter().enumerate() {
282        if i > 0 {
283            json.push_str(",\n");
284        }
285        json.push_str(&format!(
286            "    {{\"name\":\"{}\",\"ty\":\"{}\",\"kind\":\"{}\",\"module\":\"{}\",\"width\":{}}}",
287            escape_js_string(&s.name),
288            escape_js_string(&s.ty),
289            escape_js_string(&s.kind),
290            escape_js_string(&s.module),
291            s.width
292        ));
293    }
294    json.push_str("\n  ],\n  \"times\": [");
295    for (i, t) in times.iter().enumerate() {
296        if i > 0 {
297            json.push(',');
298        }
299        json.push_str(&t.to_string());
300    }
301    json.push_str("],\n  \"values\": {\n");
302    let names: Vec<&str> = typed.iter().map(|s| s.name.as_str()).collect();
303    for (ni, name) in names.iter().enumerate() {
304        if ni > 0 {
305            json.push_str(",\n");
306        }
307        json.push_str(&format!("    \"{}\": [", escape_js_string(name)));
308        for (ti, t) in times.iter().enumerate() {
309            if ti > 0 {
310                json.push(',');
311            }
312            let v = samples
313                .iter()
314                .find(|s| s.time == *t)
315                .and_then(|s| s.values.get(*name))
316                .copied()
317                .unwrap_or(0);
318            json.push_str(&v.to_string());
319        }
320        json.push(']');
321    }
322    json.push_str("\n  }\n}\n");
323    json
324}
325
326/// Upstream Tywaves-shaped sidecar (`wave.tywaves.json`) — FR125 first-class dump.
327///
328/// Distinct from FR117 `wave.typed.json`: carries `schemaVersion`,
329/// `data-bitloom-tywaves` marker field, and `viewer: "tywaves"` so an upstream
330/// (or stub) viewer can consume Bitloom typed waves without claiming FR117 alone.
331pub fn tywaves_wave_json(title: &str, samples: &[WaveSample], typed: &[TypedSignal]) -> String {
332    let base = typed_wave_json(title, samples, typed);
333    // Rewrite FR117 product header into FR125 Tywaves contract header.
334    let mut out = String::from(
335        "{\n  \"product\": \"Bitloom\",\n  \"fr\": \"FR125\",\n  \"viewer\": \"tywaves\",\n\
336         \"schemaVersion\": \"bitloom-tywaves-1\",\n  \"marker\": \"data-bitloom-tywaves\",\n",
337    );
338    if let Some(rest) = base.strip_prefix("{\n  \"product\": \"Bitloom\",\n  \"fr\": \"FR117\",\n")
339    {
340        out.push_str(rest);
341    } else {
342        // Fallback: still emit a valid FR125 envelope.
343        out.push_str(&format!(
344            "  \"title\": \"{}\",\n  \"signals\": [],\n  \"times\": [],\n  \"values\": {{}}\n}}\n",
345            escape_js_string(title)
346        ));
347    }
348    out
349}
350
351/// Shell launcher for upstream Tywaves viewer (FR125 T2).
352pub fn tywaves_launch_sh(tywaves_json_rel: &str) -> String {
353    format!(
354        "#!/usr/bin/env bash\n\
355         # Bitloom FR125 — launch upstream Tywaves (or BITLOOM_TYWAVES_BIN stub)\n\
356         set -euo pipefail\n\
357         ROOT=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n\
358         DUMP=\"$ROOT/{tywaves_json_rel}\"\n\
359         BIN=\"${{BITLOOM_TYWAVES_BIN:-}}\"\n\
360         if [[ -z \"$BIN\" ]]; then\n\
361           echo \"bitloom.tywaves-missing: set BITLOOM_TYWAVES_BIN to upstream Tywaves viewer\" >&2\n\
362           exit 2\n\
363         fi\n\
364         if [[ ! -x \"$BIN\" ]]; then\n\
365           echo \"bitloom.tywaves-missing: BITLOOM_TYWAVES_BIN not executable: $BIN\" >&2\n\
366           exit 2\n\
367         fi\n\
368         exec \"$BIN\" \"$DUMP\"\n"
369    )
370}
371
372/// Pinned upstream GUI / IDE plugin identities for FR134 G1 (beyond `BITLOOM_TYWAVES_BIN`).
373pub const TYWAVES_GUI_PACKAGE_ID: &str = "surfer-tywaves";
374pub const TYWAVES_GUI_VERSION: &str = "v0.3.2-tywaves-dev-SNAPSHOT";
375pub const TYWAVES_GUI_CHANNEL: &str =
376    "https://gitlab.com/rameloni/surfer-tywaves-demo/-/releases/v0.3.2-tywaves-SNAPSHOT";
377pub const TYWAVES_IDE_PLUGIN_ID: &str = "surfer-project.surfer";
378pub const TYWAVES_IDE_PLUGIN_CHANNEL: &str =
379    "https://marketplace.visualstudio.com/items?itemName=surfer-project.surfer";
380
381/// FR134 G2 checkable metadata (`tywaves.gui.manifest.json`).
382///
383/// Distinct from FR125 `wave.tywaves.json`: carries `tywaves.gui` /
384/// `tywaves.ide-plugin` capability marks and FR134 schema.
385pub fn tywaves_gui_manifest(title: &str) -> String {
386    format!(
387        "{{\n\
388         \"product\": \"Bitloom\",\n\
389         \"fr\": \"FR134\",\n\
390         \"schemaVersion\": \"bitloom-tywaves-gui-1\",\n\
391         \"marker\": \"data-bitloom-tywaves-gui\",\n\
392         \"title\": \"{title}\",\n\
393         \"tywaves.gui\": {{\n\
394         \"enabled\": true,\n\
395         \"packageId\": \"{TYWAVES_GUI_PACKAGE_ID}\",\n\
396         \"version\": \"{TYWAVES_GUI_VERSION}\"\n\
397         }},\n\
398         \"tywaves.ide-plugin\": {{\n\
399         \"enabled\": true,\n\
400         \"marketplaceId\": \"{TYWAVES_IDE_PLUGIN_ID}\",\n\
401         \"channel\": \"{TYWAVES_IDE_PLUGIN_CHANNEL}\"\n\
402         }},\n\
403         \"sidecar\": \"wave.tywaves.json\",\n\
404         \"note\": \"FR134 GUI/IDE depth beyond FR125 T1–T4; Tywaves runtime is not a design-crate dep\"\n\
405         }}\n",
406        title = escape_js_string(title),
407    )
408}
409
410/// FR134 G1 install descriptor (`tywaves.gui.install.json`) — version + distribution channel.
411pub fn tywaves_gui_install_json() -> String {
412    format!(
413        "{{\n\
414         \"product\": \"Bitloom\",\n\
415         \"fr\": \"FR134\",\n\
416         \"schemaVersion\": \"bitloom-tywaves-gui-install-1\",\n\
417         \"tywaves.gui\": {{\n\
418         \"packageId\": \"{TYWAVES_GUI_PACKAGE_ID}\",\n\
419         \"version\": \"{TYWAVES_GUI_VERSION}\",\n\
420         \"channel\": \"{TYWAVES_GUI_CHANNEL}\",\n\
421         \"installMarker\": \"BITLOOM_TYWAVES_GUI_OK\",\n\
422         \"envRoot\": \"BITLOOM_TYWAVES_GUI_ROOT\"\n\
423         }},\n\
424         \"tywaves.ide-plugin\": {{\n\
425         \"marketplaceId\": \"{TYWAVES_IDE_PLUGIN_ID}\",\n\
426         \"channel\": \"{TYWAVES_IDE_PLUGIN_CHANNEL}\",\n\
427         \"kind\": \"vscode-extension\"\n\
428         }},\n\
429         \"beyond\": \"BITLOOM_TYWAVES_BIN single-binary launch (FR125 T2) alone is not FR134\"\n\
430         }}\n"
431    )
432}
433
434/// Shell helper to validate / open FR134 GUI install root (G1/G3).
435pub fn tywaves_gui_install_sh() -> String {
436    format!(
437        "#!/usr/bin/env bash\n\
438         # Bitloom FR134 — validate upstream Tywaves GUI install (or stub root)\n\
439         set -euo pipefail\n\
440         ROOT=\"${{BITLOOM_TYWAVES_GUI_ROOT:-}}\"\n\
441         if [[ -z \"$ROOT\" ]]; then\n\
442           echo \"bitloom.tywaves-missing: set BITLOOM_TYWAVES_GUI_ROOT to upstream GUI install (or stub)\" >&2\n\
443           exit 2\n\
444         fi\n\
445         if [[ ! -d \"$ROOT\" ]]; then\n\
446           echo \"bitloom.tywaves-missing: BITLOOM_TYWAVES_GUI_ROOT is not a directory: $ROOT\" >&2\n\
447           exit 2\n\
448         fi\n\
449         if [[ ! -f \"$ROOT/BITLOOM_TYWAVES_GUI_OK\" ]]; then\n\
450           echo \"bitloom.tywaves-missing: GUI install marker BITLOOM_TYWAVES_GUI_OK not found under $ROOT\" >&2\n\
451           exit 2\n\
452         fi\n\
453         echo \"bitloom.tywaves: FR134 GUI root OK ($ROOT) — package {TYWAVES_GUI_PACKAGE_ID}@{TYWAVES_GUI_VERSION}\"\n\
454         echo \"bitloom.tywaves: IDE plugin channel {TYWAVES_IDE_PLUGIN_CHANNEL}\"\n"
455    )
456}
457
458/// Typed IDE waveform HTML (FR117 subset B): type/kind hierarchy beyond FR104 I1–I3.
459///
460/// Empty `typed` → explicit empty marker (must not silent-claim FR117).
461pub fn typed_wave_html(title: &str, samples: &[WaveSample], typed: &[TypedSignal]) -> String {
462    let mut out = String::from(
463        "<!DOCTYPE html><html><head><meta charset=\"utf-8\">\
464         <title>Bitloom typed IDE wave</title>\n\
465         <style>\n\
466         body{font-family:system-ui,sans-serif;margin:1rem;line-height:1.4;background:#f4f7fa;color:#122}\n\
467         .brand{color:#0b3d5c;font-weight:700;letter-spacing:.02em}\n\
468         .layout{display:grid;grid-template-columns:minmax(14rem,22rem) 1fr;gap:1rem;align-items:start}\n\
469         @media (max-width:800px){.layout{grid-template-columns:1fr}}\n\
470         .panel{background:#fff;border:1px solid #c5d0da;border-radius:4px;padding:.75rem}\n\
471         #signal-tree{list-style:none;padding-left:0;margin:0;max-height:28rem;overflow:auto}\n\
472         #signal-tree ul{list-style:none;padding-left:1rem;margin:.25rem 0}\n\
473         .mod-label{font-weight:600;color:#0b3d5c}\n\
474         .sig-btn{display:flex;flex-wrap:wrap;gap:.35rem;align-items:center;width:100%;\
475         text-align:left;border:0;background:transparent;padding:.35rem .25rem;cursor:pointer}\n\
476         .sig-node.selected{background:#e8f1f8}\n\
477         .sig-type{font-family:ui-monospace,monospace;font-size:.85rem;color:#0b5;background:#eef8f0;\
478         padding:.1rem .35rem;border-radius:3px}\n\
479         .sig-kind{font-size:.75rem;color:#567}\n\
480         #typed-wave-canvas{display:block;width:100%;max-width:100%;background:#fff;\
481         border:1px solid #c5d0da;border-radius:4px}\n\
482         .hint{font-size:.85rem;color:#456}\n\
483         .toolbar{margin:0 0 .5rem}\n\
484         .toolbar input[type=search]{min-width:12rem;padding:.35rem .5rem}\n\
485         #signal-meta dl{display:grid;grid-template-columns:6rem 1fr;gap:.25rem .5rem;margin:0}\n\
486         #signal-meta dt{font-weight:600;color:#456}\n\
487         #signal-meta dd{margin:0}\n\
488         </style></head><body>\n",
489    );
490    out.push_str("<p class=\"brand\">Bitloom</p>\n");
491    out.push_str(&format!(
492        "<h1>Typed IDE wave — {}</h1>\n",
493        escape_html(title)
494    ));
495    out.push_str(
496        "<p class=\"hint\">FR117 typed IDE waveform (NFR14 subset <strong>B</strong> — in-house). \
497         Signal tree carries <strong>type / kind / module</strong> semantics beyond FR104 \
498         <code>interactive.html</code> I1–I3 name-only timeline. \
499         Not Tywaves (subset A deferred). Not FR114 coverage GUI. \
500         Sibling <code>wave.vcd</code> / <code>interactive.html</code> remain (NFR48).</p>\n",
501    );
502
503    if typed.is_empty() {
504        out.push_str(
505            "<div id=\"root\" data-bitloom-typed-wave=\"empty\" class=\"typed-meta-missing\">\
506             <p><em>(no typed signals)</em> — typed meta missing; must not silent-claim FR117.</p>\
507             </div>\n</body></html>\n",
508        );
509        return out;
510    }
511
512    let payload = typed_wave_json(title, samples, typed);
513    // Strip outer newlines for script JSON embed — reuse compact form from payload
514    out.push_str(
515        "<div id=\"root\" class=\"bitloom-typed-wave\" data-bitloom-typed-wave=\"1\">\n\
516         <div class=\"toolbar\">\n\
517         <label for=\"typed-search\">Filter typed signals </label>\n\
518         <input type=\"search\" id=\"typed-search\" placeholder=\"name / type / kind / module\" \
519          aria-label=\"typed signal filter\" />\n\
520         </div>\n\
521         <div class=\"layout\">\n\
522         <div class=\"panel hierarchy typed-tree\">\n\
523         <h2>Typed signal hierarchy</h2>\n\
524         <ul id=\"signal-tree\" class=\"signal-tree\"></ul>\n\
525         <h2>Selected metadata</h2>\n\
526         <div id=\"signal-meta\"></div>\n\
527         </div>\n\
528         <div class=\"panel\">\n\
529         <h2>Value timeline</h2>\n\
530         <canvas id=\"typed-wave-canvas\" width=\"720\" height=\"280\" \
531          role=\"img\" aria-label=\"typed waveform timeline\"></canvas>\n\
532         </div>\n\
533         </div>\n\
534         </div>\n",
535    );
536    out.push_str("<script id=\"typed-wave-data\" type=\"application/json\">");
537    out.push_str(&payload);
538    out.push_str("</script>\n<script>\n");
539    out.push_str(TYPED_WAVE_JS);
540    out.push_str("\n</script>\n");
541    out.push_str("<p>Unrelated to <code>samitbasu/rhdl</code>.</p>\n</body></html>\n");
542    out
543}
544
545/// Browsable timing / wave HTML (product path — not GTKWave-only).
546pub fn timing_html(title: &str, samples: &[WaveSample]) -> String {
547    let mut signal_names: Vec<String> = samples
548        .iter()
549        .flat_map(|s| s.values.keys().cloned())
550        .collect();
551    signal_names.sort();
552    signal_names.dedup();
553
554    let mut out = String::from(
555        "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>Bitloom timing</title>\n\
556         <style>body{font-family:system-ui,sans-serif;margin:1.5rem;line-height:1.4}\n\
557         .brand{color:#0b3d5c;font-weight:700}\n\
558         table{border-collapse:collapse;font-size:0.9rem}\n\
559         th,td{border:1px solid #ccc;padding:0.25rem 0.5rem;text-align:left}\n\
560         th{background:#f0f4f8}\n\
561         .lane{font-family:ui-monospace,monospace;white-space:pre}\n\
562         </style></head><body>\n",
563    );
564    out.push_str("<p class=\"brand\">Bitloom</p>\n");
565    out.push_str(&format!("<h1>Timing — {}</h1>\n", escape_html(title)));
566    out.push_str(
567        "<p>Product timing view from tick/VCD samples. GTKWave/Surfer remain optional \
568         viewers for the sibling <code>.vcd</code>; they are <strong>not</strong> the sole path.</p>\n",
569    );
570
571    if samples.is_empty() || signal_names.is_empty() {
572        out.push_str("<p><em>(no samples)</em></p>\n</body></html>\n");
573        return out;
574    }
575
576    out.push_str("<h2>Value table</h2>\n<table>\n<tr><th>time</th>");
577    for n in &signal_names {
578        out.push_str(&format!("<th>{}</th>", escape_html(n)));
579    }
580    out.push_str("</tr>\n");
581    for s in samples {
582        out.push_str(&format!("<tr><td>{}</td>", s.time));
583        for n in &signal_names {
584            let v = s.values.get(n).copied().unwrap_or(0);
585            out.push_str(&format!("<td>{v}</td>"));
586        }
587        out.push_str("</tr>\n");
588    }
589    out.push_str("</table>\n");
590
591    out.push_str("<h2>ASCII timing lanes</h2>\n<pre class=\"lane\">\n");
592    for n in &signal_names {
593        let mut lane = format!("{:>12} ", n);
594        let mut prev: Option<u64> = None;
595        for s in samples {
596            let v = s.values.get(n).copied().unwrap_or(0);
597            if prev == Some(v) {
598                lane.push('-');
599            } else {
600                lane.push_str(&format!("[{v}]"));
601                prev = Some(v);
602            }
603        }
604        out.push_str(&lane);
605        out.push('\n');
606    }
607    out.push_str("</pre>\n");
608    out.push_str("<p>Unrelated to <code>samitbasu/rhdl</code>.</p>\n</body></html>\n");
609    out
610}
611
612/// Parse a minimal VCD (as emitted by `bitloom-sim`) into wave samples.
613pub fn samples_from_vcd(vcd: &str) -> Result<Vec<WaveSample>, String> {
614    let mut samples = Vec::new();
615    let mut current = WaveSample::default();
616    let mut started = false;
617    for line in vcd.lines() {
618        let line = line.trim();
619        if let Some(rest) = line.strip_prefix('#') {
620            if started && !current.values.is_empty() {
621                samples.push(current.clone());
622            }
623            let t: u64 = rest
624                .split_whitespace()
625                .next()
626                .ok_or_else(|| "empty VCD time".to_string())?
627                .parse()
628                .map_err(|e| format!("bad VCD time: {e}"))?;
629            current = WaveSample {
630                time: t,
631                values: current.values.clone(),
632            };
633            started = true;
634        } else if let Some(rest) = line.strip_prefix('b') {
635            let mut parts = rest.split_whitespace();
636            let bits = parts
637                .next()
638                .ok_or_else(|| "VCD b-line missing bits".to_string())?;
639            let name = parts
640                .next()
641                .ok_or_else(|| "VCD b-line missing name".to_string())?;
642            let val = u64::from_str_radix(bits, 2).unwrap_or(0);
643            current.values.insert(name.to_string(), val);
644        }
645    }
646    if started {
647        samples.push(current);
648    }
649    if samples.is_empty() {
650        return Err("VCD contained no time samples".into());
651    }
652    Ok(samples)
653}
654
655/// Collect `(parent_module, instance_name, child_module)` edges.
656pub fn instance_edges(hir: &FrozenHir) -> Vec<(String, String, String)> {
657    let mut edges = Vec::new();
658    for m in &hir.circuit().modules {
659        for stmt in &m.body {
660            if let Stmt::Instance(inst) = stmt {
661                edges.push((m.name.clone(), inst.name.clone(), inst.module.clone()));
662            }
663        }
664    }
665    edges
666}
667
668fn mermaid_hierarchy(hir: &FrozenHir) -> String {
669    let mut s = String::from("flowchart TD\n");
670    let top = &hir.abi_name;
671    s.push_str(&format!(
672        "  {id}[\"{label}\"]\n",
673        id = mmd_id(top),
674        label = top
675    ));
676    for (parent, name, module) in instance_edges(hir) {
677        let child_label = format!("{name}:{module}");
678        let child_id = mmd_id(&format!("{parent}__{name}"));
679        s.push_str(&format!(
680            "  {cid}[\"{clabel}\"]\n  {pid} --> {cid}\n",
681            cid = child_id,
682            clabel = child_label,
683            pid = mmd_id(&parent),
684        ));
685    }
686    s
687}
688
689fn mmd_id(raw: &str) -> String {
690    let mut out = String::from("n_");
691    for c in raw.chars() {
692        if c.is_ascii_alphanumeric() {
693            out.push(c);
694        } else {
695            out.push('_');
696        }
697    }
698    out
699}
700
701fn escape_html(s: &str) -> String {
702    s.replace('&', "&amp;")
703        .replace('<', "&lt;")
704        .replace('>', "&gt;")
705        .replace('"', "&quot;")
706}
707
708#[cfg(test)]
709mod tests {
710    use bitloom_builder::{ElaborateSession, GroundType, Span};
711
712    use super::*;
713
714    #[test]
715    fn html_lists_ports() {
716        let mut s = ElaborateSession::new("t");
717        s.begin_module("M", Span::default());
718        s.add_input("clk", GroundType::Clock, Span::default());
719        s.add_input("rst", GroundType::Reset, Span::default());
720        s.add_output("y", GroundType::UInt { width: 1 }, Span::default());
721        s.end_module();
722        let hir = s.finish().unwrap();
723        let html = to_html(&hir);
724        assert!(html.contains("Bitloom"));
725        assert!(html.contains("<strong>M</strong>"));
726        assert!(html.contains("port y"));
727        assert!(html.contains("Instance hierarchy"));
728        assert!(html.contains("flowchart TD"));
729    }
730
731    #[test]
732    fn html_lists_instance_hierarchy() {
733        let mut s = ElaborateSession::new("Top");
734        s.begin_module("Child", Span::default());
735        s.add_input("clk", GroundType::Clock, Span::default());
736        s.add_input("rst", GroundType::Reset, Span::default());
737        s.add_output("y", GroundType::UInt { width: 1 }, Span::default());
738        s.end_module();
739        s.begin_module("Top", Span::default());
740        s.add_input("clk", GroundType::Clock, Span::default());
741        s.add_input("rst", GroundType::Reset, Span::default());
742        s.add_output("y", GroundType::UInt { width: 1 }, Span::default());
743        s.add_instance(
744            "u0",
745            "Child",
746            vec![
747                ("clk".into(), "clk".into()),
748                ("rst".into(), "rst".into()),
749                ("y".into(), "y".into()),
750            ],
751            vec![],
752            Span::default(),
753        );
754        s.end_module();
755        let hir = s.finish().unwrap();
756        let html = to_html(&hir);
757        assert!(html.contains("Top → <strong>u0</strong> : Child"), "{html}");
758        assert!(html.contains("u0:Child"), "{html}");
759    }
760
761    #[test]
762    fn timing_html_from_samples_and_vcd() {
763        let samples = vec![
764            WaveSample {
765                time: 0,
766                values: BTreeMap::from([("x".into(), 1), ("y".into(), 1)]),
767            },
768            WaveSample {
769                time: 1,
770                values: BTreeMap::from([("x".into(), 2), ("y".into(), 2)]),
771            },
772        ];
773        let html = timing_html("demo", &samples);
774        assert!(html.contains("Bitloom") && html.contains("Timing"));
775        assert!(html.contains("Value table") && html.contains("[1]"));
776
777        let vcd = "\
778$timescale 1ns $end
779$scope module demo $end
780$var wire 8 x x $end
781$var wire 8 y y $end
782$upscope $end
783$enddefinitions $end
784#0
785b1 x
786b1 y
787#1
788b10 x
789b10 y
790";
791        let parsed = samples_from_vcd(vcd).unwrap();
792        assert_eq!(parsed.len(), 2);
793        assert_eq!(parsed[1].values.get("x"), Some(&2));
794        let from_vcd = timing_html("demo", &parsed);
795        assert!(from_vcd.contains("Value table"));
796    }
797
798    #[test]
799    fn interactive_wave_html_has_i1_i3_markers() {
800        let samples = vec![
801            WaveSample {
802                time: 0,
803                values: BTreeMap::from([("clk".into(), 0), ("x".into(), 1)]),
804            },
805            WaveSample {
806                time: 1,
807                values: BTreeMap::from([("clk".into(), 1), ("x".into(), 2)]),
808            },
809        ];
810        let html = interactive_wave_html("demo", &samples);
811        assert!(html.contains("Bitloom"));
812        assert!(html.contains("data-bitloom-interactive-wave"));
813        assert!(html.contains("wave-canvas") || html.contains("<canvas"));
814        assert!(html.contains("zoom") || html.contains("Zoom"));
815        assert!(html.contains("signal-search") || html.contains("search"));
816    }
817
818    #[test]
819    fn typed_wave_html_exposes_types_beyond_names() {
820        let mut s = ElaborateSession::new("Top");
821        s.begin_module("Top", Span::default());
822        s.add_input("clk", GroundType::Clock, Span::default());
823        s.add_input("rst", GroundType::Reset, Span::default());
824        s.add_input("x", GroundType::UInt { width: 8 }, Span::default());
825        s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
826        s.end_module();
827        let hir = s.finish().unwrap();
828        let typed = typed_signals_from_hir(&hir);
829        assert!(typed.iter().any(|t| t.ty.contains("UInt") && t.name == "x"));
830        assert!(typed.iter().any(|t| t.ty == "Clock"));
831
832        let samples = vec![WaveSample {
833            time: 0,
834            values: BTreeMap::from([("clk".into(), 0), ("x".into(), 1)]),
835        }];
836        let html = typed_wave_html("demo", &samples, &typed);
837        assert!(html.contains("data-bitloom-typed-wave=\"1\""));
838        assert!(html.contains("signal-tree") || html.contains("Typed signal hierarchy"));
839        assert!(html.contains("UInt<8>") || html.contains("data-signal-type"));
840        assert!(html.contains("Bitloom"));
841
842        let empty = typed_wave_html("demo", &samples, &[]);
843        assert!(empty.contains("data-bitloom-typed-wave=\"empty\""));
844
845        let json = typed_wave_json("demo", &samples, &typed);
846        assert!(json.contains("\"ty\"") && json.contains("\"signals\""));
847    }
848}