pbt 0.5.3

High-throughput property-based testing with `derive`, swarm-testing, precise sizing, and full graph-theoretic type analysis over mutually inductive and uninstantiable types.
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
//! A masked view into a type's constructors,
//! partitioned into potential leaves and loops.

use {
    crate::{
        Pbt, fields,
        hash::map,
        instantiability,
        multiset::Multiset,
        reflection::{Constructor, Constructors, Erased, Parts, Uninstantiable, constructors_of},
        scc,
        size::Size,
        unavoidability,
        union_find::UnionFind,
    },
    ahash::{HashMap, HashSet},
    alloc::{collections::BTreeMap, sync::Arc},
    core::{any::TypeId, mem, num::NonZero},
    wyrand::WyRand,
};

/// A type's constructors, partitioned into potential leaves and loops,
/// i.e. whether a sub-term of type `Self` is *avoidable* or *reachable*.
#[non_exhaustive]
enum Affordances {
    /// Algebraic constructors partitioned by whether they can leave or stay inside recursion.
    Algebraic {
        /// Sorted list of indices of instantiable constructors
        /// for which a sub-term of type `Self` is *avoidable*.
        potential_leaves: Box<[Constructor]>,
        /// Sorted list of indices of instantiable constructors
        /// for which a sub-term of type `Self` is *reachable*.
        potential_loops: Box<[Constructor]>,
    },
    /// Literal generators enabled by this swarm.
    Literal {
        /// Opaque function pointers that generate values of this type.
        generators: Box<[fn(&mut WyRand) -> Erased]>,
    },
}

/// A masked view into a type's constructors,
/// partitioned into potential leaves and loops.
pub(crate) struct Swarm {
    /// A masked (partial) set of constructors for this type,
    /// partitioned into potential leaves and loops.
    affordances: HashMap<TypeId, Affordances>,
}

impl Affordances {
    /// Whether this type can transitively
    /// contain a field of its own type.
    ///
    /// Equivalently, whether this type can be arbitrarily large.
    #[inline]
    #[must_use]
    fn is_inductive(&self) -> bool {
        match *self {
            Self::Algebraic {
                ref potential_loops,
                ..
            } => !potential_loops.is_empty(),
            Self::Literal { .. } => false,
        }
    }
}

impl Swarm {
    /// Split this type's (instantiable and unmasked)
    /// constructors into potential leaves and loops.
    #[inline]
    fn affordances<T>(&self) -> &Affordances
    where
        T: 'static,
    {
        self.affordances_of(TypeId::of::<T>())
    }

