const-builder 0.1.6

Derive macro for const-compatible compile-time checked builders.
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
#![no_std]
// enable basically all clippy lints so we can see unexpected
// ones triggering while testing and debugging.
#![warn(
    clippy::complexity,
    clippy::correctness,
    clippy::nursery,
    clippy::pedantic,
    clippy::perf,
    clippy::style,
    clippy::suspicious
)]
#![allow(clippy::derive_partial_eq_without_eq)]

use core::any::TypeId;
use core::marker::PhantomData;
use core::mem::ManuallyDrop;

use const_builder::ConstBuilder;

/// Helper trait for `dyn` with reference-identity equality.
trait Object: core::fmt::Debug {}
impl<T: core::fmt::Debug> Object for T {}

impl PartialEq for dyn Object + '_ {
    fn eq(&self, other: &Self) -> bool {
        core::ptr::eq(self, other)
    }
}

#[derive(Debug, PartialEq, ConstBuilder)]
pub struct Person<'a> {
    pub name: &'a str,
    #[builder(default = 0)]
    pub age: u32,
}

#[derive(Debug, PartialEq, ConstBuilder)]
#[builder(default)]
struct Defaultable {
    #[builder(default = 0, leak_on_drop)]
    key: u32,
    #[builder(default = Some(0))]
    value: Option<u32>,
}

#[derive(Debug, PartialEq, ConstBuilder)]
#[repr(Rust, packed)]
struct PackedUnsize<T: ?Sized> {
    #[builder(default = r#""hello world""#)]
    id: &'static str,
    #[builder(unsized_tail)]
    tail: ManuallyDrop<T>,
}

#[derive(Debug, PartialEq, ConstBuilder)]
#[repr(C, packed(4))]
struct Packed4 {
    // the macro doesn't actually care about field alignment.
    // it will either use all aligned or all unaligned operations.
    aligned: u32,
    unaligned: u64,
}

#[derive(Debug, PartialEq, ConstBuilder)]
struct StripOption {
    #[builder(setter(strip_option))]
    value: Option<u32>,
}

#[derive(Debug, PartialEq, ConstBuilder)]
struct StripOptionSpecial<'a, T> {
    #[builder(setter(strip_option))]
    dyn_trait: Option<&'a dyn Object>,
    #[builder(setter(strip_option))]
    gen_value: Option<T>,
}

#[derive(Debug, PartialEq, ConstBuilder)]
struct Sum {
    #[builder(setter(transform = |a: u32, b: u32| a + b))]
    value: u32,
}

#[derive(Debug, PartialEq, ConstBuilder)]
struct OddButValidTransforms {
    #[builder(setter(transform = ((|a: i32| a * 2))))]
    wrapped: i32,
    #[builder(setter(transform = "|a: u32| a + 1"))]
    in_literal: u32,
    #[builder(setter(transform = for<'a> |a: &'a u32| *a))]
    with_lifetime: u32,
    // so this wasn't intentional but it parses and emits correctly.
    // may be useful when const traits are stabilized.
    #[builder(setter(transform = for<I: Copy> |a: I| size_of_val(&a)))]
    with_generic: usize,
}

struct Droppable;
impl Drop for Droppable {
    fn drop(&mut self) {}
}

#[expect(
    non_camel_case_types,
    reason = "struct builder types may start with lowercase letter"
)]
#[expect(
    non_upper_case_globals,
    reason = "generic `r#const` should be uppercase"
)]
#[expect(clippy::use_self)]
mod raw {
    // ensure raw idents compile in every possible position
    use const_builder::ConstBuilder;

    #[derive(Debug, PartialEq, ConstBuilder)]
    pub struct r#struct {
        pub r#fn: r#bool,
        pub r#type: &'r#static r#str,
        #[builder(
            default = None,
            setter(strip_option),
            rename = r#pub,
            rename_generic = r#const,
        )]
        pub r#next: r#Option<&'r#static r#struct>,
    }

    #[allow(dead_code)]
    #[derive(Debug, PartialEq, ConstBuilder)]
    #[builder(rename = r#use, rename_fn = r#struct, unchecked(rename = r#let))]
    struct r#mod {
        _f: (),
    }
}

