Skip to main content

dive_stdlib/random/
mod.rs

1//! TLC's randomness, bit-exact, and dive's replayable randomness.
2//!
3//! TLC's random operators are unseeded unless `-seed` is given; its draws while
4//! expanding a state also depend on the fingerprint polynomial, and in simulation on
5//! which worker ran a trace, so `-seed` alone does not replay them. dive always
6//! reports the seed it used, and `--seed` alone replays a run exactly at any worker
7//! count; `--compat=tlc` reproduces TLC's draws bit for bit. See
8//! [Differences from TLC](https://github.com/Chelis-Lang/dive/blob/main/docs/tlc-differences.md).
9//!
10//! # Layers
11//!
12//! - [`RandomSource`]: a source of random bits with Java's derived draws
13//!   (`nextDouble`, `nextInt(bound)`, `nextLong`) and TLC's `nextPrime`. Any
14//!   `FnMut(u32) -> i32` is one, so the evaluator can carry a source without naming
15//!   this crate.
16//! - [`JavaRandom`]: `java.util.Random`, bit-exact.
17//! - [`Streams`]: where each stream starts, under [`RandomMode::Tlc`] (TLC's seeding)
18//!   or [`RandomMode::Dive`] (replayable at any worker count).
19//! - [`random_element`], [`random_subset`], [`random_set_of_subsets`]: the operators
20//!   over [`dive_value::Value`]s, drawing exactly as TLC's Java overrides draw.
21//!
22//! # Using it from the evaluator and the checker
23//!
24//! The checker owns the streams: it asks [`Streams::startup`] for constant
25//! definitions, `ASSUME`s and `Init`, and [`Streams::state`] once per expanded state
26//! (TLC: `fingerprint(state) ^ seed`). The evaluator passes the current stream down to
27//! the operator as a `&mut dyn FnMut(u32) -> i32`:
28//!
29//! ```
30//! use dive_stdlib::random::{random_element, RandomMode, RandomSource, Streams};
31//! use dive_value::{Ctx, Int, Value, print::print_value};
32//!
33//! let ctx = Ctx::tlc();
34//! let streams = Streams::new(7, RandomMode::Tlc);
35//! let mut stream = streams.startup();
36//! // What dive-eval would carry in its context:
37//! let mut bits = |n| stream.next_bits(n);
38//! let s = Value::interval(Int::from(1i64), Int::from(1_000_000i64), ctx);
39//! let v = random_element(&s, ctx, &mut bits)?;
40//! // Under TLC -seed 7, `RandomElement(1..1000000)` is 730700.
41//! assert_eq!(print_value(&v, ctx)?, "730700");
42//! # Ok::<(), Box<dyn std::error::Error>>(())
43//! ```
44//!
45//! Under [`RandomMode::Tlc`], [`Streams::state`] needs TLC's own state fingerprint,
46//! which depends on TLC's variable order; under [`RandomMode::Dive`] any
47//! fixed 64-bit state fingerprint gives a replayable run.
48
49mod lcg;
50mod ops;
51mod primes;
52mod seeding;
53mod source;
54
55pub use ops::{
56    RANDOM_ELEMENT_METHOD, RANDOM_SET_OF_SUBSETS_METHOD, RANDOM_SUBSET_METHOD, RandomError,
57    random_element, random_set_of_subsets, random_subset,
58};
59pub use seeding::{DiveStream, RandomMode, Stream, Streams, fresh_seed, parse_seed};
60pub use source::{JavaRandom, RandomSource};