bitloom-macro 1.1.0

Bitloom proc-macro sugar → builder paths; includes #[derive(Bundle)] (FR80)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! Proc macros expand only to `bitloom_builder` / prelude paths (AD-6). Never depend on rhdl-hir.

use proc_macro::TokenStream;
use quote::quote;
use syn::{
    Attribute, Data, DeriveInput, Fields, GenericArgument, ItemFn, PathArguments, Type,
    parse_macro_input,
};

/// FR102 / AD-5: `#[functional_state]` / `#[rhdl::functional_state]` (last path segment).
fn is_functional_state_attr(attr: &Attribute) -> bool {
    attr.path()
        .segments
        .last()
        .is_some_and(|s| s.ident == "functional_state")
}

/// Drop inert `functional_state` field attrs so rustc never sees unknown attributes.
fn strip_functional_state_field_attrs(input: &mut DeriveInput) {
    if let Data::Struct(data) = &mut input.data {
        for field in data.fields.iter_mut() {
            field.attrs.retain(|a| !is_functional_state_attr(a));
        }
    }
}

/// Derive [`bitloom_prelude::Bundle`] from named struct fields (FR80 / Story 32.3).
///
/// **Supported:** named-field structs; ground fields `Bool` / `Clock` / `Reset` /
/// `UInt<N>` / `SInt<N>` / `Bits<N>`; other simple path types as **one-level** nested
/// Bundles (`Type::leaves`).
///
/// **Rejected (stable `compile_error!`):** enums, unions, tuple structs, unit structs
/// without named fields, `HwVec<_>`, `Input<_>` / `Output<_>`, references/tuples/arrays,
/// and non-path field types.
///
/// Re-exported from `bitloom-prelude` so design crates never depend on this crate
/// directly (AD-6).
#[proc_macro_derive(Bundle, attributes(bundle))]
pub fn derive_bundle(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match expand_derive_bundle(&input) {
        Ok(ts) => ts,
        Err(e) => e.to_compile_error().into(),
    }
}

fn expand_derive_bundle(input: &DeriveInput) -> Result<TokenStream, syn::Error> {
    if !input.generics.params.is_empty() {
        return Err(syn::Error::new_spanned(
            &input.generics,
            "rhdl::E0180: #[derive(Bundle)] does not support generic parameters",
        ));
    }

    let Data::Struct(data) = &input.data else {
        return Err(syn::Error::new_spanned(
            input,
            "rhdl::E0180: #[derive(Bundle)] only supports structs with named fields",
        ));
    };

    let Fields::Named(fields) = &data.fields else {
        return Err(syn::Error::new_spanned(
            &data.fields,
            "rhdl::E0180: #[derive(Bundle)] requires named fields (tuple/unit structs unsupported)",
        ));
    };

    let name = &input.ident;
    let mut leaf_entries = Vec::new();
    let mut nested_entries = Vec::new();

    for field in &fields.named {
        let Some(ident) = &field.ident else {
            return Err(syn::Error::new_spanned(
                field,
                "rhdl::E0180: #[derive(Bundle)] requires named fields",
            ));
        };
        let field_name = ident.to_string();
        match classify_bundle_field(&field.ty)? {
            BundleFieldKind::Ground { ground_expr } => {
                leaf_entries.push(quote! {
                    (#field_name, #ground_expr)
                });
            }
            BundleFieldKind::Nested { ty } => {
                nested_entries.push(quote! {
                    (#field_name, <#ty as ::bitloom_prelude::Bundle>::leaves)
                });
            }
        }
    }

    Ok(TokenStream::from(quote! {
        impl ::bitloom_prelude::Bundle for #name {
            fn leaves() -> &'static [(&'static str, ::bitloom_prelude::GroundType)] {
                &[#(#leaf_entries),*]
            }

            fn nested_bundles() -> &'static [(
                &'static str,
                fn() -> &'static [(&'static str, ::bitloom_prelude::GroundType)],
            )] {
                &[#(#nested_entries),*]
            }
        }
    }))
}

enum BundleFieldKind {
    Ground {
        ground_expr: proc_macro2::TokenStream,
    },
    Nested {
        ty: Type,
    },
}