    /// Split this type's (instantiable and unmasked)
    /// constructors into potential leaves and loops.
    #[inline]
    #[expect(
        clippy::expect_used,
        reason = "Internal invariants: violations should fail loudly."
    )]
    fn affordances_of(&self, ty: TypeId) -> &Affordances {
        self.affordances
            .get(&ty)
            .expect("INTERNAL ERROR (`pbt`): unregistered type")
    }

    /// Generate an arbitrary term of some type.
    #[inline]
    #[expect(
        clippy::panic,
        reason = "Internal invariants: violations should fail loudly."
    )]
    pub(crate) fn arbitrary<T>(&self, size: Size, prng: &mut WyRand) -> T
    where
        T: Pbt,
    {
        let (potential_leaves, potential_loops) = match *self.affordances::<T>() {
            Affordances::Algebraic {
                ref potential_leaves,
                ref potential_loops,
            } => (potential_leaves, potential_loops),
            Affordances::Literal { ref generators } => {
                #[expect(
                    clippy::expect_used,
                    reason = "Swarms for uninstantiable literal types are rejected during construction."
                )]
                let n = NonZero::new(generators.len()).expect(
                    "INTERNAL ERROR (`pbt`): swarm created for an uninstantiable literal type",
                );
                #[expect(
                    clippy::as_conversions,
                    clippy::cast_possible_truncation,
                    reason = "Intentional lossy sampling from a 64-bit PRNG into machine-word indices."
                )]
                let generator_index = prng.rand() as usize % n;
                // SAFETY: `%` above.
                let erased = unsafe { *generators.get_unchecked(generator_index) };
                // SAFETY: `Registration::register::<T>` erased this function pointer.
                let generate = unsafe {
                    mem::transmute::<fn(&mut WyRand) -> Erased, fn(&mut WyRand) -> T>(erased)
                };
                return generate(prng);
            }
        };

        let (ctors, n) = if let Some(n_loops) = NonZero::new(potential_loops.len())
            && size.should_recurse(prng)
        {
            (potential_loops.as_ref(), n_loops)
        } else if let Some(n_leaves) = NonZero::new(potential_leaves.len()) {
            (potential_leaves.as_ref(), n_leaves)
        } else {
            panic!("INTERNAL ERROR (`pbt`): swarm created for an uninstantiable type")
        };

        #[expect(
            clippy::as_conversions,
            clippy::cast_possible_truncation,
            reason = "OK: `u64` is already huge"
        )]
        let ctor_index = prng.rand() as usize % n;
        // SAFETY: `%` above.
        let ctor = unsafe { ctors.get_unchecked(ctor_index) };

        let n_ind = self.count_inductive_fields(ctor.field_types());
        let sizes = size.partition(n_ind, prng);
        T::construct(Parts {
            fields: fields::Lazy {
                prng,
                sizes,
                swarm: self,
            },
            variant_index: Some(ctor.index),
        })
    }

    /// How many fields on this variant have inductive types?
    ///
    /// Two fields of the same type will count twice,
    /// since this is for partitioning a total size among fields.
    #[inline]
    #[expect(
        clippy::arithmetic_side_effects,
        reason = "if there were more than `usize::MAX` fields, they wouldn't have compiled"
    )]
    fn count_inductive_fields(&self, field_types: &Multiset<TypeId>) -> usize {
        let mut acc = 0_usize;
        for (&ty, count) in field_types.iter() {
            if self.affordances_of(ty).is_inductive() {
                acc += count.get();
            }
        }
        acc
    }

    /// Whether this type can transitively
    /// contain a field of its own type.
    ///
    /// Equivalently, whether this type can be arbitrarily large.
    #[inline]
    pub(crate) fn is_inductive<T>(&self) -> bool
    where
        T: 'static,
    {
        self.affordances::<T>().is_inductive()
    }

    /// Randomly disable a subset of variants for
    /// *all types used to construct this type*,
    /// including this type itself.
    ///
    /// See [the original swarm testing paper](https://dl.acm.org/doi/pdf/10.1145/2338965.2336763).
    #[inline]
    #[expect(
        clippy::expect_used,
        reason = "Internal invariants: violations should fail loudly."
    )]
    pub(crate) fn new<T>(
        prng: &mut WyRand,
        cache: &mut HashMap<BTreeMap<TypeId, Constructors<Erased>>, Option<Arc<Self>>>,
    ) -> Result<Arc<Self>, Uninstantiable>
    where
        T: Pbt,
    {
        let ty = TypeId::of::<T>();

        // Check if this type is instantiable *before* masking:
        if constructors_of(ty).is_empty() {
            return Err(Uninstantiable);
        }

        'rejection_sampling: loop {
            // Mask constructors at random (though preferring more variants over fewer variants):
            let mut naive_masked_constructors = BTreeMap::new();
            let () = mask_all_constructors_reachable_from(ty, &mut naive_masked_constructors, prng);
            if let Some(cached) = cache.get(&naive_masked_constructors) {
                match *cached {
                    None => continue 'rejection_sampling, // uninstantiable
                    Some(ref swarm) => return Ok(Arc::clone(swarm)),
                }
            }

            // Remove all uninstantiable variants:
            let mut masked_constructors = map();
            let () =
                instantiability::update(ty, &naive_masked_constructors, &mut masked_constructors);

            // If the original type is uninstantiable with these masks, try again:
            if masked_constructors
                .get(&ty)
                .is_none_or(Constructors::is_empty)
            {
                let _: &mut _ = cache.entry(naive_masked_constructors).or_insert(None);
                continue 'rejection_sampling;
            }

            // Compute strongly connected components, i.e. mutually inductive types:
            let mut scc_quotient_graph = UnionFind::new();
            let () = scc::update(
                ty,
                &|t| {
                    masked_constructors
                        .get(&t)
                        .expect("INTERNAL ERROR (`pbt`): unregistered type")
                        .algebraic()
                        .iter()
                        .flat_map(Constructor::dedup_fields)
                },
                &mut scc_quotient_graph,
            );

            let mut unavoidable = map();
            let () = unavoidability::update(
                ty,
                &mut unavoidable,
                &|t| {
                    masked_constructors
                        .get(&t)
                        .expect("INTERNAL ERROR (`pbt`): unregistered type")
                        .algebraic()
                },
                &|ctor| ctor.dedup_fields(),
            );

            let affordances = masked_constructors
                .into_iter()
                .map(|(t, ctors)| {
                    (
                        t,
                        affordances_of(t, ctors, &mut scc_quotient_graph, &unavoidable),
                    )
                })
                .collect();

            let arc = Arc::new(Self { affordances });
            let _: &mut _ = cache
                .entry(naive_masked_constructors)
                .or_insert(Some(Arc::clone(&arc)));

            return Ok(arc);
        }
    }
}