trait WeirdGatTrait {
    type Opt<T, U>;
}

impl<V> WeirdGatTrait for PhantomData<V> {
    type Opt<T, U> = Option<T>;
}

#[derive(Debug, PartialEq, ConstBuilder)]
struct WeirdGatUse<T, U, V> {
    // resolves to `Option<T>`, tests that the behavior for which generic is picked stays
    // consistent across releases and that it keeps compiling. the derive can't actually see the
    // real type, so it can only _guess_ what generic it needs to extract to get the `Option`'s
    // inner type for `strip_option`.
    // the current behavior is "first argument to last path segment", which is `T` here.
    #[builder(setter(strip_option))]
    opt: <PhantomData<U> as WeirdGatTrait>::Opt<T, V>,
}

#[derive(Debug, PartialEq, ConstBuilder)]
struct DeprecatedFields {
    #[deprecated = "outdated, use `new_field`"]
    #[builder(default = 0)]
    old_field: u32,
    new_field: u64,
}

#[derive(Debug, PartialEq, ConstBuilder)]
struct DefaultedGenerics<T, U: Default = u32> {
    value: T,
    #[builder(default = PhantomData)]
    marker: PhantomData<U>,
}

impl<T, U: 'static + Default> DefaultedGenerics<T, U> {
    #[expect(clippy::unused_self)]
    fn u_type_id(&self) -> TypeId {
        TypeId::of::<U>()
    }
}

#[derive(Debug, PartialEq)]
struct PanicDrop(usize);
impl Drop for PanicDrop {
    fn drop(&mut self) {
        panic!("this value must not be dropped");
    }
}

// used to assert leak behavior
#[derive(Debug, PartialEq, ConstBuilder)]
struct HasPanicDropField {
    #[builder(default = PanicDrop(0))]
    field: PanicDrop,
}

#[test]
fn no_std_person() {
    const STEVE: Person<'_> = const {
        Person::builder()
            .name("steve smith")
            // keep the default for age
            .build()
    };

    assert_eq!(
        STEVE,
        Person {
            name: "steve smith",
            age: 0
        }
    );
}

#[test]
fn defaultable() {
    let default = const { Defaultable::default() };
    assert_eq!(default, <Defaultable as Default>::default());
    assert_eq!(
        default,
        Defaultable {
            key: 0,
            value: Some(0),
        }
    );
}

#[test]
fn packed_unsize() {
    let _drop_me = PackedUnsize::builder()
        .id("1024")
        .tail(ManuallyDrop::new(Droppable));

    let packed = PackedUnsize::builder()
        .id("16")
        .tail(ManuallyDrop::new([1u8, 2, 3, 4]))
        .build();

    let unsized_packed: &PackedUnsize<[u8]> = &packed;

    assert_eq!({ unsized_packed.id }, "16");
    assert_eq!(*unsized_packed.tail, [1u8, 2, 3, 4]);
}

#[test]
fn packed4() {
    let packed = const { Packed4::builder().aligned(42).unaligned(600).build() };

    assert_eq!(
        packed,
        Packed4 {
            aligned: 42,
            unaligned: 600
        }
    );
}

#[test]
fn strip_option() {
    let strip = StripOption::builder().value(16).build();
    assert_eq!(strip, StripOption { value: Some(16) });
}

#[test]
fn strip_option_special() {
    // miri later considers the `dyn Object` refs different if they are created
    // separately on both sides of the comparison.
    let dyn_value = 42u32;
    let dyn_value: &dyn Object = &dyn_value;

    let strip = StripOptionSpecial::builder()
        .dyn_trait(dyn_value)
        .gen_value(60usize)
        .build();

    assert_eq!(
        strip,
        StripOptionSpecial {
            dyn_trait: Some(dyn_value),
            gen_value: Some(60usize)
        }
    );
}