fn classify_bundle_field(ty: &Type) -> Result<BundleFieldKind, syn::Error> {
    let Type::Path(type_path) = ty else {
        return Err(syn::Error::new_spanned(
            ty,
            "rhdl::E0180: #[derive(Bundle)] field types must be simple paths (ground or nested Bundle)",
        ));
    };

    if type_path.qself.is_some() {
        return Err(syn::Error::new_spanned(
            ty,
            "rhdl::E0180: #[derive(Bundle)] does not support qualified self types",
        ));
    }

    let last =
        type_path.path.segments.last().ok_or_else(|| {
            syn::Error::new_spanned(ty, "rhdl::E0180: empty path in Bundle field")
        })?;
    let ident = last.ident.to_string();

    match ident.as_str() {
        "HwVec" => {
            return Err(syn::Error::new_spanned(
                ty,
                "rhdl::E0180: #[derive(Bundle)] does not support HwVec fields; HwVec<Bundle,_> remains OUT OF SCOPE",
            ));
        }
        "Input" | "Output" => {
            return Err(syn::Error::new_spanned(
                ty,
                "rhdl::E0180: #[derive(Bundle)] fields must be bare ground or nested Bundle types, not Input/Output",
            ));
        }
        "Bool" => {
            require_no_args(ty, &last.arguments)?;
            return Ok(BundleFieldKind::Ground {
                ground_expr: quote! { ::bitloom_prelude::GroundType::Bool },
            });
        }
        "Clock" => {
            require_no_args(ty, &last.arguments)?;
            return Ok(BundleFieldKind::Ground {
                ground_expr: quote! { ::bitloom_prelude::GroundType::Clock },
            });
        }
        "Reset" => {
            require_no_args(ty, &last.arguments)?;
            return Ok(BundleFieldKind::Ground {
                ground_expr: quote! { ::bitloom_prelude::GroundType::Reset },
            });
        }
        "UInt" | "Bits" => {
            let width = const_generic_u32(ty, &last.arguments)?;
            return Ok(BundleFieldKind::Ground {
                ground_expr: quote! { ::bitloom_prelude::GroundType::UInt { width: #width } },
            });
        }
        "SInt" => {
            let width = const_generic_u32(ty, &last.arguments)?;
            return Ok(BundleFieldKind::Ground {
                ground_expr: quote! { ::bitloom_prelude::GroundType::SInt { width: #width } },
            });
        }
        _ => {}
    }

    // Nested Bundle: simple path, no type args (Epic 32 one-level contract).
    if !matches!(last.arguments, PathArguments::None) {
        return Err(syn::Error::new_spanned(
            ty,
            "rhdl::E0180: #[derive(Bundle)] nested Bundle fields must be bare type paths without generics",
        ));
    }

    Ok(BundleFieldKind::Nested { ty: ty.clone() })
}

fn require_no_args(ty: &Type, args: &PathArguments) -> Result<(), syn::Error> {
    if matches!(args, PathArguments::None) {
        Ok(())
    } else {
        Err(syn::Error::new_spanned(
            ty,
            "rhdl::E0180: unexpected type arguments on ground Bundle field",
        ))
    }
}

fn const_generic_u32(ty: &Type, args: &PathArguments) -> Result<u32, syn::Error> {
    let PathArguments::AngleBracketed(ab) = args else {
        return Err(syn::Error::new_spanned(
            ty,
            "rhdl::E0180: width-parameterized ground types require a const generic (e.g. UInt<8>)",
        ));
    };
    let mut width: Option<u32> = None;
    for arg in &ab.args {
        match arg {
            GenericArgument::Const(syn::Expr::Lit(syn::ExprLit {
                lit: syn::Lit::Int(lit),
                ..
            })) => {
                if width.is_some() {
                    return Err(syn::Error::new_spanned(
                        ty,
                        "rhdl::E0180: expected exactly one const width parameter",
                    ));
                }
                width = Some(lit.base10_parse()?);
            }
            _ => {
                return Err(syn::Error::new_spanned(
                    arg,
                    "rhdl::E0180: ground width must be an integer literal const generic",
                ));
            }
        }
    }
    width.ok_or_else(|| {
        syn::Error::new_spanned(
            ty,
            "rhdl::E0180: width-parameterized ground types require a const generic (e.g. UInt<8>)",
        )
    })
}

/// Marks a struct as an RHDL module shell for Story 1.1.
/// Generates `Elaboratable` that records directed ports via the builder session.
///
/// Fields marked `#[functional_state]` / `#[rhdl::functional_state]` (FR102) are
/// host-only soft state: kept on the Rust struct, **skipped** for port registration,
/// and never enter FrozenHir / `freeze` (AD-5 / AD-18).
#[proc_macro_attribute]
pub fn module(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    let name = &input.ident;
    let vis = &input.vis;

    let syn::Data::Struct(data) = &input.data else {
        return syn::Error::new_spanned(&input, "rhdl::module only supports structs")
            .to_compile_error()
            .into();
    };

    let mod_name = name.to_string();
    let field_defs = data.fields.iter().map(|f| {
        let id = f.ident.as_ref().unwrap();
        let ty = &f.ty;
        let fvis = &f.vis;
        // Strip functional_state so the expanded struct is plain Rust.
        let keep_attrs: Vec<_> = f
            .attrs
            .iter()
            .filter(|a| !is_functional_state_attr(a))
            .collect();
        quote! { #(#keep_attrs)* #fvis #id: #ty }
    });

    let port_stmts = data.fields.iter().filter_map(|field| {
        if field.attrs.iter().any(is_functional_state_attr) {
            // FR102 negative gate: soft fields must not register as HIR ports.
            return None;
        }
        let Some(ident) = &field.ident else {
            return Some(quote! {
                compile_error!("tuple structs are not supported by rhdl::module");
            });
        };
        let ty = &field.ty;
        let name_str = ident.to_string();
        Some(quote! {
            {
                type __PortTy = #ty;
                for (__leaf, __dir, __gt) in
                    <__PortTy as ::bitloom_prelude::PortField>::flatten(#name_str)
                {
                    match __dir {
                        ::bitloom_prelude::PortDir::Input => {
                            __session.add_input(
                                __leaf,
                                __gt,
                                ::bitloom_prelude::Span::default(),
                            );
                        }
                        ::bitloom_prelude::PortDir::Output => {
                            __session.add_output(
                                __leaf,
                                __gt,
                                ::bitloom_prelude::Span::default(),
                            );
                        }
                    }
                }
            }
        })
    });

    TokenStream::from(quote! {
        #vis struct #name {
            #(#field_defs),*
        }

        impl ::bitloom_prelude::Elaboratable for #name {
            fn elaborate() -> ::core::result::Result<
                ::bitloom_prelude::FrozenHir,
                ::bitloom_prelude::Diagnostics,
            > {
                let mut __session = ::bitloom_prelude::ElaborateSession::new(#mod_name);
                __session.begin_module(#mod_name, ::bitloom_prelude::Span::default());
                #(#port_stmts)*
                __session.end_module();
                __session.finish()
            }
        }
    })
}

/// Marks a hardware process as combinational. Expands to a builder open/close
/// around the function body (must call session helpers for assigns).
#[proc_macro_attribute]
pub fn combinational(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);
    let vis = &input.vis;
    let sig = &input.sig;
    let block = &input.block;
    let attrs = &input.attrs;
    TokenStream::from(quote! {
        #(#attrs)*
        #vis #sig {
            // Marker retained so unmarked hardware fns are distinguishable.
            const _: () = ();
            let __rhdl_process_kind = ::bitloom_prelude::ProcessKindMark::Combinational;
            let _ = __rhdl_process_kind;
            #block
        }
    })
}

/// Marks a hardware process as sequential.
#[proc_macro_attribute]
pub fn sequential(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);
    let vis = &input.vis;
    let sig = &input.sig;
    let block = &input.block;
    let attrs = &input.attrs;
    TokenStream::from(quote! {
        #(#attrs)*
        #vis #sig {
            const _: () = ();
            let __rhdl_process_kind = ::bitloom_prelude::ProcessKindMark::Sequential;
            let _ = __rhdl_process_kind;
            #block
        }
    })
}

/// Rejects unmarked hardware process attributes — use `combinational`/`sequential`.
#[proc_macro_attribute]
pub fn process(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);
    syn::Error::new_spanned(
        input.sig.ident,
        "hardware processes must use #[combinational] or #[sequential]; bare #[process] is forbidden",
    )
    .to_compile_error()
    .into()
}

/// Marks a handwritten functional model (Story 3.3). Does not enter FrozenHir.
#[proc_macro_attribute]
pub fn functional_model(_attr: TokenStream, item: TokenStream) -> TokenStream {
    host_only_view(item, "FunctionalModel")
}

/// Handwritten TLM↔pin adapter (FR29). Host-only; never enters FrozenHir / freeze.
/// Does **not** generate TLM from HIR.
#[proc_macro_attribute]
pub fn bridge(_attr: TokenStream, item: TokenStream) -> TokenStream {
    host_only_view(item, "Bridge")
}

/// Handwritten untimed / transaction abstraction (FR29). Host-only.
#[proc_macro_attribute]
pub fn abstraction(_attr: TokenStream, item: TokenStream) -> TokenStream {
    host_only_view(item, "Abstraction")
}

/// Mixed `both` simulation: RTL (`tick`) + handwritten view in one fixture (FR29).
#[proc_macro_attribute]
pub fn both(_attr: TokenStream, item: TokenStream) -> TokenStream {
    host_only_view(item, "Both")
}

/// Marks a function for HLS (FR35 external and/or FR95 in-tree). Does not schedule in the macro;
/// scheduling is `bitloom::hls::schedule_in_tree` (FR95) or external Bambu (FR35).
#[proc_macro_attribute]
pub fn hls(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);
    let vis = &input.vis;
    let sig = &input.sig;
    let block = &input.block;
    let attrs = &input.attrs;
    TokenStream::from(quote! {
        #(#attrs)*
        #vis #sig {
            const _: () = ();
            let __rhdl_hls = ::bitloom_prelude::HlsMark;
            let _ = __rhdl_hls;
            #block
        }
    })
}

