Skip to main content

bitloom_firrtl/
lib.rs

1//! FIRRTL 6.0.0 text import/export (AD-3, AD-8). No firtool invocation.
2
3use bitloom_hir::{
4    Artifact, Assign, AssignExpr, AssignTarget, EmittedFile, FrozenHir, GroundType, Instance,
5    Module, Port, PortConnect, PortDirection, Process, ProcessKind, Stmt,
6};
7
8mod chisel;
9pub use chisel::{
10    CHISEL_TARGET, ChiselGenError, FIRTOOL_TARGET, IdiomaticCheckError,
11    check_chisel_ecosystem_fr176, check_chisel_style_guide_fr130, check_chisel_style_guide_fr165,
12    check_chisel_style_guide_pack_fr188, check_chisel_style_linter_fr181, check_idiomatic_chisel,
13    check_idiomatic_chisel_fr111, check_idiomatic_chisel_fr122, emit_chisel,
14    emit_chisel_ecosystem_fr176, emit_chisel_idiomatic, emit_chisel_idiomatic_fr111,
15    emit_chisel_idiomatic_fr122, emit_chisel_style_guide_fr130, emit_chisel_style_guide_fr165,
16    emit_chisel_style_guide_pack_fr188, emit_chisel_style_linter_fr181,
17};
18
19/// Emit `<abi_name>.fir` with FIRRTL version 6.0.0 header.
20pub fn emit(hir: &FrozenHir) -> Artifact {
21    let mut body = String::from("FIRRTL version 6.0.0\n");
22    body.push_str(&format!("circuit {} :\n", hir.abi_name));
23    for m in &hir.circuit().modules {
24        body.push_str(&emit_module(
25            m,
26            m.name == hir.abi_name,
27            &hir.circuit().modules,
28        ));
29    }
30    let path = format!("{}.fir", hir.abi_name);
31    Artifact {
32        files: vec![EmittedFile {
33            path: path.clone(),
34            contents: body,
35        }],
36        filelist: vec![path],
37    }
38}
39
40fn fir_type(ty: &GroundType) -> String {
41    match ty {
42        GroundType::UInt { width } => format!("UInt<{width}>"),
43        GroundType::SInt { width } => format!("SInt<{width}>"),
44        GroundType::Clock => "Clock".into(),
45        GroundType::Reset => "Reset".into(),
46        GroundType::Bool => "UInt<1>".into(),
47        GroundType::Analog => "Analog".into(),
48    }
49}
50
51fn emit_expr(expr: &AssignExpr, m: &Module, target: &str) -> String {
52    match expr {
53        AssignExpr::Ref(n) => n.clone(),
54        AssignExpr::Lit(v) => format!("UInt({v})"),
55        AssignExpr::Inc(n) => {
56            let literal = if matches!(signal_type(m, n), Some(GroundType::SInt { .. })) {
57                "SInt(1)"
58            } else {
59                "UInt(1)"
60            };
61            format!("add({n}, {literal})")
62        }
63        AssignExpr::Add(a, b) => format!("add({a}, {b})"),
64        AssignExpr::Sub(a, b) => format!("sub({a}, {b})"),
65        AssignExpr::And(a, b) => format!("and({a}, {b})"),
66        AssignExpr::Or(a, b) => format!("or({a}, {b})"),
67        AssignExpr::Xor(a, b) => format!("xor({a}, {b})"),
68        AssignExpr::Shl(a, b) => bounded_left_shift(m, a, b, target),
69        AssignExpr::Shr(a, b) => {
70            let value = unsigned_ref(m, a);
71            format!("dshr({value}, {b})")
72        }
73        AssignExpr::Ult { lhs, rhs, .. } => format!("lt({lhs}, {rhs})"),
74        AssignExpr::Slt { lhs, rhs, .. } => format!("lt(asSInt({lhs}), asSInt({rhs}))"),
75        AssignExpr::Sar { value, shamt, .. } => format!("dshr(asSInt({value}), {shamt})"),
76        AssignExpr::Slice { src, lo, width } => format!("bits({src}, {}, {lo})", lo + width - 1),
77        AssignExpr::Concat { high, low, .. } => format!("cat({high}, {low})"),
78        AssignExpr::ZeroExtend { src, to_width, .. } => format!("pad({src}, {to_width})"),
79        AssignExpr::SignExtend { src, to_width, .. } => {
80            format!("asUInt(pad(asSInt({src}), {to_width}))")
81        }
82        AssignExpr::Eq(a, b) => format!("eq({a}, {b})"),
83        AssignExpr::Mux { sel, t, f } => format!("mux({sel}, {t}, {f})"),
84        AssignExpr::MemRead { mem, addr } => format!("{mem}[{addr}]"),
85    }
86}
87
88fn signal_type<'a>(m: &'a Module, name: &str) -> Option<&'a GroundType> {
89    m.ports
90        .iter()
91        .find(|p| p.name == name)
92        .map(|p| &p.ty)
93        .or_else(|| {
94            m.body.iter().find_map(|stmt| match stmt {
95                Stmt::RegDecl { name: n, ty, .. } | Stmt::WireDecl { name: n, ty, .. }
96                    if n == name =>
97                {
98                    Some(ty)
99                }
100                _ => None,
101            })
102        })
103}
104
105fn unsigned_ref(m: &Module, name: &str) -> String {
106    if matches!(signal_type(m, name), Some(GroundType::SInt { .. })) {
107        format!("asUInt({name})")
108    } else {
109        name.into()
110    }
111}
112
113fn bounded_left_shift(m: &Module, value: &str, shift: &str, target: &str) -> String {
114    let width = match signal_type(m, target) {
115        Some(GroundType::UInt { width } | GroundType::SInt { width }) => *width,
116        _ => 1,
117    };
118    // FIRRTL dshl's inferred width grows exponentially with shift-operand width.
119    // Bound the shift operand, but preserve out-of-range zero semantics by guarding
120    // the original (untruncated) shift amount. Width-one needs no dshl at all.
121    let value = unsigned_ref(m, value);
122    let shifted = if width <= 1 {
123        value.to_string()
124    } else {
125        let shift_width = match signal_type(m, shift) {
126            Some(GroundType::UInt { width } | GroundType::SInt { width }) => *width,
127            _ => 1,
128        };
129        let high = (31 - (width - 1).leading_zeros()).min(shift_width - 1);
130        format!("dshl({value}, bits({shift}, {high}, 0))")
131    };
132    format!("mux(geq({shift}, UInt({width})), UInt(0), {shifted})")
133}
134
135fn emit_assignment_expr(expr: &AssignExpr, m: &Module, target: &str) -> String {
136    if let AssignExpr::ZeroExtend { src, to_width, .. } = expr {
137        let padded = format!("pad({}, {to_width})", unsigned_ref(m, src));
138        return if matches!(signal_type(m, target), Some(GroundType::SInt { .. })) {
139            format!("asSInt({padded})")
140        } else {
141            padded
142        };
143    }
144    if let AssignExpr::SignExtend { src, to_width, .. } = expr {
145        if matches!(signal_type(m, target), Some(GroundType::SInt { .. })) {
146            return format!("pad(asSInt({src}), {to_width})");
147        }
148    }
149    let expression = emit_expr(expr, m, target);
150    if matches!(expr, AssignExpr::Shl(..) | AssignExpr::Shr(..))
151        && matches!(signal_type(m, target), Some(GroundType::SInt { .. }))
152    {
153        let width = match signal_type(m, target) {
154            Some(GroundType::SInt { width }) => *width,
155            _ => unreachable!(),
156        };
157        // Logical results zero-extend before adopting a signed destination type.
158        format!("asSInt(pad({expression}, {width}))")
159    } else {
160        expression
161    }
162}
163
164fn emit_module(m: &Module, is_top: bool, modules: &[Module]) -> String {
165    let visibility = if is_top { "public " } else { "" };
166    let mut out = format!("  {visibility}module {} :\n", m.name);
167    for p in &m.ports {
168        let dir = match p.direction {
169            PortDirection::Input => "input",
170            PortDirection::Output => "output",
171            PortDirection::InOut => "inout",
172        };
173        let ty = if matches!(p.ty, GroundType::Reset) {
174            // Public FIRRTL ports require concrete reset types. Preserve our
175            // logical reset identity in a comment for the subset importer.
176            "UInt<1> ; bitloom-type: Reset".to_string()
177        } else {
178            fir_type(&p.ty)
179        };
180        out.push_str(&format!("    {} {}: {}\n", dir, p.name, ty));
181    }
182    for stmt in &m.body {
183        match stmt {
184            Stmt::WireDecl { name, ty, .. } => {
185                out.push_str(&format!("    wire {}: {}\n", name, fir_type(ty)));
186            }
187            Stmt::RegDecl {
188                name,
189                ty,
190                clock,
191                reset,
192                ..
193            } => {
194                let zero = if matches!(ty, GroundType::SInt { .. }) {
195                    "SInt(0)"
196                } else {
197                    "UInt(0)"
198                };
199                out.push_str(&format!(
200                    "    regreset {}: {}, {}, {}, {}\n",
201                    name,
202                    fir_type(ty),
203                    clock,
204                    reset,
205                    zero
206                ));
207            }
208            Stmt::MemDecl {
209                name,
210                depth,
211                width,
212                sync_read,
213                init,
214                ..
215            } => {
216                let ruw = if *sync_read { "smem" } else { "cmem" };
217                out.push_str(&format!(
218                    "    ; CHIRRTL-friendly {ruw} {name} : UInt<{width}>[{depth}]\n"
219                ));
220                if let Some(words) = init {
221                    let preview: Vec<String> = words.iter().map(|w| w.to_string()).collect();
222                    out.push_str(&format!(
223                        "    ; mem-init {name} = [{}]\n",
224                        preview.join(", ")
225                    ));
226                }
227                let rlat = if *sync_read { 1 } else { 0 };
228                out.push_str(&format!(
229                    "    mem {name} :\n      data-type => UInt<{width}>\n      depth => {depth}\n      read-latency => {rlat}\n      write-latency => 1\n      readwriter => rw\n      read-under-write => undefined\n"
230                ));
231            }
232            Stmt::Process(p) => {
233                for a in &p.assigns {
234                    match (&a.target, p.kind) {
235                        (AssignTarget::Net(n), ProcessKind::Combinational) => {
236                            out.push_str(&format!(
237                                "    connect {n}, {}\n",
238                                emit_assignment_expr(&a.expr, m, n)
239                            ));
240                        }
241                        (AssignTarget::RegD(n), ProcessKind::Sequential) => {
242                            out.push_str(&format!(
243                                "    connect {n}, {}\n",
244                                emit_assignment_expr(&a.expr, m, n)
245                            ));
246                        }
247                        (AssignTarget::MemWrite { mem, addr, we }, ProcessKind::Sequential) => {
248                            let gate = we.as_ref().map(|e| format!(" if {e}")).unwrap_or_default();
249                            out.push_str(&format!(
250                                "    ; mem write{gate} {mem}[{addr}] <= {}\n",
251                                emit_expr(&a.expr, m, mem)
252                            ));
253                        }
254                        _ => {}
255                    }
256                }
257            }
258            Stmt::Instance(inst) => {
259                out.push_str(&format!("    inst {} of {}\n", inst.name, inst.module));
260                for c in &inst.connects {
261                    if !c.dangling {
262                        let output = modules
263                            .iter()
264                            .find(|child| child.name == inst.module)
265                            .and_then(|child| child.ports.iter().find(|p| p.name == c.child_port))
266                            .is_some_and(|p| p.direction == PortDirection::Output);
267                        if output {
268                            out.push_str(&format!(
269                                "    connect {}, {}.{}\n",
270                                c.parent_net, inst.name, c.child_port
271                            ));
272                        } else {
273                            out.push_str(&format!(
274                                "    connect {}.{}, {}\n",
275                                inst.name, c.child_port, c.parent_net
276                            ));
277                        }
278                    }
279                }
280            }
281        }
282    }
283    out
284}
285
286/// Import a FIRRTL 6 subset into FrozenHir via the same private freeze path.
287pub fn import(text: &str) -> Result<FrozenHir, bitloom_hir::Diagnostics> {
288    if !text.contains("FIRRTL version 6.0.0") {
289        return Err(bitloom_hir::Diagnostics(vec![bitloom_hir::Diagnostic {
290            span: bitloom_hir::Span::default(),
291            code: "rhdl::E0401".into(),
292            en: "FIRRTL import requires 'FIRRTL version 6.0.0' header".into(),
293            zh: "FIRRTL 导入需要 'FIRRTL version 6.0.0' 头".into(),
294        }]));
295    }
296    if text.contains("Analog") || text.contains("assert") || text.contains("chirrtl") {
297        return Err(bitloom_hir::Diagnostics(vec![bitloom_hir::Diagnostic {
298            span: bitloom_hir::Span::default(),
299            code: "rhdl::E0402".into(),
300            en: "import rejects Analog/InOut, properties, and CHIRRTL mem".into(),
301            zh: "导入拒绝 Analog/InOut、property 与 CHIRRTL mem".into(),
302        }]));
303    }
304
305    let mut circuit_name = String::from("Imported");
306    let mut modules: Vec<Module> = Vec::new();
307    let mut current: Option<Module> = None;
308    let mut comb_assigns: Vec<Assign> = Vec::new();
309    let mut seq_assigns: Vec<Assign> = Vec::new();
310    let mut import_errs: Vec<bitloom_hir::Diagnostic> = Vec::new();
311
312    let flush_processes = |m: &mut Module, comb: &mut Vec<Assign>, seq: &mut Vec<Assign>| {
313        if !comb.is_empty() {
314            m.body.push(Stmt::Process(Process {
315                kind: ProcessKind::Combinational,
316                assigns: std::mem::take(comb),
317                span: bitloom_hir::Span::default(),
318            }));
319        }
320        if !seq.is_empty() {
321            m.body.push(Stmt::Process(Process {
322                kind: ProcessKind::Sequential,
323                assigns: std::mem::take(seq),
324                span: bitloom_hir::Span::default(),
325            }));
326        }
327    };
328
329    for line in text.lines() {
330        let line = line.trim();
331        if let Some(rest) = line.strip_prefix("circuit ") {
332            circuit_name = rest.trim_end_matches(" :").trim().to_string();
333        } else if let Some(rest) = line
334            .strip_prefix("module ")
335            .or_else(|| line.strip_prefix("public module "))
336        {
337            if let Some(mut m) = current.take() {
338                flush_processes(&mut m, &mut comb_assigns, &mut seq_assigns);
339                modules.push(m);
340            }
341            let name = rest.trim_end_matches(" :").trim().to_string();
342            current = Some(Module {
343                name,
344                ports: Vec::new(),
345                body: Vec::new(),
346                span: bitloom_hir::Span::default(),
347            });
348        } else if let Some(m) = current.as_mut() {
349            if let Some(rest) = line.strip_prefix("input ") {
350                if let Some((name, ty)) = rest.split_once(':') {
351                    m.ports.push(Port {
352                        name: name.trim().to_string(),
353                        direction: PortDirection::Input,
354                        ty: parse_ty(ty.trim()),
355                        span: bitloom_hir::Span::default(),
356                    });
357                }
358            } else if let Some(rest) = line.strip_prefix("output ") {
359                if let Some((name, ty)) = rest.split_once(':') {
360                    m.ports.push(Port {
361                        name: name.trim().to_string(),
362                        direction: PortDirection::Output,
363                        ty: parse_ty(ty.trim()),
364                        span: bitloom_hir::Span::default(),
365                    });
366                }
367            } else if let Some(rest) = line.strip_prefix("wire ") {
368                if let Some((name, ty)) = rest.split_once(':') {
369                    m.body.push(Stmt::WireDecl {
370                        name: name.trim().to_string(),
371                        ty: parse_ty(ty.trim()),
372                        span: bitloom_hir::Span::default(),
373                    });
374                }
375            } else if let Some(rest) = line.strip_prefix("regreset ") {
376                if let Some((name, declaration)) = rest.split_once(':') {
377                    let parts: Vec<_> = declaration.split(',').map(str::trim).collect();
378                    if parts.len() == 4 && matches!(parts[3], "UInt(0)" | "SInt(0)") {
379                        m.body.push(Stmt::RegDecl {
380                            name: name.trim().into(),
381                            ty: parse_ty(parts[0]),
382                            clock: parts[1].into(),
383                            reset: parts[2].into(),
384                            async_reset: false,
385                            has_enable: false,
386                            span: bitloom_hir::Span::default(),
387                        });
388                    } else {
389                        import_errs.push(bitloom_hir::Diagnostic {
390                            span: bitloom_hir::Span::default(),
391                            code: "rhdl::E0403".into(),
392                            en: "import supports only zero-reset regreset declarations".into(),
393                            zh: "导入仅支持零复位 regreset 声明".into(),
394                        });
395                    }
396                }
397            } else if let Some(rest) = line.strip_prefix("reg ") {
398                // reg count: UInt<8>, clk with:
399                if let Some((lhs, _)) = rest.split_once(" with:") {
400                    if let Some((name, ty_clk)) = lhs.split_once(':') {
401                        let name = name.trim().to_string();
402                        let mut parts = ty_clk.split(',');
403                        let ty = parse_ty(parts.next().unwrap_or("UInt<1>").trim());
404                        let clock = parts.next().unwrap_or("clk").trim().to_string();
405                        m.body.push(Stmt::RegDecl {
406                            name,
407                            ty,
408                            clock,
409                            reset: "rst".into(),
410                            async_reset: false,
411                            has_enable: false,
412                            span: bitloom_hir::Span::default(),
413                        });
414                    }
415                }
416            } else if let Some(rest) = line.strip_prefix("inst ") {
417                // inst u0 of Child
418                if let Some((iname, rest)) = rest.split_once(" of ") {
419                    m.body.push(Stmt::Instance(Instance {
420                        name: iname.trim().to_string(),
421                        module: rest.trim().to_string(),
422                        connects: Vec::new(),
423                        params: Vec::new(),
424                        span: bitloom_hir::Span::default(),
425                    }));
426                }
427            } else if let Some((lhs, rhs)) = line
428                .strip_prefix("connect ")
429                .and_then(|s| s.split_once(", "))
430                .or_else(|| line.split_once(" <= "))
431            {
432                let lhs = lhs.trim();
433                let rhs = rhs.trim();
434                // Bitloom emit: `inst.port <= parent`. firtool/Chisel output often uses
435                // `parent <= inst.port` for child outputs (FR46 reverse).
436                let mut took_inst = false;
437                if let Some((inst, port)) = lhs.split_once('.') {
438                    if let Some(Stmt::Instance(i)) = m
439                        .body
440                        .iter_mut()
441                        .rev()
442                        .find(|s| matches!(s, Stmt::Instance(ii) if ii.name == inst))
443                    {
444                        i.connects.push(PortConnect {
445                            child_port: port.to_string(),
446                            parent_net: rhs.to_string(),
447                            span: bitloom_hir::Span::default(),
448                            dangling: false,
449                        });
450                    } else {
451                        import_errs.push(bitloom_hir::Diagnostic {
452                            span: bitloom_hir::Span::default(),
453                            code: "rhdl::E0403".into(),
454                            en: format!(
455                                "import rejects unknown instance connect `{inst}.{port} <= …` (no matching `inst {inst}`)"
456                            ),
457                            zh: format!(
458                                "导入拒绝未知实例连接 `{inst}.{port} <= …`(无匹配的 `inst {inst}`)"
459                            ),
460                        });
461                    }
462                    took_inst = true;
463                } else if let Some((inst, port)) = rhs.split_once('.') {
464                    if let Some(Stmt::Instance(i)) = m
465                        .body
466                        .iter_mut()
467                        .rev()
468                        .find(|s| matches!(s, Stmt::Instance(ii) if ii.name == inst))
469                    {
470                        i.connects.push(PortConnect {
471                            child_port: port.to_string(),
472                            parent_net: lhs.to_string(),
473                            span: bitloom_hir::Span::default(),
474                            dangling: false,
475                        });
476                    } else {
477                        import_errs.push(bitloom_hir::Diagnostic {
478                            span: bitloom_hir::Span::default(),
479                            code: "rhdl::E0403".into(),
480                            en: format!(
481                                "import rejects unknown `… <= {inst}.{port}` (no matching `inst {inst}`; will not treat as ordinary assign)"
482                            ),
483                            zh: format!(
484                                "导入拒绝未知 `… <= {inst}.{port}`(无匹配的 `inst {inst}`;不会降为普通赋值)"
485                            ),
486                        });
487                    }
488                    took_inst = true;
489                }
490                if !took_inst {
491                    let expr = parse_expr(rhs, m, lhs);
492                    let is_reg = m
493                        .body
494                        .iter()
495                        .any(|s| matches!(s, Stmt::RegDecl { name, .. } if name == lhs));
496                    let a = Assign {
497                        target: if is_reg {
498                            AssignTarget::RegD(lhs.to_string())
499                        } else {
500                            AssignTarget::Net(lhs.to_string())
501                        },
502                        expr,
503                        span: bitloom_hir::Span::default(),
504                    };
505                    if is_reg {
506                        seq_assigns.push(a);
507                    } else {
508                        comb_assigns.push(a);
509                    }
510                }
511            }
512        }
513    }
514    if let Some(mut m) = current.take() {
515        flush_processes(&mut m, &mut comb_assigns, &mut seq_assigns);
516        modules.push(m);
517    }
518
519    if !import_errs.is_empty() {
520        return Err(bitloom_hir::Diagnostics(import_errs));
521    }
522
523    let mut owned = bitloom_hir::BuilderOwnedHir::new(circuit_name);
524    for m in modules {
525        owned.add_module(m);
526    }
527    bitloom_hir::seal_from_builder(owned)
528}
529
530/// FR46: public port name / width / direction round-trip between two FrozenHir circuits.
531/// Modules are matched by name; port order may differ.
532pub fn ports_roundtrip_ok(expected: &FrozenHir, got: &FrozenHir) -> Result<(), String> {
533    let exp: std::collections::HashMap<&str, &Module> = expected
534        .circuit()
535        .modules
536        .iter()
537        .map(|m| (m.name.as_str(), m))
538        .collect();
539    let got_map: std::collections::HashMap<&str, &Module> = got
540        .circuit()
541        .modules
542        .iter()
543        .map(|m| (m.name.as_str(), m))
544        .collect();
545    if exp.len() != got_map.len() {
546        return Err(format!(
547            "module count: expected {}, got {}",
548            exp.len(),
549            got_map.len()
550        ));
551    }
552    for (name, em) in &exp {
553        let gm = got_map
554            .get(name)
555            .ok_or_else(|| format!("missing module `{name}` after import"))?;
556        if em.ports.len() != gm.ports.len() {
557            return Err(format!(
558                "module `{name}` port count: expected {}, got {}",
559                em.ports.len(),
560                gm.ports.len()
561            ));
562        }
563        let mut gp: std::collections::HashMap<&str, &Port> =
564            gm.ports.iter().map(|p| (p.name.as_str(), p)).collect();
565        for ep in &em.ports {
566            let p = gp
567                .remove(ep.name.as_str())
568                .ok_or_else(|| format!("module `{name}` missing port `{}`", ep.name))?;
569            if p.direction != ep.direction {
570                return Err(format!(
571                    "module `{name}` port `{}` direction mismatch",
572                    ep.name
573                ));
574            }
575            if p.ty != ep.ty {
576                return Err(format!(
577                    "module `{name}` port `{}` type mismatch: {:?} vs {:?}",
578                    ep.name, ep.ty, p.ty
579                ));
580            }
581        }
582    }
583    Ok(())
584}
585
586/// FR46: instance graph round-trip (instance name, child module, connects).
587/// Connects compared as unordered `(child_port, parent_net, dangling)` sets.
588pub fn instance_graph_roundtrip_ok(expected: &FrozenHir, got: &FrozenHir) -> Result<(), String> {
589    let exp: std::collections::HashMap<&str, &Module> = expected
590        .circuit()
591        .modules
592        .iter()
593        .map(|m| (m.name.as_str(), m))
594        .collect();
595    let got_map: std::collections::HashMap<&str, &Module> = got
596        .circuit()
597        .modules
598        .iter()
599        .map(|m| (m.name.as_str(), m))
600        .collect();
601    for (name, em) in &exp {
602        let gm = got_map
603            .get(name)
604            .ok_or_else(|| format!("missing module `{name}`"))?;
605        let e_insts: Vec<_> = em
606            .body
607            .iter()
608            .filter_map(|s| match s {
609                Stmt::Instance(i) => Some(i),
610                _ => None,
611            })
612            .collect();
613        let g_insts: Vec<_> = gm
614            .body
615            .iter()
616            .filter_map(|s| match s {
617                Stmt::Instance(i) => Some(i),
618                _ => None,
619            })
620            .collect();
621        if e_insts.len() != g_insts.len() {
622            return Err(format!(
623                "module `{name}` instance count: expected {}, got {}",
624                e_insts.len(),
625                g_insts.len()
626            ));
627        }
628        let mut g_by_name: std::collections::HashMap<&str, &Instance> =
629            g_insts.iter().map(|i| (i.name.as_str(), *i)).collect();
630        for ei in e_insts {
631            let gi = g_by_name
632                .remove(ei.name.as_str())
633                .ok_or_else(|| format!("module `{name}` missing instance `{}`", ei.name))?;
634            if gi.module != ei.module {
635                return Err(format!(
636                    "instance `{}` module: expected {}, got {}",
637                    ei.name, ei.module, gi.module
638                ));
639            }
640            let eset: std::collections::HashSet<_> = ei
641                .connects
642                .iter()
643                .map(|c| (c.child_port.as_str(), c.parent_net.as_str(), c.dangling))
644                .collect();
645            let gset: std::collections::HashSet<_> = gi
646                .connects
647                .iter()
648                .map(|c| (c.child_port.as_str(), c.parent_net.as_str(), c.dangling))
649                .collect();
650            if eset != gset {
651                let e_dangling: Vec<_> = ei
652                    .connects
653                    .iter()
654                    .filter(|c| c.dangling)
655                    .map(|c| c.child_port.as_str())
656                    .collect();
657                let g_dangling: Vec<_> = gi
658                    .connects
659                    .iter()
660                    .filter(|c| c.dangling)
661                    .map(|c| c.child_port.as_str())
662                    .collect();
663                if e_dangling != g_dangling {
664                    return Err(format!(
665                        "instance `{}` dangling connects mismatch (FIRRTL emit omits dangling; they cannot round-trip): expected dangling {e_dangling:?}, got {g_dangling:?}; full expected {eset:?}, got {gset:?}",
666                        ei.name
667                    ));
668                }
669                return Err(format!(
670                    "instance `{}` connects mismatch: expected {eset:?}, got {gset:?}",
671                    ei.name
672                ));
673            }
674        }
675    }
676    Ok(())
677}
678
679fn parse_expr(s: &str, m: &Module, target: &str) -> AssignExpr {
680    if let Some(inner) = s.strip_prefix("asSInt(").and_then(|s| s.strip_suffix(')')) {
681        let inner = inner
682            .strip_prefix("pad(")
683            .and_then(|s| s.strip_suffix(')'))
684            .and_then(|s| s.rsplit_once(", ").map(|(value, _)| value))
685            .unwrap_or(inner);
686        let expression = parse_expr(inner, m, target);
687        if matches!(expression, AssignExpr::Shl(..) | AssignExpr::Shr(..))
688            && emit_assignment_expr(&expression, m, target) == s
689        {
690            return expression;
691        }
692    }
693    // Recognize exactly our bounded dynamic-left-shift encoding, preserving HIR
694    // identity rather than treating the nested FIRRTL primitive as a signal name.
695    if let Some(rest) = s.strip_prefix("mux(geq(") {
696        if let Some((shift, rest)) = rest.split_once(", UInt(") {
697            if let Some((_, rest)) = rest.split_once(")), UInt(0), ") {
698                let value = rest
699                    .strip_prefix("dshl(")
700                    .and_then(|s| s.split_once(',').map(|(v, _)| v))
701                    .or_else(|| rest.strip_suffix(')'));
702                if let Some(value) = value {
703                    let value = value
704                        .strip_prefix("asUInt(")
705                        .and_then(|s| s.strip_suffix(')'))
706                        .unwrap_or(value);
707                    let candidate = AssignExpr::Shl(value.into(), shift.into());
708                    if emit_expr(&candidate, m, target) == s {
709                        return candidate;
710                    }
711                }
712            }
713        }
714    }
715    for (primitive, make) in [
716        ("dshl(", AssignExpr::Shl as fn(String, String) -> AssignExpr),
717        ("dshr(", AssignExpr::Shr as fn(String, String) -> AssignExpr),
718    ] {
719        if let Some(inner) = s.strip_prefix(primitive).and_then(|x| x.strip_suffix(')')) {
720            if let Some((a, b)) = inner.split_once(", ") {
721                let a = a
722                    .strip_prefix("asUInt(")
723                    .and_then(|s| s.strip_suffix(')'))
724                    .unwrap_or(a);
725                if !a.contains('(') && !b.contains('(') {
726                    let candidate = make(a.into(), b.into());
727                    // Only discard casts that match our logical-shift encoding.
728                    if emit_expr(&candidate, m, target) == s || s == format!("{primitive}{a}, {b})")
729                    {
730                        return candidate;
731                    }
732                }
733            }
734        }
735    }
736    if let Some(inner) = s.strip_prefix("add(").and_then(|x| x.strip_suffix(')')) {
737        let parts: Vec<_> = inner.split(',').map(str::trim).collect();
738        if parts.len() == 2 {
739            if matches!(parts[1], "UInt(1)" | "SInt(1)") {
740                return AssignExpr::Inc(parts[0].to_string());
741            }
742            return AssignExpr::Add(parts[0].to_string(), parts[1].to_string());
743        }
744    }
745    if let Some(v) = s
746        .strip_prefix("UInt(")
747        .and_then(|x| x.strip_suffix(')'))
748        .and_then(|x| x.parse().ok())
749    {
750        return AssignExpr::Lit(v);
751    }
752    AssignExpr::Ref(s.to_string())
753}
754
755fn parse_ty(s: &str) -> GroundType {
756    if s == "UInt<1> ; bitloom-type: Reset" {
757        return GroundType::Reset;
758    }
759    match s {
760        "Clock" => GroundType::Clock,
761        "Reset" => GroundType::Reset,
762        _ => {
763            if let Some(w) = s
764                .strip_prefix("UInt<")
765                .and_then(|x| x.strip_suffix('>'))
766                .and_then(|x| x.parse().ok())
767            {
768                GroundType::UInt { width: w }
769            } else if let Some(w) = s
770                .strip_prefix("SInt<")
771                .and_then(|x| x.strip_suffix('>'))
772                .and_then(|x| x.parse().ok())
773            {
774                GroundType::SInt { width: w }
775            } else {
776                GroundType::UInt { width: 1 }
777            }
778        }
779    }
780}
781
782#[cfg(test)]
783mod tests {
784    use bitloom_builder::{ElaborateSession, GroundType, Span};
785
786    use super::*;
787
788    #[test]
789    fn import_rejects_zero_width_signal_types_at_shared_freeze() {
790        let fir = "FIRRTL version 6.0.0\ncircuit Top :\n  module Top :\n    input zero: UInt<0>\n";
791        let errors = import(fir).unwrap_err();
792        assert!(errors.0.iter().any(|diagnostic| {
793            diagnostic.code == "rhdl::E0271" && diagnostic.en.contains("zero")
794        }));
795    }
796
797    #[test]
798    fn firrtl6_public_top_and_modern_connections() {
799        let hir = hierarchical_sample();
800        let text = emit(&hir).files.remove(0).contents;
801        assert!(text.contains(&format!("public module {} :", hir.abi_name)));
802        assert_eq!(text.matches("public module ").count(), 1);
803        assert!(text.contains("connect "));
804        assert!(
805            !text
806                .lines()
807                .any(|l| !l.trim().starts_with(';') && l.contains(" <= "))
808        );
809        let back = import(&text).expect("modern FIRRTL remains importable");
810        ports_roundtrip_ok(&hir, &back).unwrap();
811        instance_graph_roundtrip_ok(&hir, &back).unwrap();
812    }
813
814    #[test]
815    fn bounded_left_shift_roundtrips_without_modulo_semantics() {
816        for (width, shift_width, out_width, signed) in [
817            (1, 1, 1),
818            (8, 8, 8),
819            (32, 32, 32),
820            (64, 64, 64),
821            (32, 1, 32),
822            (8, 8, 16),
823            (8, 1, 16),
824            (16, 8, 8),
825        ]
826        .into_iter()
827        .flat_map(|(w, s, o)| [(w, s, o, false), (w, s, o, true)])
828        {
829            let mut s = ElaborateSession::new("Shift");
830            let p = Span::default();
831            s.begin_module("Shift", p);
832            s.add_input("clk", GroundType::Clock, p);
833            s.add_input("rst", GroundType::Reset, p);
834            let ty = if signed {
835                GroundType::SInt { width }
836            } else {
837                GroundType::UInt { width }
838            };
839            s.add_input("a", ty.clone(), p);
840            s.add_input("shift", GroundType::UInt { width: shift_width }, p);
841            let out_ty = if signed {
842                GroundType::SInt { width: out_width }
843            } else {
844                GroundType::UInt { width: out_width }
845            };
846            s.add_output("out", out_ty.clone(), p);
847            s.add_output("right", out_ty, p);
848            s.begin_combinational(p);
849            s.assign_shl("out", "a", "shift", p);
850            s.assign_shr("right", "a", "shift", p);
851            s.end_process();
852            s.end_module();
853            let hir = s.finish().unwrap();
854            let text = emit(&hir).files.remove(0).contents;
855            assert!(text.contains(&format!("geq(shift, UInt({out_width}))")));
856            let back = import(&text).expect("bounded shift expression roundtrip");
857            let assignments: Vec<_> = back.circuit().modules[0]
858                .body
859                .iter()
860                .filter_map(|s| {
861                    if let Stmt::Process(p) = s {
862                        Some(p.assigns.as_slice())
863                    } else {
864                        None
865                    }
866                })
867                .flatten()
868                .collect();
869            assert_eq!(assignments.len(), 2);
870            assert_eq!(
871                assignments[0].expr,
872                AssignExpr::Shl("a".into(), "shift".into())
873            );
874            assert_eq!(
875                assignments[1].expr,
876                AssignExpr::Shr("a".into(), "shift".into())
877            );
878        }
879    }
880
881    fn hierarchical_sample() -> FrozenHir {
882        let mut s = ElaborateSession::new("t");
883        s.begin_module("Child", Span::default());
884        s.add_input("clk", GroundType::Clock, Span::default());
885        s.add_input("rst", GroundType::Reset, Span::default());
886        s.add_input("x", GroundType::UInt { width: 8 }, Span::default());
887        s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
888        s.declare_reg("r", GroundType::UInt { width: 8 }, Span::default());
889        s.begin_combinational(Span::default());
890        s.assign_net("y", "x", Span::default());
891        s.end_process();
892        s.begin_sequential(Span::default());
893        s.assign_reg_d_inc("r", Span::default());
894        s.end_process();
895        s.end_module();
896
897        s.begin_module("Top", Span::default());
898        s.add_input("clk", GroundType::Clock, Span::default());
899        s.add_input("rst", GroundType::Reset, Span::default());
900        s.add_input("x", GroundType::UInt { width: 8 }, Span::default());
901        s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
902        s.add_instance(
903            "u0",
904            "Child",
905            vec![
906                ("clk".into(), "clk".into()),
907                ("rst".into(), "rst".into()),
908                ("x".into(), "x".into()),
909                ("y".into(), "y".into()),
910            ],
911            vec![],
912            Span::default(),
913        );
914        s.end_module();
915        s.finish().unwrap()
916    }
917
918    #[test]
919    fn emit_has_version_header() {
920        let art = emit(&hierarchical_sample());
921        assert!(art.files[0].contents.starts_with("FIRRTL version 6.0.0"));
922        assert_eq!(art.filelist[0], "Top.fir");
923    }
924
925    #[test]
926    fn roundtrip_hierarchy_reg_and_instance() {
927        let frozen = hierarchical_sample();
928        let text = emit(&frozen).files[0].contents.clone();
929        let back = import(&text).expect("import");
930        assert_eq!(back.circuit().modules.len(), frozen.circuit().modules.len());
931        let child = &back.circuit().modules[0];
932        assert!(
933            child
934                .body
935                .iter()
936                .any(|s| matches!(s, Stmt::RegDecl { name, .. } if name == "r"))
937        );
938        assert!(child.body.iter().any(|s| matches!(
939            s,
940            Stmt::Process(p) if p.kind == ProcessKind::Combinational
941                && p.assigns.iter().any(|a| matches!(&a.target, AssignTarget::Net(n) if n == "y"))
942        )));
943        let top = &back.circuit().modules[1];
944        assert!(top.body.iter().any(|s| matches!(
945            s,
946            Stmt::Instance(i) if i.name == "u0" && i.module == "Child" && i.connects.len() == 4
947        )));
948    }
949
950    fn counter_for_chisel() -> FrozenHir {
951        let mut s = ElaborateSession::new("t");
952        s.begin_module("Counter", Span::default());
953        s.add_input("clk", GroundType::Clock, Span::default());
954        s.add_input("rst", GroundType::Reset, Span::default());
955        s.add_input("data_in", GroundType::UInt { width: 8 }, Span::default());
956        s.add_output("data_out", GroundType::UInt { width: 8 }, Span::default());
957        s.declare_reg("count", GroundType::UInt { width: 8 }, Span::default());
958        s.begin_combinational(Span::default());
959        s.assign_net("data_out", "count", Span::default());
960        s.end_process();
961        s.begin_sequential(Span::default());
962        s.assign_reg_d_inc("count", Span::default());
963        s.end_process();
964        s.end_module();
965        s.finish().unwrap()
966    }
967
968    /// Port name / width / direction predicates for FR28 (skip clk/rst).
969    fn assert_port_predicates(scala: &str, hir: &FrozenHir) {
970        for m in &hir.circuit().modules {
971            assert!(
972                scala.contains(&format!("class {} extends Module", m.name)),
973                "missing class for module {}",
974                m.name
975            );
976            for p in &m.ports {
977                if p.name == "clk" || p.name == "rst" {
978                    continue;
979                }
980                let dir = match p.direction {
981                    PortDirection::Input => "Input",
982                    PortDirection::Output => "Output",
983                    PortDirection::InOut => "Analog",
984                };
985                let ty = match &p.ty {
986                    GroundType::UInt { width } => format!("UInt({width}.W)"),
987                    GroundType::SInt { width } => format!("SInt({width}.W)"),
988                    GroundType::Bool => "Bool()".into(),
989                    GroundType::Clock => "Clock()".into(),
990                    GroundType::Reset => "Reset()".into(),
991                    GroundType::Analog => "Analog()".into(),
992                };
993                let field = format!("val {} = {dir}({ty})", p.name);
994                assert!(
995                    scala.contains(&field),
996                    "port predicate failed for {}.{}: expected `{field}`",
997                    m.name,
998                    p.name
999                );
1000            }
1001        }
1002    }
1003
1004    /// Instance hierarchy predicates: Module(new Child) + directional connects.
1005    fn assert_hierarchy_predicates(scala: &str, hir: &FrozenHir) {
1006        let modules: std::collections::HashMap<&str, &Module> = hir
1007            .circuit()
1008            .modules
1009            .iter()
1010            .map(|m| (m.name.as_str(), m))
1011            .collect();
1012        for m in &hir.circuit().modules {
1013            for stmt in &m.body {
1014                let Stmt::Instance(inst) = stmt else {
1015                    continue;
1016                };
1017                assert!(
1018                    scala.contains(&format!("val {} = Module(new {})", inst.name, inst.module)),
1019                    "missing Module(new {}) for instance {}",
1020                    inst.module,
1021                    inst.name
1022                );
1023                let child = modules
1024                    .get(inst.module.as_str())
1025                    .expect("child module in circuit");
1026                for c in &inst.connects {
1027                    if c.dangling || c.child_port == "clk" || c.child_port == "rst" {
1028                        continue;
1029                    }
1030                    let port = child
1031                        .ports
1032                        .iter()
1033                        .find(|p| p.name == c.child_port)
1034                        .expect("child port");
1035                    let parent_ref = if m.ports.iter().any(|p| p.name == c.parent_net) {
1036                        format!("io.{}", c.parent_net)
1037                    } else {
1038                        c.parent_net.clone()
1039                    };
1040                    let child_io = format!("{}.io.{}", inst.name, c.child_port);
1041                    let expected = match port.direction {
1042                        PortDirection::Input => format!("{child_io} := {parent_ref}"),
1043                        PortDirection::Output => format!("{parent_ref} := {child_io}"),
1044                        PortDirection::InOut => continue,
1045                    };
1046                    assert!(
1047                        scala.contains(&expected),
1048                        "connect predicate failed: expected `{expected}`"
1049                    );
1050                }
1051            }
1052        }
1053    }
1054
1055    #[test]
1056    fn chisel_fr28_flat_counter_emits_scala() {
1057        assert_eq!(CHISEL_TARGET, "7.15.0");
1058        assert_eq!(FIRTOOL_TARGET, "1.159.0");
1059        let hir = counter_for_chisel();
1060        let art = emit_chisel(&hir).unwrap();
1061        let scala = &art.files[0].contents;
1062        assert!(scala.contains("target Chisel 7.15.0"));
1063        assert!(scala.contains("firtool-1.159.0"));
1064        assert!(scala.contains("FR28 compilable Chisel"));
1065        assert!(scala.contains("class Counter extends Module"));
1066        assert!(scala.contains("io.data_out := count"));
1067        assert!(scala.contains("count := count + 1.U"));
1068        assert_port_predicates(scala, &hir);
1069        // FIRRTL path unchanged (AD-3)
1070        assert!(
1071            emit(&hir).files[0]
1072                .contents
1073                .starts_with("FIRRTL version 6.0.0")
1074        );
1075    }
1076
1077    #[test]
1078    fn chisel_fr28_hierarchy_emits_module_new_and_connects() {
1079        let hir = hierarchical_sample();
1080        let art = emit_chisel(&hir).expect("hierarchy must emit; E0902 removed");
1081        let scala = &art.files[0].contents;
1082        assert!(scala.contains("val u0 = Module(new Child)"));
1083        assert!(scala.contains("u0.io.x := io.x"));
1084        assert!(scala.contains("io.y := u0.io.y"));
1085        assert!(!scala.contains("u0.io.clk"));
1086        assert!(!scala.contains("u0.io.rst"));
1087        assert_port_predicates(scala, &hir);
1088        assert_hierarchy_predicates(scala, &hir);
1089    }
1090
1091    #[test]
1092    fn chisel_fr28_hierarchy_via_wire_parent_net() {
1093        let mut s = ElaborateSession::new("t");
1094        s.begin_module("Child", Span::default());
1095        s.add_input("clk", GroundType::Clock, Span::default());
1096        s.add_input("rst", GroundType::Reset, Span::default());
1097        s.add_input("x", GroundType::UInt { width: 8 }, Span::default());
1098        s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
1099        s.begin_combinational(Span::default());
1100        s.assign_net("y", "x", Span::default());
1101        s.end_process();
1102        s.end_module();
1103
1104        s.begin_module("Top", Span::default());
1105        s.add_input("clk", GroundType::Clock, Span::default());
1106        s.add_input("rst", GroundType::Reset, Span::default());
1107        s.add_input("x", GroundType::UInt { width: 8 }, Span::default());
1108        s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
1109        s.declare_wire("w", GroundType::UInt { width: 8 }, Span::default());
1110        s.begin_combinational(Span::default());
1111        s.assign_net("w", "x", Span::default());
1112        s.end_process();
1113        s.add_instance(
1114            "u0",
1115            "Child",
1116            vec![
1117                ("clk".into(), "clk".into()),
1118                ("rst".into(), "rst".into()),
1119                ("x".into(), "w".into()),
1120                ("y".into(), "y".into()),
1121            ],
1122            vec![],
1123            Span::default(),
1124        );
1125        s.end_module();
1126        let hir = s.finish().unwrap();
1127        let scala = emit_chisel(&hir).unwrap().files[0].contents.clone();
1128        assert!(scala.contains("val w = Wire(UInt(8.W))"));
1129        assert!(scala.contains("u0.io.x := w"));
1130        assert!(!scala.contains("u0.io.x := io.w"));
1131        assert_hierarchy_predicates(&scala, &hir);
1132    }
1133
1134    #[test]
1135    fn chisel_fr28_dangling_connect_omitted() {
1136        let mut s = ElaborateSession::new("t");
1137        s.begin_module("Child", Span::default());
1138        s.add_input("clk", GroundType::Clock, Span::default());
1139        s.add_input("rst", GroundType::Reset, Span::default());
1140        s.add_input("x", GroundType::UInt { width: 8 }, Span::default());
1141        s.add_input("spare", GroundType::UInt { width: 8 }, Span::default());
1142        s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
1143        s.begin_combinational(Span::default());
1144        s.assign_net("y", "x", Span::default());
1145        s.end_process();
1146        s.end_module();
1147
1148        s.begin_module("Top", Span::default());
1149        s.add_input("clk", GroundType::Clock, Span::default());
1150        s.add_input("rst", GroundType::Reset, Span::default());
1151        s.add_input("x", GroundType::UInt { width: 8 }, Span::default());
1152        s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
1153        s.add_instance(
1154            "u0",
1155            "Child",
1156            vec![
1157                ("clk".into(), "clk".into()),
1158                ("rst".into(), "rst".into()),
1159                ("x".into(), "x".into()),
1160                ("y".into(), "y".into()),
1161            ],
1162            vec![],
1163            Span::default(),
1164        );
1165        s.add_dangling_input("u0", "spare", Span::default());
1166        s.end_module();
1167        let hir = s.finish().unwrap();
1168        let scala = emit_chisel(&hir).unwrap().files[0].contents.clone();
1169        assert!(scala.contains("u0.io.x := io.x"));
1170        assert!(
1171            !scala.contains("u0.io.spare"),
1172            "dangling child input must not appear as a connect"
1173        );
1174        assert_hierarchy_predicates(&scala, &hir);
1175    }
1176
1177    #[test]
1178    fn chisel_fr28_fir_import_then_emit() {
1179        let frozen = hierarchical_sample();
1180        let fir = emit(&frozen).files[0].contents.clone();
1181        let back = import(&fir).expect("import .fir");
1182        let scala = emit_chisel(&back).expect("emit_chisel after import").files[0]
1183            .contents
1184            .clone();
1185        assert_port_predicates(&scala, &back);
1186        assert_hierarchy_predicates(&scala, &back);
1187        assert!(scala.contains("Module(new Child)"));
1188        assert!(scala.contains("target Chisel 7.15.0"));
1189        assert!(scala.contains("firtool-1.159.0"));
1190    }
1191
1192    #[test]
1193    fn chisel_fr28_pin_locked() {
1194        assert_eq!(CHISEL_TARGET, "7.15.0");
1195        assert_eq!(FIRTOOL_TARGET, "1.159.0");
1196        let scala = emit_chisel(&counter_for_chisel()).unwrap().files[0]
1197            .contents
1198            .clone();
1199        assert!(scala.contains("Chisel 7.15.0"));
1200        assert!(scala.contains("firtool-1.159.0"));
1201    }
1202
1203    #[test]
1204    fn chisel_fr81_path_a_lowers_sync_read_mem() {
1205        let mut s = ElaborateSession::new("t");
1206        s.begin_module("MemTop", Span::default());
1207        s.add_input("clk", GroundType::Clock, Span::default());
1208        s.add_input("rst", GroundType::Reset, Span::default());
1209        s.add_input("addr", GroundType::UInt { width: 2 }, Span::default());
1210        s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
1211        s.declare_sync_read_mem("ram", 4, 8, Span::default());
1212        s.declare_reg("q", GroundType::UInt { width: 8 }, Span::default());
1213        s.begin_sequential(Span::default());
1214        s.assign_reg_d_mem_read("q", "ram", "addr", Span::default());
1215        s.end_process();
1216        s.begin_combinational(Span::default());
1217        s.assign_net("y", "q", Span::default());
1218        s.end_process();
1219        s.end_module();
1220        let scala = emit_chisel(&s.finish().unwrap()).unwrap().files[0]
1221            .contents
1222            .clone();
1223        assert!(scala.contains("SyncReadMem(4, UInt(8.W))"), "{scala}");
1224        assert!(scala.contains("ram.read("), "{scala}");
1225        assert!(scala.contains("Chisel 7.15.0"));
1226        assert!(scala.contains("firtool-1.159.0"));
1227    }
1228
1229    #[test]
1230    fn chisel_fr81_path_a_lowers_async_mem_and_init() {
1231        let mut s = ElaborateSession::new("t");
1232        s.begin_module("RomTop", Span::default());
1233        s.add_input("clk", GroundType::Clock, Span::default());
1234        s.add_input("rst", GroundType::Reset, Span::default());
1235        s.add_input("addr", GroundType::UInt { width: 2 }, Span::default());
1236        s.add_input("wdata", GroundType::UInt { width: 8 }, Span::default());
1237        s.add_input("we", GroundType::UInt { width: 1 }, Span::default());
1238        s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
1239        s.declare_mem_with_init("rom", 4, 8, vec![1, 2, 3, 4], Span::default());
1240        s.declare_reg("q", GroundType::UInt { width: 8 }, Span::default());
1241        s.begin_sequential(Span::default());
1242        s.assign_mem_write_en("rom", "addr", "wdata", "we", Span::default());
1243        s.assign_reg_d_mem_read("q", "rom", "addr", Span::default());
1244        s.end_process();
1245        s.begin_combinational(Span::default());
1246        s.assign_net("y", "q", Span::default());
1247        s.end_process();
1248        s.end_module();
1249        let scala = emit_chisel(&s.finish().unwrap()).unwrap().files[0]
1250            .contents
1251            .clone();
1252        assert!(scala.contains("Mem(4, UInt(8.W))"), "{scala}");
1253        assert!(!scala.contains("SyncReadMem("), "{scala}");
1254        assert!(scala.contains("rom_init = VecInit("), "{scala}");
1255        assert!(scala.contains("rom.write(i.U, rom_init(i))"), "{scala}");
1256        assert!(
1257            scala.contains("when (!reset.asBool && io.we.asBool)"),
1258            "{scala}"
1259        );
1260        assert!(scala.contains("rom.write(io.addr, io.wdata)"), "{scala}");
1261    }
1262
1263    #[test]
1264    fn chisel_fr81_e0901_out_of_subset_init_len() {
1265        use bitloom_hir::{
1266            BuilderOwnedHir, GroundType, Module, Port, PortDirection, Span, Stmt, seal_from_builder,
1267        };
1268        let mut owned = BuilderOwnedHir::new("BadMem");
1269        owned.add_module(Module {
1270            name: "BadMem".into(),
1271            ports: vec![
1272                Port {
1273                    name: "clk".into(),
1274                    direction: PortDirection::Input,
1275                    ty: GroundType::Clock,
1276                    span: Span::default(),
1277                },
1278                Port {
1279                    name: "rst".into(),
1280                    direction: PortDirection::Input,
1281                    ty: GroundType::Reset,
1282                    span: Span::default(),
1283                },
1284            ],
1285            body: vec![Stmt::MemDecl {
1286                name: "ram".into(),
1287                depth: 4,
1288                width: 8,
1289                sync_read: true,
1290                init: Some(vec![1, 2]), // length ≠ depth → out of Path A
1291                span: Span::default(),
1292            }],
1293            span: Span::default(),
1294        });
1295        let frozen = seal_from_builder(owned).expect("freeze allows mismatched init");
1296        let err = emit_chisel(&frozen).unwrap_err();
1297        assert_eq!(err.code, "rhdl::E0901");
1298        assert!(err.en.contains("mem"), "{err}");
1299    }
1300
1301    #[test]
1302    fn fr46_export_reimport_ports_and_instance_graph() {
1303        let frozen = hierarchical_sample();
1304        let fir = emit(&frozen).files[0].contents.clone();
1305        let back = import(&fir).expect("export→import");
1306        ports_roundtrip_ok(&frozen, &back).expect("FR46 port predicates");
1307        instance_graph_roundtrip_ok(&frozen, &back).expect("FR46 instance graph");
1308        // Re-emit FIRRTL and Chisel from imported HIR (same backend path as Bitloom surface).
1309        let re = emit(&back).files[0].contents.clone();
1310        assert!(re.starts_with("FIRRTL version 6.0.0"));
1311        let scala = emit_chisel(&back)
1312            .expect("emit_chisel after FR46 import")
1313            .files[0]
1314            .contents
1315            .clone();
1316        assert!(scala.contains("Module(new Child)"));
1317    }
1318
1319    #[test]
1320    fn fr46_external_fir_firtool_style_connects_then_emit() {
1321        let fir = include_str!("../fixtures/external_hierarchy.fir");
1322        assert!(
1323            fir.contains("y <= u0.y"),
1324            "fixture must use firtool-style output connect"
1325        );
1326        let hir = import(fir).expect("import external .fir");
1327        let child = hir
1328            .circuit()
1329            .modules
1330            .iter()
1331            .find(|m| m.name == "Child")
1332            .expect("Child");
1333        assert!(
1334            child
1335                .ports
1336                .iter()
1337                .any(|p| p.name == "x" && p.direction == PortDirection::Input)
1338        );
1339        let top = hir
1340            .circuit()
1341            .modules
1342            .iter()
1343            .find(|m| m.name == "ExternalTop")
1344            .expect("ExternalTop");
1345        let inst = top
1346            .body
1347            .iter()
1348            .find_map(|s| match s {
1349                Stmt::Instance(i) if i.name == "u0" => Some(i),
1350                _ => None,
1351            })
1352            .expect("u0");
1353        assert_eq!(inst.module, "Child");
1354        assert!(
1355            inst.connects
1356                .iter()
1357                .any(|c| c.child_port == "y" && c.parent_net == "y" && !c.dangling)
1358        );
1359        let v = bitloom_vlog::emit(&hir);
1360        assert!(!v.files.is_empty());
1361        assert!(v.files[0].contents.contains("module"));
1362        let fir_out = emit(&hir).files[0].contents.clone();
1363        assert!(fir_out.starts_with("FIRRTL version 6.0.0"));
1364        let scala = emit_chisel(&hir).expect("chisel from external").files[0]
1365            .contents
1366            .clone();
1367        assert!(scala.contains("Module(new Child)"));
1368    }
1369
1370    #[test]
1371    fn fr46_import_counter_then_tick() {
1372        let hir = counter_for_chisel();
1373        let fir = emit(&hir).files[0].contents.clone();
1374        let back = import(&fir).expect("import counter");
1375        ports_roundtrip_ok(&hir, &back).unwrap();
1376        let mut sim = bitloom_sim::Sim::new(back);
1377        let mut pv = bitloom_hir::PortValues::default();
1378        pv.set("rst", 1);
1379        sim.set_inputs(pv.clone());
1380        sim.tick();
1381        pv.set("rst", 0);
1382        sim.set_inputs(pv);
1383        sim.tick();
1384        sim.tick();
1385        assert_eq!(sim.ports().get("data_out"), Some(2));
1386    }
1387
1388    #[test]
1389    fn fr46_rejects_unknown_parent_le_inst_port() {
1390        let fir = r#"FIRRTL version 6.0.0
1391circuit BadRhs :
1392  module BadRhs :
1393    input clock : Clock
1394    input reset : UInt<1>
1395    input x : UInt<8>
1396    output y : UInt<8>
1397    y <= missing.y
1398"#;
1399        let err = import(fir).expect_err("unknown rhs inst.port must reject");
1400        assert!(
1401            err.0.iter().any(|d| d.code == "rhdl::E0403"),
1402            "expected E0403, got {err}"
1403        );
1404        assert!(
1405            err.0.iter().any(|d| d.en.contains("missing.y")),
1406            "diagnostic should name unknown inst.port, got {err}"
1407        );
1408    }
1409
1410    #[test]
1411    fn fr46_rejects_unknown_inst_port_le_parent() {
1412        let fir = r#"FIRRTL version 6.0.0
1413circuit BadLhs :
1414  module BadLhs :
1415    input clock : Clock
1416    input reset : UInt<1>
1417    input x : UInt<8>
1418    output y : UInt<8>
1419    ghost.x <= x
1420"#;
1421        let err = import(fir).expect_err("unknown lhs inst.port must reject");
1422        assert!(
1423            err.0.iter().any(|d| d.code == "rhdl::E0403"),
1424            "expected E0403, got {err}"
1425        );
1426        assert!(
1427            err.0.iter().any(|d| d.en.contains("ghost.x")),
1428            "diagnostic should name unknown inst.port, got {err}"
1429        );
1430    }
1431
1432    #[test]
1433    fn fr46_dangling_connect_roundtrip_predicate_fails_clearly() {
1434        fn top_with_child(spare_dangling: bool) -> FrozenHir {
1435            let mut s = ElaborateSession::new("t");
1436            s.begin_module("Child", Span::default());
1437            s.add_input("clk", GroundType::Clock, Span::default());
1438            s.add_input("rst", GroundType::Reset, Span::default());
1439            s.add_input("x", GroundType::UInt { width: 8 }, Span::default());
1440            if spare_dangling {
1441                s.add_input("spare", GroundType::UInt { width: 8 }, Span::default());
1442            }
1443            s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
1444            s.begin_combinational(Span::default());
1445            s.assign_net("y", "x", Span::default());
1446            s.end_process();
1447            s.end_module();
1448
1449            s.begin_module("Top", Span::default());
1450            s.add_input("clk", GroundType::Clock, Span::default());
1451            s.add_input("rst", GroundType::Reset, Span::default());
1452            s.add_input("x", GroundType::UInt { width: 8 }, Span::default());
1453            s.add_output("y", GroundType::UInt { width: 8 }, Span::default());
1454            s.add_instance(
1455                "u0",
1456                "Child",
1457                vec![
1458                    ("clk".into(), "clk".into()),
1459                    ("rst".into(), "rst".into()),
1460                    ("x".into(), "x".into()),
1461                    ("y".into(), "y".into()),
1462                ],
1463                vec![],
1464                Span::default(),
1465            );
1466            if spare_dangling {
1467                s.add_dangling_input("u0", "spare", Span::default());
1468            }
1469            s.end_module();
1470            s.finish().unwrap()
1471        }
1472
1473        let with_dangling = top_with_child(true);
1474        let fir = emit(&with_dangling).files[0].contents.clone();
1475        assert!(
1476            !fir.contains("u0.spare"),
1477            "FIRRTL emit must omit dangling instance connects, got:\n{fir}"
1478        );
1479        // Emit drops dangling marks; a re-imported graph matches the no-dangling shape.
1480        // Strengthened predicate must fail clearly rather than silently accepting.
1481        let without = top_with_child(false);
1482        let err = instance_graph_roundtrip_ok(&with_dangling, &without)
1483            .expect_err("dangling must fail FR46 instance-graph round-trip");
1484        assert!(
1485            err.contains("dangling"),
1486            "predicate message must call out dangling: {err}"
1487        );
1488    }
1489}