/// Given some total number of features,
/// how many should we enable?
///
/// This works better than enabling each individually,
/// since binomial distributions collapse very quickly.
#[inline]
#[expect(
    clippy::as_conversions,
    clippy::cast_possible_truncation,
    reason = "OK: `u64` is already huge"
)]
#[expect(
    clippy::arithmetic_side_effects,
    reason = "if there were more than `usize::MAX` fields, they wouldn't have compiled"
)]
fn how_many_features_to_mask_out_of(n_total: usize, prng: &mut WyRand) -> usize {
    // Usually in programming we deal with [0, n),
    // but here we want [0, n], in which `n` itself is an option.
    // SAFETY: `n_total` is the length of an in-memory array,
    // so it cannot be `usize::MAX` while leaving enough memory for this subroutine.
    let inclusive = unsafe { NonZero::new_unchecked(n_total + 1) };

    // Weight "more features" more heavily than "fewer features":
    // specifically, "0 features" has weight 1, "1 feature" has weight 2,
    // etc., up to "all n features" with weight (n+1).
    'rejection_sampling: loop {
        // Sample two points in an `inclusive` by `inclusive` matrix:
        let y = prng.rand() as usize % inclusive;
        let x = prng.rand() as usize % inclusive;

        // Reject above the diagonal:
        if x > y {
            continue 'rejection_sampling;
        }

        return x;
    }
}

/// Pseudorandomly choose which of `n` features remain enabled.
#[inline]
#[expect(
    clippy::arithmetic_side_effects,
    clippy::as_conversions,
    clippy::cast_possible_truncation,
    clippy::integer_division_remainder_used,
    reason = "OK: `u64` is already huge"
)]
fn mask_for(n_total: usize, prng: &mut WyRand) -> Vec<bool> {
    let n_to_mask = how_many_features_to_mask_out_of(n_total, prng);
    let mut mask = vec![true; n_total];
    for _ in 0..n_to_mask {
        'rejection_sampling: loop {
            let i = prng.rand() as usize % n_total;
            // SAFETY: `%` above
            let flip = unsafe { mask.get_unchecked_mut(i) };
            if *flip {
                *flip = false;
                break 'rejection_sampling;
            }
        }
    }
    mask
}

/// Build the masked affordance view for one type.
#[inline]
#[expect(
    clippy::expect_used,
    reason = "Internal invariants: violations should fail loudly."
)]
fn affordances_of(
    ty: TypeId,
    constructors_of_ty: Constructors<Erased>,
    scc_quotient_graph: &mut UnionFind<TypeId>,
    unavoidable: &HashMap<TypeId, Arc<HashSet<TypeId>>>,
) -> Affordances {
    let constructors = match constructors_of_ty {
        Constructors::Algebraic(constructors) => constructors,
        Constructors::Literal { generators, .. } => {
            return Affordances::Literal {
                generators: generators.iter().copied().collect(),
            };
        }
    };

    let self_scc = scc_quotient_graph
        .root(ty)
        .expect("INTERNAL ERROR (`pbt`): SCC missing");

    let mut potential_leaves = vec![];
    let mut potential_loops = vec![];
    for constructor in &*constructors {
        let mut potential_leaf = true;
        let mut potential_loop = false;
        for field in constructor.dedup_fields() {
            if unavoidable
                .get(&field)
                .expect("INTERNAL ERROR (`pbt`): unavoidability missing")
                .contains(&ty)
            {
                potential_leaf = false;
            }
            if scc_quotient_graph
                .root(field)
                .expect("INTERNAL ERROR (`pbt`): SCC missing")
                == self_scc
            {
                potential_loop = true;
            }
        }
        if potential_leaf {
            let () = potential_leaves.push(constructor.clone());
        }
        // Both can coexist.
        if potential_loop {
            let () = potential_loops.push(constructor.clone());
        }
        debug_assert!(
            potential_leaf || potential_loop,
            "INTERNAL ERROR (`pbt`): constructor is neither a leaf nor a loop",
        );
    }

    Affordances::Algebraic {
        potential_leaves: potential_leaves.into_boxed_slice(),
        potential_loops: potential_loops.into_boxed_slice(),
    }
}

/// Run depth-first search, selecting constructors to mask for every type traversed.
#[inline]
fn mask_all_constructors_reachable_from(
    ty: TypeId,
    masked_constructors: &mut BTreeMap<TypeId, Constructors<Erased>>,
    prng: &mut WyRand,
) {
    if masked_constructors.contains_key(&ty) {
        return;
    }

    match constructors_of(ty) {
        Constructors::Algebraic(constructors) => {
            let mask = mask_for(constructors.len(), prng);
            let masked = constructors
                .iter()
                .zip(mask)
                .filter_map(|(constructor, enable)| enable.then_some(constructor.clone()))
                .collect();
            let _dup: Option<_> =
                masked_constructors.insert(ty, Constructors::Algebraic(Arc::clone(&masked)));

            for constructor in &*masked {
                for field_ty in constructor.dedup_fields() {
                    let () =
                        mask_all_constructors_reachable_from(field_ty, masked_constructors, prng);
                }
            }
        }
        Constructors::Literal {
            deserialize,
            generators,
            serialize,
            shrink,
        } => {
            let mask = mask_for(generators.len(), prng);
            let masked_generators = generators
                .iter()
                .zip(mask)
                .filter_map(|(&generate, enable)| enable.then_some(generate))
                .collect();
            let _dup: Option<_> = masked_constructors.insert(
                ty,
                Constructors::Literal {
                    deserialize,
                    generators: masked_generators,
                    serialize,
                    shrink,
                },
            );
        }
    }
}