fn host_only_view(item: TokenStream, kind: &str) -> TokenStream {
    let mut input = parse_macro_input!(item as DeriveInput);
    // FR102: allow `#[functional_state]` on host view fields; strip before emit.
    strip_functional_state_field_attrs(&mut input);
    let name = &input.ident;
    let kind_ident = syn::Ident::new(kind, name.span());
    TokenStream::from(quote! {
        #input

        impl ::bitloom_prelude::HostView for #name {
            const KIND: ::bitloom_prelude::ViewKind = ::bitloom_prelude::ViewKind::#kind_ident;
        }
        // Host-only; never participates in freeze/HIR. No HIR→TLM lowering.
    })
}

/// Marks the elaboratable top for `cargo rhdl build` (AD-19).
#[proc_macro_attribute]
pub fn top(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    let name = &input.ident;
    TokenStream::from(quote! {
        #input

        impl #name {
            /// ABI marker used by the RHDL host/CLI.
            pub const RHDL_TOP: bool = true;
        }
    })
}

/// FR157: mark an FSM state `enum` so variant names become a label set.
///
/// Optional attribute: `name = "demo"` overrides the FSM id (default: type name).
/// Only unit variants are supported. Empty enums / non-enums → `compile_error!`.
///
/// Implements [`bitloom_prelude::FsmLabels`]. Re-exported as `#[rhdl::fsm]` /
/// `#[bitloom::fsm]` from `bitloom-prelude` (AD-6).
#[proc_macro_attribute]
pub fn fsm(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as FsmAttrArgs);
    let input = parse_macro_input!(item as DeriveInput);
    match expand_fsm(&args, &input) {
        Ok(ts) => ts,
        Err(e) => e.to_compile_error().into(),
    }
}