#[test]
fn transform_sum() {
    let sum = Sum::builder().value(4, 6).build();
    assert_eq!(sum, Sum { value: 10 });
}

#[test]
fn raw_idents() {
    const ROOT: raw::r#struct = raw::r#struct::builder().r#fn(false).r#type("root").build();

    let raw = raw::r#struct::builder()
        .r#fn(true)
        .r#type("name")
        .r#pub(&ROOT)
        .build();

    assert_eq!(
        raw,
        raw::r#struct {
            r#fn: true,
            r#type: "name",
            r#next: Some(&ROOT),
        }
    );
}

#[test]
fn odd_but_valid_transforms() {
    let value = OddButValidTransforms::builder()
        .wrapped(8)
        .in_literal(6)
        .with_lifetime(&52)
        .with_generic([0u8; 23])
        .build();

    assert_eq!(
        value,
        OddButValidTransforms {
            wrapped: 16,
            in_literal: 7,
            with_lifetime: 52,
            with_generic: 23,
        }
    );
}

#[test]
fn weird_gat_use() {
    // unique target type used for the generic type used by the `strip_option` field
    // to be sure the derive doesn't get the wrong generic
    #[derive(Debug, PartialEq)]
    struct StripTarget;

    let weird_gat: WeirdGatUse<StripTarget, &str, ()> =
        const { WeirdGatUse::builder().opt(StripTarget).build() };

    assert_eq!(
        weird_gat,
        WeirdGatUse {
            opt: Some(StripTarget)
        }
    );
}

#[test]
fn deprecated_fields_new() {
    let value = DeprecatedFields::builder().new_field(48).build();

    assert_eq!(
        value,
        DeprecatedFields {
            #[expect(deprecated)]
            old_field: 0,
            new_field: 48
        }
    );
}

#[test]
fn deprecated_fields_old() {
    #[expect(deprecated)]
    let value = DeprecatedFields::builder()
        .old_field(32)
        .new_field(0)
        .build();

    assert_eq!(
        value,
        DeprecatedFields {
            #[expect(deprecated)]
            old_field: 32,
            new_field: 0
        }
    );
}

#[test]
fn defaulted_generics_use_default() {
    // annotate the type here to enforce using the default on the 2nd generic
    let builder: DefaultedGenericsBuilder<&str> = DefaultedGenerics::builder();
    let value = builder.value("hello world").build();

    assert_eq!(
        value,
        DefaultedGenerics {
            value: "hello world",
            marker: PhantomData
        }
    );
    assert_eq!(value.u_type_id(), TypeId::of::<u32>());
}

#[test]
fn defaulted_generics_imply() {
    // infer the generic by the surrounding context
    // i.e. the default is irrelevant unless we actually annotate types
    let value = DefaultedGenerics::builder().value("goodbye").build();

    assert_eq!(
        value,
        DefaultedGenerics {
            value: "goodbye",
            // does not compile without this turbofish
            marker: PhantomData::<()>
        }
    );
    assert_eq!(value.u_type_id(), TypeId::of::<()>());
}

#[test]
fn defaulted_panic_drop_field() {
    // since replacing the default value is likely never going to be changed to drop
    // the default (see comment in `replace_panic_drop_field`), that value should
    // also not be dropped if the builder is dropped

    // defaulted field is always leaked
    let _panic_drop = HasPanicDropField::builder();
}

#[test]
fn replace_panic_drop_field() {
    // while `[const] Destruct` may be used once it's stable, using such a bound
    // here would prevent setting fields of types such as `Cow<'_, B>` in const

    // replaced defaulted field is leaked
    let panic_drop = HasPanicDropField::builder().field(PanicDrop(42)).build();

    // wrap the struct so it doesn't panic on drop
    let no_drop = ManuallyDrop::new(panic_drop);
    assert_eq!(
        no_drop,
        ManuallyDrop::new(HasPanicDropField {
            field: PanicDrop(42),
        })
    );
}