Skip to main content

bitloom_prelude/
lib.rs

1//! Design-facing surface. Designs depend only on this crate.
2
3pub use bitloom_builder::{
4    CombInline, Elaboratable, ElaborateSession, GeneratedInstance, HwCaptureKind, HwCaptureRef,
5    LegalEmptyClosure, LegalSimpleClosure, SeqInline, SeqOwnershipViolation,
6    SeqOwnershipViolationKind, SynthesizableClosure, SynthesizableClosureViolation,
7    SynthesizableClosureViolationKind, diagnose_seq_ownership_violations,
8    diagnose_synthesizable_closure_violations,
9};
10pub use bitloom_hir::{Diagnostics, FrozenHir, GroundType, PortDirection, PortValues, Span};
11/// `#[derive(Bundle)]` (FR80) — same name as the [`Bundle`] trait (macro vs type namespace).
12pub use bitloom_macro::Bundle;
13
14/// First-class IP stubs (FR37 / FR48): FIFO, UART, … via this prelude only.
15pub mod ip;
16
17/// Re-export attributes via this crate's `rhdl` facade.
18///
19/// **FR102 multi-view matrix:** `functional_model` / `abstraction` / `bridge` / `both`
20/// are type attributes; `functional_state` is an **inert field attribute** recognized
21/// by [`module`](rhdl::module) and HostView macros (stripped on expand; never HIR).
22/// See `docs/fr102-multiview-attribute-matrix.md`.
23///
24/// **FR157:** [`fsm`](rhdl::fsm) marks an FSM state enum for automatic label extraction.
25pub mod rhdl {
26    pub use bitloom_macro::{
27        abstraction, both, bridge, combinational, fsm, functional_model, hls, module, process,
28        sequential, top,
29    };
30}
31
32/// Bitloom-branded attribute facade (FR118 / FR157 text paths use `#[bitloom::…]`).
33///
34/// Prefer this for new design annotations; [`rhdl`] remains the transitional alias.
35pub mod bitloom {
36    pub use bitloom_macro::{fsm, top};
37}
38
39/// FR157: compile-time FSM state label set (from `#[bitloom::fsm]` / `#[rhdl::fsm]`).
40///
41/// Feed `bitloom_sim::Sim::register_fsm_states` with [`Self::FSM_ID`] and
42/// [`Self::state_labels`] — does **not** replace FR109 visit sampling.
43pub trait FsmLabels {
44    /// FSM instance id used in coverage keys (`fsm:<id>:<label>`).
45    const FSM_ID: &'static str;
46    /// Ordered state labels (enum variant names).
47    fn state_labels() -> &'static [&'static str];
48}
49
50/// Host-only simulation view kind (FR29 / FR102). Never a FrozenHir node.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum ViewKind {
53    FunctionalModel,
54    Bridge,
55    Abstraction,
56    Both,
57}
58
59/// Marker implemented by `#[rhdl::bridge]` / `#[rhdl::abstraction]` / `#[rhdl::both]` /
60/// `#[rhdl::functional_model]`. These types do not enter HIR.
61///
62/// Soft fields on modules / host views use inert `#[functional_state]` /
63/// `#[rhdl::functional_state]` (FR102) — never registered as FrozenHir ports.
64pub trait HostView {
65    const KIND: ViewKind;
66}
67
68/// Host/bridge handshake template: start action → tick until not busy (FR78 / Cap-R-65).
69///
70/// **View boundary (Cap-R-66/67 / NFR36):** `start_fn` is a **free host closure** — it may
71/// set signal-level fields on `Self`. The cycle-accurate path continues only via
72/// [`Self::tick`] / ordinary pins/`PortValues`. The `Fn` **never** enters FrozenHir or
73/// `Sim::tick` as a closure object. Not SynthesizableClosure (≠ FR74/75) and not an
74/// elaborate-time generator (≠ FR73). SystemC TLM is not a product path (AD-5).
75///
76/// See `docs/fr78-bridge-adapter-closures.md`.
77pub trait StartWaitComplete {
78    /// Whether the handshake is still in progress (e.g. `tx_busy`).
79    fn is_busy(&self) -> bool;
80
81    /// Advance one cycle on the cycle-accurate side (ordinary signal update only).
82    fn tick(&mut self);
83
84    /// Run `start_fn` once, commit with one [`tick`](Self::tick), then tick while
85    /// [`is_busy`](Self::is_busy) (documented equivalent of requirements
86    /// `start → while busy { tick }` — the mandatory first tick lets registered
87    /// busy flags assert before the wait loop).
88    fn start_wait_complete<F>(&mut self, start_fn: F)
89    where
90        F: FnOnce(&mut Self),
91    {
92        start_fn(self);
93        self.tick();
94        while self.is_busy() {
95            self.tick();
96        }
97    }
98}
99
100/// Free-function form of [`StartWaitComplete::start_wait_complete`] (same FR78 contract).
101///
102/// Prefer the trait when the adapter owns `tick` / `is_busy`; use this when wiring an
103/// external sim/`PortValues` driver without implementing the trait.
104pub fn start_wait_complete<H, F>(
105    host: &mut H,
106    mut tick: impl FnMut(&mut H),
107    is_busy: impl Fn(&H) -> bool,
108    start_fn: F,
109) where
110    F: FnOnce(&mut H),
111{
112    start_fn(host);
113    tick(host);
114    while is_busy(host) {
115        tick(host);
116    }
117}
118
119/// Marker retained by `#[rhdl::hls]` expansions (FR35).
120#[derive(Debug, Clone, Copy)]
121pub struct HlsMark;
122
123/// Compile-time mark expanded by `#[combinational]` / `#[sequential]`.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum ProcessKindMark {
126    Combinational,
127    Sequential,
128}
129
130/// Port direction recorded by `PortField`.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum PortDir {
133    Input,
134    Output,
135}
136
137/// Marker trait: only `Input<T>` / `Output<T>` implement this.
138/// Bare `UInt<N>` etc. cannot be used as module fields with `#[rhdl::module]`.
139///
140/// Composites (`Bundle`, [`HwVec`]) flatten to scalar leaf ports before HIR
141/// (FR51 / FR80 / AD-20). Leaf names: `{field}_{member}` / `{field}_{nested}_{leaf}` /
142/// `{field}_{i}`.
143pub trait PortField {
144    /// Flatten this directed port field into scalar `(leaf_name, dir, ground)` rows.
145    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)>;
146}
147
148/// Hardware ground types (language surface).
149#[derive(Debug, Clone, Copy, Default)]
150pub struct Bool;
151
152#[derive(Debug, Clone, Copy)]
153pub struct Bits<const N: u32>;
154
155#[derive(Debug, Clone, Copy)]
156pub struct UInt<const N: u32>;
157
158#[derive(Debug, Clone, Copy)]
159pub struct SInt<const N: u32>;
160
161#[derive(Debug, Clone, Copy, Default)]
162pub struct Clock;
163
164#[derive(Debug, Clone, Copy, Default)]
165pub struct Reset;
166
167/// Directed input port wrapper (AD-18).
168#[derive(Debug, Clone, Copy, Default)]
169pub struct Input<T>(pub T);
170
171/// Directed output port wrapper (AD-18).
172#[derive(Debug, Clone, Copy, Default)]
173pub struct Output<T>(pub T);
174
175/// Documented synthesizable named aggregate (FR51 / FR80).
176///
177/// Implementors declare ground leaves and optional **one-level** nested Bundle
178/// members via [`Self::nested_bundles`]. `Input<Self>` / `Output<Self>` flatten to
179/// `{field}_{member}` or `{field}_{nested}_{leaf}` scalar HIR ports. Does not extend
180/// public HIR with Bundle nodes.
181///
182/// **Nesting (FR80 / AD-20):** at least one documented nesting level is in scope —
183/// child Bundles are referenced by their ground [`Self::leaves`] functions. Deeper
184/// nesting (≥2 levels) is deferred / non-goal for the Epic 32 default contract; do
185/// not claim arbitrary depth.
186///
187/// **Derive (FR80):** `#[derive(Bundle)]` is available via this prelude (AD-6 —
188/// design crates must not depend on `bitloom-macro` / CLI). Supported: named-field
189/// structs; ground fields `Bool` / `Clock` / `Reset` / `UInt<N>` / `SInt<N>` /
190/// `Bits<N>`; other simple path types as one-level nested Bundles. Rejected with
191/// stable `rhdl::E0180` diagnostics: enums, tuple/unit structs, generics on the
192/// struct, `HwVec<_>` / `Input<_>` / `Output<_>` fields, and non-path field types.
193///
194/// **Still OUT OF SCOPE:** `HwVec<Bundle, _>` — `HwVec` elements must be ground.
195pub trait Bundle {
196    /// Ground leaf members at this Bundle level `(member_name, GroundType)`.
197    fn leaves() -> &'static [(&'static str, GroundType)];
198
199    /// One-level nested Bundle members: `(member_name, nested_leaves_fn)`.
200    ///
201    /// Typical entry: `("stream", Stream::leaves)`. Nested leaves must be ground;
202    /// the nested fn does not recurse into further `nested_bundles` under the Epic 32
203    /// one-level contract.
204    fn nested_bundles() -> &'static [(&'static str, fn() -> &'static [(&'static str, GroundType)])]
205    {
206        &[]
207    }
208}
209
210/// Hardware vector; documented as the synthesizable `Vec<T,N>` equivalent (FR51).
211///
212/// Named `HwVec` to avoid collision with heap [`alloc::vec::Vec`] / E0141.
213/// `Input<HwVec<T,N>>` flattens to `{field}_0` … `{field}_{N-1}`.
214/// Element type must be ground (`Bool` / `UInt` / …); **`HwVec<Bundle, _>` is OUT OF SCOPE**.
215#[derive(Debug, Clone, Copy, Default)]
216pub struct HwVec<T, const N: u32>(pub core::marker::PhantomData<T>);
217
218/// Clash-style phantom clock-domain marker (AD-22 / FR52).
219///
220/// **Product surface:** `ClockDomain::<ID>` (this ZST) +
221/// [`ElaborateSession::bind_domain`] session domain tags — not a separate
222/// `Signal<D, T>` wrapper type. Default modules remain single-clock + **sync
223/// active-high** [`Reset`](AD-15). Sync/async reset via
224/// [`ElaborateSession::declare_reg_ex`] `async_reset`; legal CDC via
225/// [`DoubleFlop`] / [`SyncFIFO`](FR79 真 RTL)或 [`ElaborateSession::mark_cdc_bridge`]
226///(FR52 最小合同),else `finish` → `rhdl::E0220`.
227///
228/// Fixture: `examples/clockdomain_skel`(FR52 最小合同);`examples/doubleflop_skel`
229/// / `examples/syncfifo_skel`(FR79 真 RTL)。Sim: global `Sim::tick` is the MVP
230/// per-domain tick stand-in.
231#[derive(Debug, Clone, Copy, Default)]
232pub struct ClockDomain<const ID: u32>;
233
234/// 语言级 CDC 两级同步器(FR79 / AD-29;加深 FR23/FR52)。
235///
236/// **真 RTL:** [`Elaboratable::elaborate`] 发出可综合模块,含 `sync_ff0` /
237/// `sync_ff1` 两级寄存器(不得仅以空 ZST + [`ElaborateSession::mark_cdc_bridge`]
238/// 交差深度合同)。亦可在会话内用
239/// [`ElaborateSession::declare_double_flop_stages`] +
240/// [`ElaborateSession::connect_double_flop`] 嵌入更大模块。
241///
242/// **级数 / 延迟合同:** [`Self::STAGES`] = 2;稳定 `din` 后经
243/// [`Self::LATENCY_DST_TICKS`] 个**目的域** tick(MVP:全局
244/// `bitloom_sim::Sim::tick`)才在 `dout` 可见。
245///
246/// **合同外:** 不保证物理亚稳态消除或 MTBF(见
247/// `nfr14-risk-epic31-cdc-true-rtl.md`)。
248///
249/// 多位/流式 CDC 见 [`SyncFIFO`](FR79)。
250#[derive(Debug, Clone, Copy, Default)]
251pub struct DoubleFlop;
252
253impl DoubleFlop {
254    /// Documented synchronizer stage count (FR79).
255    pub const STAGES: u32 = 2;
256    /// Destination-domain ticks until `dout` follows a stable `din`.
257    pub const LATENCY_DST_TICKS: u32 = 2;
258}
259
260impl Elaboratable for DoubleFlop {
261    fn elaborate() -> Result<FrozenHir, Diagnostics> {
262        Self::elaborate_width(1)
263    }
264}
265
266impl DoubleFlop {
267    /// Elaborate a DoubleFlop with `width`-bit `din`/`dout` (default path uses 1).
268    pub fn elaborate_width(width: u32) -> Result<FrozenHir, Diagnostics> {
269        let ty = GroundType::UInt { width };
270        let mut s = ElaborateSession::new("DoubleFlop");
271        s.begin_module("DoubleFlop", Span::default());
272        s.add_input("clk", GroundType::Clock, Span::default());
273        s.add_input("rst", GroundType::Reset, Span::default());
274        s.add_input("din", ty.clone(), Span::default());
275        s.add_output("dout", ty.clone(), Span::default());
276        // Phantom domains: din = src (0), sync chain + dout = dst (1).
277        s.bind_domain("din", 0);
278        s.bind_domain("dout", 1);
279        let (ff0, ff1) = s.declare_double_flop_stages("sync", ty, 1, Span::default());
280        s.begin_combinational(Span::default());
281        s.assign_net("dout", &ff1, Span::default());
282        s.end_process();
283        s.begin_sequential(Span::default());
284        s.connect_double_flop(&ff0, &ff1, "din", Span::default());
285        s.end_process();
286        s.end_module();
287        s.finish()
288    }
289}
290
291/// 语言级跨域 FIFO(FR79 / AD-29;加深 FR23/FR52)。
292///
293/// **真 RTL:** [`Elaboratable::elaborate`](默认 [`SyncFIFO`]`<4, 8>`)发出可综合
294/// 模块:`mem` + 二进制/灰码指针 + 经 [`DoubleFlop`] 级数同步的跨域灰码 +
295/// `full`/`empty`(不得仅以空 ZST + [`ElaborateSession::mark_cdc_bridge`] 交差)。
296///
297/// **文档化最小子集:** `DEPTH=4`、`WIDTH=8`;单物理 `clk`/`rst` + phantom 写域 D0 /
298/// 读域 D1(与 DoubleFlop MVP 一致);全局 `Sim::tick` ≡ 按域 tick。
299///
300/// **延迟:** 灰码指针同步 [`Self::LATENCY_PTR_SYNC_TICKS`](= DoubleFlop 2);
301/// 注册读 [`Self::LATENCY_REG_READ_TICKS`]。详见 `docs/fr79-syncfifo-cdc.md`。
302///
303/// **≠** [`ip::SyncFifo`](FR82 单时钟一级 IP)。合同外:非 MTBF / 非双物理时钟端口矩阵。
304#[derive(Debug, Clone, Copy)]
305pub struct SyncFIFO<const DEPTH: u32, const WIDTH: u32>;
306
307impl<const DEPTH: u32, const WIDTH: u32> SyncFIFO<DEPTH, WIDTH> {
308    /// Documented FIFO depth (FR79 MVP default 4).
309    pub const DEPTH: u32 = DEPTH;
310    /// Documented data width (FR79 MVP default 8).
311    pub const WIDTH: u32 = WIDTH;
312    /// Binary/gray pointer width = clog2(DEPTH)+1 (DEPTH must be power of two).
313    pub const PTR_WIDTH: u32 = {
314        match DEPTH {
315            4 => 3,
316            _ => 3, // MVP documents DEPTH=4 only; other depths are Ask First.
317        }
318    };
319    /// Destination-domain ticks for gray pointer DoubleFlop sync (empty/full observe).
320    pub const LATENCY_PTR_SYNC_TICKS: u32 = DoubleFlop::LATENCY_DST_TICKS;
321    /// Registered mem-read latency to `data_out` after an accepted `rd_en`.
322    pub const LATENCY_REG_READ_TICKS: u32 = 1;
323}
324
325impl Elaboratable for SyncFIFO<4, 8> {
326    fn elaborate() -> Result<FrozenHir, Diagnostics> {
327        Self::elaborate_cdc()
328    }
329}
330
331impl SyncFIFO<4, 8> {
332    /// Elaborate the FR79 CDC SyncFIFO MVP (DEPTH=4, WIDTH=8).
333    pub fn elaborate_cdc() -> Result<FrozenHir, Diagnostics> {
334        const DEPTH: u32 = 4;
335        const WIDTH: u32 = 8;
336        const PTR_W: u32 = 3;
337        let data_ty = GroundType::UInt { width: WIDTH };
338        let ptr_ty = GroundType::UInt { width: PTR_W };
339        let bit_ty = GroundType::UInt { width: 1 };
340
341        let mut s = ElaborateSession::new("SyncFIFO");
342        s.begin_module("SyncFIFO", Span::default());
343        s.add_input("clk", GroundType::Clock, Span::default());
344        s.add_input("rst", GroundType::Reset, Span::default());
345        s.add_input("wr_en", bit_ty.clone(), Span::default());
346        s.add_input("rd_en", bit_ty.clone(), Span::default());
347        s.add_input("data_in", data_ty.clone(), Span::default());
348        s.add_output("data_out", data_ty.clone(), Span::default());
349        s.add_output("full", bit_ty.clone(), Span::default());
350        s.add_output("empty", bit_ty.clone(), Span::default());
351
352        // Write domain D0, read domain D1 (phantom; single physical clk MVP).
353        s.bind_domain("wr_en", 0);
354        s.bind_domain("data_in", 0);
355        s.bind_domain("full", 0);
356        s.bind_domain("rd_en", 1);
357        s.bind_domain("data_out", 1);
358        s.bind_domain("empty", 1);
359
360        s.declare_mem("ram", DEPTH, WIDTH, Span::default());
361        s.declare_reg("wr_ptr", ptr_ty.clone(), Span::default());
362        s.declare_reg("rd_ptr", ptr_ty.clone(), Span::default());
363        s.declare_reg("dout", data_ty, Span::default());
364        s.bind_domain("wr_ptr", 0);
365        s.bind_domain("rd_ptr", 1);
366        s.bind_domain("dout", 1);
367
368        // DoubleFlop sync gray(wr) → read domain; gray(rd) → write domain.
369        let (w2r_ff0, w2r_ff1) =
370            s.declare_double_flop_stages("w2r", ptr_ty.clone(), 1, Span::default());
371        let (r2w_ff0, r2w_ff1) =
372            s.declare_double_flop_stages("r2w", ptr_ty.clone(), 0, Span::default());
373
374        // Constants / comb helpers
375        s.declare_wire("c0_1", bit_ty.clone(), Span::default());
376        s.declare_wire("c1_1", bit_ty.clone(), Span::default());
377        s.declare_wire("c0_3", ptr_ty.clone(), Span::default());
378        s.declare_wire("c1_3", ptr_ty.clone(), Span::default());
379        s.declare_wire("c3_3", ptr_ty.clone(), Span::default());
380        s.declare_wire("c7_3", ptr_ty.clone(), Span::default());
381        s.declare_wire("wr_ptr_p1", ptr_ty.clone(), Span::default());
382        s.declare_wire("rd_ptr_p1", ptr_ty.clone(), Span::default());
383        s.declare_wire("wr_ptr_shr", ptr_ty.clone(), Span::default());
384        s.declare_wire("rd_ptr_shr", ptr_ty.clone(), Span::default());
385        s.declare_wire("wr_gray", ptr_ty.clone(), Span::default());
386        s.declare_wire("rd_gray", ptr_ty.clone(), Span::default());
387        s.declare_wire("wr_addr", ptr_ty.clone(), Span::default());
388        s.declare_wire("rd_addr", ptr_ty.clone(), Span::default());
389        s.declare_wire("rd_sync_shr", ptr_ty.clone(), Span::default());
390        s.declare_wire("rd_sync_hi_x", ptr_ty.clone(), Span::default());
391        s.declare_wire("rd_sync_hi", ptr_ty.clone(), Span::default());
392        s.declare_wire("rd_sync_hi_shl", ptr_ty.clone(), Span::default());
393        s.declare_wire("rd_sync_lo", ptr_ty.clone(), Span::default());
394        s.declare_wire("rd_fold", ptr_ty.clone(), Span::default());
395        s.declare_wire("can_wr", bit_ty.clone(), Span::default());
396        s.declare_wire("can_rd", bit_ty.clone(), Span::default());
397        s.declare_wire("next_wr", ptr_ty.clone(), Span::default());
398        s.declare_wire("next_rd", ptr_ty.clone(), Span::default());
399        s.declare_wire("not_full", bit_ty.clone(), Span::default());
400        s.declare_wire("not_empty", bit_ty, Span::default());
401
402        s.bind_domain("wr_gray", 0);
403        s.bind_domain("rd_fold", 0);
404        s.bind_domain("can_wr", 0);
405        s.bind_domain("next_wr", 0);
406        s.bind_domain("rd_gray", 1);
407        s.bind_domain("can_rd", 1);
408        s.bind_domain("next_rd", 1);
409        // Bridged sync outputs already marked via declare_double_flop_stages.
410        s.mark_cdc_bridge("wr_gray");
411        s.mark_cdc_bridge("rd_gray");
412
413        s.begin_combinational(Span::default());
414        s.assign_lit("c0_1", 0, Span::default());
415        s.assign_lit("c1_1", 1, Span::default());
416        s.assign_lit("c0_3", 0, Span::default());
417        s.assign_lit("c1_3", 1, Span::default());
418        s.assign_lit("c3_3", 3, Span::default());
419        s.assign_lit("c7_3", 7, Span::default());
420
421        s.assign_add("wr_ptr_p1", "wr_ptr", "c1_3", Span::default());
422        s.assign_add("rd_ptr_p1", "rd_ptr", "c1_3", Span::default());
423        s.assign_and("wr_addr", "wr_ptr", "c3_3", Span::default());
424        s.assign_and("rd_addr", "rd_ptr", "c3_3", Span::default());
425
426        // gray = bin ^ (bin >> 1)
427        s.assign_shr("wr_ptr_shr", "wr_ptr", "c1_3", Span::default());
428        s.assign_xor("wr_gray", "wr_ptr", "wr_ptr_shr", Span::default());
429        s.assign_shr("rd_ptr_shr", "rd_ptr", "c1_3", Span::default());
430        s.assign_xor("rd_gray", "rd_ptr", "rd_ptr_shr", Span::default());
431
432        // rd_fold = {~rd_sync[2:1], rd_sync[0]} for Cummings full compare
433        // = ((~(rd>>1) & 3) << 1) | (rd & 1)
434        s.assign_shr("rd_sync_shr", &r2w_ff1, "c1_3", Span::default());
435        s.assign_xor("rd_sync_hi_x", "rd_sync_shr", "c7_3", Span::default());
436        s.assign_and("rd_sync_hi", "rd_sync_hi_x", "c3_3", Span::default());
437        s.assign_shl("rd_sync_hi_shl", "rd_sync_hi", "c1_3", Span::default());
438        s.assign_and("rd_sync_lo", &r2w_ff1, "c1_3", Span::default());
439        s.assign_or("rd_fold", "rd_sync_hi_shl", "rd_sync_lo", Span::default());
440
441        s.assign_eq("full", "wr_gray", "rd_fold", Span::default());
442        s.assign_eq("empty", "rd_gray", &w2r_ff1, Span::default());
443        // not_full / not_empty via mux against constants (no bitwise not on 1-bit eq)
444        s.assign_mux("not_full", "full", "c0_1", "c1_1", Span::default());
445        s.assign_mux("not_empty", "empty", "c0_1", "c1_1", Span::default());
446        s.assign_and("can_wr", "wr_en", "not_full", Span::default());
447        s.assign_and("can_rd", "rd_en", "not_empty", Span::default());
448        s.assign_mux("next_wr", "can_wr", "wr_ptr_p1", "wr_ptr", Span::default());
449        s.assign_mux("next_rd", "can_rd", "rd_ptr_p1", "rd_ptr", Span::default());
450        s.assign_net("data_out", "dout", Span::default());
451        s.end_process();
452
453        s.begin_sequential(Span::default());
454        s.assign_mem_write_en("ram", "wr_addr", "data_in", "can_wr", Span::default());
455        s.assign_reg_d_mem_read("dout", "ram", "rd_addr", Span::default());
456        s.assign_reg_d_from("wr_ptr", "next_wr", Span::default());
457        s.assign_reg_d_from("rd_ptr", "next_rd", Span::default());
458        s.connect_double_flop(&w2r_ff0, &w2r_ff1, "wr_gray", Span::default());
459        s.connect_double_flop(&r2w_ff0, &r2w_ff1, "rd_gray", Span::default());
460        s.end_process();
461        s.end_module();
462        s.finish()
463    }
464}
465
466/// CHIRRTL-friendly SyncReadMem surface marker (AD-21).
467#[derive(Debug, Clone, Copy)]
468pub struct SyncReadMem<const DEPTH: u32, const WIDTH: u32>;
469
470/// CHIRRTL-friendly Mem (async-read) surface marker (AD-21).
471#[derive(Debug, Clone, Copy)]
472pub struct Mem<const DEPTH: u32, const WIDTH: u32>;
473
474/// Elaborate-time LUT/ROM/Mem init generator (FR73 / AD-18).
475///
476/// Runs `f(addr)` for each address and returns plain words for
477/// [`ElaborateSession::declare_mem_with_init`] /
478/// [`ElaborateSession::declare_sync_read_mem_with_init`]. Prefer session
479/// helpers [`ElaborateSession::declare_mem_with_init_fn`] when declaring
480/// and initializing in one step. The closure dissolves before freeze —
481/// FrozenHir stores only `Vec<u64>` (NFR36).
482///
483/// **Non-capturing only:** do not capture Wire/Reg/signal refs. Documented
484/// illegal capture → [`ElaborateSession::assert_no_hw_capture`] (`rhdl::E0142`).
485///
486/// ```ignore
487/// use bitloom_prelude::{generate_mem_init, ElaborateSession, GroundType, Span};
488/// let init = generate_mem_init(16, 8, |i| ((i * i) & 0xff) as u64);
489/// session.declare_mem_with_init("rom", 16, 8, init, Span::default());
490/// // or: session.declare_mem_with_init_fn("rom", 16, 8, |i| ..., Span::default());
491/// ```
492pub use bitloom_builder::{generate_mem_init_words as generate_mem_init, mask_mem_word};
493
494/// Module-factory entry points live on [`ElaborateSession`]:
495/// [`ElaborateSession::generate_instances`] and
496/// [`ElaborateSession::generate_instances_from`] (+ [`GeneratedInstance`])
497/// (FR73 / Cap-R-53). Factory `Fn` runs at elaborate time and dissolves to
498/// ordinary instance/connect HIR (NFR36). Capturing Wire/Reg →
499/// [`ElaborateSession::assert_no_hw_capture`] (`rhdl::E0142`).
500///
501/// **HwCaptureRef mapping (NFR35):** Wire → [`HwCaptureRef::wire`], Reg →
502/// [`HwCaptureRef::reg`], port/signal → [`HwCaptureRef::signal`]. See
503/// language-surface “Elaborate-time vs capturing”.
504
505/// SynthesizableClosure constraints + Cap-R-60 check hook (FR74 / Epic 28.1).
506///
507/// Marker trait [`SynthesizableClosure`] documents Cap-R-48…50 (pure, no heap,
508/// no runtime capture state). Call
509/// [`ElaborateSession::check_synthesizable_closure`] /
510/// [`ElaborateSession::reject_unsynthesizable_closure`] (or free
511/// [`diagnose_synthesizable_closure_violations`]) when a documented breach is
512/// present. Stable codes: **`rhdl::E0143`** (heap), **`rhdl::E0144`** (runtime
513/// capture state), **`rhdl::E0145`** (impure). Legal empty/simple stand-ins:
514/// [`LegalEmptyClosure`], [`LegalSimpleClosure`]. Does **not** add closure IR
515/// to FrozenHir / backends (NFR36).
516///
517/// **Comb inline (FR75 / Cap-R-55 / Epic 28.2):**
518/// [`ElaborateSession::inline_comb_fn`] / [`ElaborateSession::inline_comb_fn_marker`]
519/// + [`CombInline`] — Cap-R-60 check then elaborate-time expand into ordinary
520/// `assign_*` / Wire assigns.
521///
522/// **Seq inline (FR75 / Cap-R-56 / Cap-R-70 / Epic 28.3):**
523/// [`ElaborateSession::inline_seq_fn`] / [`ElaborateSession::inline_seq_fn_marker`]
524/// + [`SeqInline`] — Cap-R-60 + Cap-R-70 (`rhdl::E0146`) then expand into ordinary
525/// `Reg.d` / sequential assigns (NFR36).
526
527trait AsGround {
528    fn ground() -> GroundType;
529}
530
531impl AsGround for Bool {
532    fn ground() -> GroundType {
533        GroundType::Bool
534    }
535}
536
537impl AsGround for Clock {
538    fn ground() -> GroundType {
539        GroundType::Clock
540    }
541}
542
543impl AsGround for Reset {
544    fn ground() -> GroundType {
545        GroundType::Reset
546    }
547}
548
549impl<const N: u32> AsGround for Bits<N> {
550    fn ground() -> GroundType {
551        GroundType::UInt { width: N }
552    }
553}
554
555impl<const N: u32> AsGround for UInt<N> {
556    fn ground() -> GroundType {
557        GroundType::UInt { width: N }
558    }
559}
560
561impl<const N: u32> AsGround for SInt<N> {
562    fn ground() -> GroundType {
563        GroundType::SInt { width: N }
564    }
565}
566
567fn scalar_leaves(field: &str, dir: PortDir, gt: GroundType) -> Vec<(String, PortDir, GroundType)> {
568    vec![(field.to_string(), dir, gt)]
569}
570
571fn bundle_leaves<B: Bundle>(field: &str, dir: PortDir) -> Vec<(String, PortDir, GroundType)> {
572    let mut out: Vec<(String, PortDir, GroundType)> = B::leaves()
573        .iter()
574        .map(|(member, gt)| (format!("{field}_{member}"), dir, gt.clone()))
575        .collect();
576    for (nested, nested_leaves) in B::nested_bundles() {
577        for (leaf, gt) in nested_leaves() {
578            out.push((format!("{field}_{nested}_{leaf}"), dir, gt.clone()));
579        }
580    }
581    out
582}
583
584fn hwvec_leaves<T: AsGround, const N: u32>(
585    field: &str,
586    dir: PortDir,
587) -> Vec<(String, PortDir, GroundType)> {
588    const {
589        assert!(N > 0, "HwVec length must be non-zero");
590    }
591    (0..N)
592        .map(|i| (format!("{field}_{i}"), dir, T::ground()))
593        .collect()
594}
595
596macro_rules! impl_ground_port_field {
597    ($ty:ty) => {
598        impl PortField for Input<$ty> {
599            fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
600                scalar_leaves(field, PortDir::Input, <$ty as AsGround>::ground())
601            }
602        }
603        impl PortField for Output<$ty> {
604            fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
605                scalar_leaves(field, PortDir::Output, <$ty as AsGround>::ground())
606            }
607        }
608    };
609}
610
611impl_ground_port_field!(Bool);
612impl_ground_port_field!(Clock);
613impl_ground_port_field!(Reset);
614
615impl<const N: u32> PortField for Input<Bits<N>> {
616    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
617        scalar_leaves(field, PortDir::Input, Bits::<N>::ground())
618    }
619}
620impl<const N: u32> PortField for Output<Bits<N>> {
621    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
622        scalar_leaves(field, PortDir::Output, Bits::<N>::ground())
623    }
624}
625
626impl<const N: u32> PortField for Input<UInt<N>> {
627    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
628        scalar_leaves(field, PortDir::Input, UInt::<N>::ground())
629    }
630}
631impl<const N: u32> PortField for Output<UInt<N>> {
632    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
633        scalar_leaves(field, PortDir::Output, UInt::<N>::ground())
634    }
635}
636
637impl<const N: u32> PortField for Input<SInt<N>> {
638    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
639        scalar_leaves(field, PortDir::Input, SInt::<N>::ground())
640    }
641}
642impl<const N: u32> PortField for Output<SInt<N>> {
643    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
644        scalar_leaves(field, PortDir::Output, SInt::<N>::ground())
645    }
646}
647
648impl<T: Bundle> PortField for Input<T> {
649    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
650        bundle_leaves::<T>(field, PortDir::Input)
651    }
652}
653impl<T: Bundle> PortField for Output<T> {
654    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
655        bundle_leaves::<T>(field, PortDir::Output)
656    }
657}
658
659impl<T: AsGround, const N: u32> PortField for Input<HwVec<T, N>> {
660    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
661        hwvec_leaves::<T, N>(field, PortDir::Input)
662    }
663}
664impl<T: AsGround, const N: u32> PortField for Output<HwVec<T, N>> {
665    fn flatten(field: &str) -> Vec<(String, PortDir, GroundType)> {
666        hwvec_leaves::<T, N>(field, PortDir::Output)
667    }
668}
669
670/// Register a directed port field, flattening composites to scalar HIR ports.
671pub fn add_port_field<P: PortField>(session: &mut ElaborateSession, field: &str, span: Span) {
672    for (name, dir, gt) in P::flatten(field) {
673        match dir {
674            PortDir::Input => session.add_input(name, gt, span),
675            PortDir::Output => session.add_output(name, gt, span),
676        }
677    }
678}