struct FsmAttrArgs {
    name: Option<syn::LitStr>,
}

impl syn::parse::Parse for FsmAttrArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        if input.is_empty() {
            return Ok(Self { name: None });
        }
        let ident: syn::Ident = input.parse()?;
        if ident != "name" {
            return Err(syn::Error::new(ident.span(), "expected `name = \"...\"`"));
        }
        input.parse::<syn::Token![=]>()?;
        let name: syn::LitStr = input.parse()?;
        Ok(Self { name: Some(name) })
    }
}

fn expand_fsm(args: &FsmAttrArgs, input: &DeriveInput) -> Result<TokenStream, syn::Error> {
    let Data::Enum(data) = &input.data else {
        return Err(syn::Error::new_spanned(
            &input.ident,
            "#[bitloom::fsm] / #[rhdl::fsm] may only be applied to enums (FR157)",
        ));
    };
    if data.variants.is_empty() {
        return Err(syn::Error::new_spanned(
            &input.ident,
            "#[bitloom::fsm] enum must have at least one variant (FR157)",
        ));
    }
    let mut label_lits = Vec::new();
    for v in &data.variants {
        if !matches!(v.fields, Fields::Unit) {
            return Err(syn::Error::new_spanned(
                &v.ident,
                "#[bitloom::fsm] supports only unit variants (FR157 MVP)",
            ));
        }
        let lit = v.ident.to_string();
        label_lits.push(syn::LitStr::new(&lit, v.ident.span()));
    }
    let ty = &input.ident;
    let fsm_id = if let Some(n) = &args.name {
        n.value()
    } else {
        ty.to_string()
    };
    let fsm_id_lit = syn::LitStr::new(&fsm_id, ty.span());
    Ok(TokenStream::from(quote! {
        #input

        impl ::bitloom_prelude::FsmLabels for #ty {
            const FSM_ID: &'static str = #fsm_id_lit;
            fn state_labels() -> &'static [&'static str] {
                &[#(#label_lits),*]
            }
        }
    }))
}