Skip to main content

kani/
arbitrary.rs

1// Copyright Kani Contributors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! This module introduces the `Arbitrary` trait as well as implementation for
5//! primitive types and other std containers.
6
7use crate::Arbitrary;
8
9impl<T> Arbitrary for std::boxed::Box<T>
10where
11    T: Arbitrary,
12{
13    fn any() -> Self {
14        Box::new(T::any())
15    }
16}
17
18impl<T> Arbitrary for std::rc::Rc<T>
19where
20    T: Arbitrary,
21{
22    fn any() -> Self {
23        std::rc::Rc::new(T::any())
24    }
25}
26
27impl<T> Arbitrary for std::sync::Arc<T>
28where
29    T: Arbitrary,
30{
31    fn any() -> Self {
32        std::sync::Arc::new(T::any())
33    }
34}
35
36/// The models below are used by the compiler to generate nondeterministic
37/// `Box<T>`/`Rc<T>`/`Arc<T>` values for automatic harnesses when `T` does not implement
38/// `Arbitrary` in source code but the compiler can derive it: the `kani::any::<T>()` calls in
39/// their bodies are then replaced with the compiler-synthesized implementation. (For `T`s that
40/// do implement `Arbitrary`, the `Arbitrary` implementations above are resolved directly
41/// instead.)
42/// These models are *optional*: they require `alloc` and thus have no `core::kani`
43/// counterpart, c.f. `KaniModel::is_optional`.
44#[kanitool::fn_marker = "AnyBoxModel"]
45#[inline(never)]
46#[doc(hidden)]
47pub fn any_box<T: Arbitrary>() -> Box<T> {
48    Box::new(crate::any())
49}
50
51#[kanitool::fn_marker = "AnyRcModel"]
52#[inline(never)]
53#[doc(hidden)]
54pub fn any_rc<T: Arbitrary>() -> std::rc::Rc<T> {
55    std::rc::Rc::new(crate::any())
56}
57
58#[kanitool::fn_marker = "AnyArcModel"]
59#[inline(never)]
60#[doc(hidden)]
61pub fn any_arc<T: Arbitrary>() -> std::sync::Arc<T> {
62    std::sync::Arc::new(crate::any())
63}
64
65impl Arbitrary for std::time::Duration {
66    fn any() -> Self {
67        const NANOS_PER_SEC: u32 = 1_000_000_000;
68        let nanos = u32::any();
69        crate::assume(nanos < NANOS_PER_SEC);
70        std::time::Duration::new(u64::any(), nanos)
71    }
72}
73
74impl Arbitrary for std::char::EscapeUnicode {
75    fn any() -> Self {
76        // Generate any state reachable by consuming a freshly constructed
77        // EscapeUnicode iterator from the front.
78        let mut escape = char::any().escape_unicode();
79        let len = escape.len();
80
81        let front = usize::from(u8::any());
82        crate::assume(front <= len);
83
84        if front >= 1 {
85            let _ = escape.next();
86        }
87        if front >= 2 {
88            let _ = escape.next();
89        }
90        if front >= 3 {
91            let _ = escape.next();
92        }
93        if front >= 4 {
94            let _ = escape.next();
95        }
96        if front >= 5 {
97            let _ = escape.next();
98        }
99        if front >= 6 {
100            let _ = escape.next();
101        }
102        if front >= 7 {
103            let _ = escape.next();
104        }
105        if front >= 8 {
106            let _ = escape.next();
107        }
108        if front >= 9 {
109            let _ = escape.next();
110        }
111        if front >= 10 {
112            let _ = escape.next();
113        }
114
115        escape
116    }
117}
118
119impl Arbitrary for std::ascii::EscapeDefault {
120    fn any() -> Self {
121        // Generate any state reachable by consuming a freshly constructed
122        // EscapeDefault iterator from either end.
123        let mut escape = std::ascii::escape_default(u8::any());
124        let len = escape.size_hint().0;
125
126        let front = usize::from(u8::any());
127        crate::assume(front <= len);
128
129        let back = usize::from(u8::any());
130        crate::assume(back <= len - front);
131
132        // The front/back consumption below is unrolled by hand (EscapeDefault
133        // yields at most 4 bytes) rather than written as a loop, so generating
134        // an arbitrary value does not require loop unwinding during verification.
135        if front >= 1 {
136            let _ = escape.next();
137        }
138        if front >= 2 {
139            let _ = escape.next();
140        }
141        if front >= 3 {
142            let _ = escape.next();
143        }
144        if front >= 4 {
145            let _ = escape.next();
146        }
147
148        if back >= 1 {
149            let _ = escape.next_back();
150        }
151        if back >= 2 {
152            let _ = escape.next_back();
153        }
154        if back >= 3 {
155            let _ = escape.next_back();
156        }
157        if back >= 4 {
158            let _ = escape.next_back();
159        }
160
161        escape
162    }
163}
164
165/// Generate a slice of *unbounded* nondeterministic length: a fresh allocation of
166/// nondeterministic size whose contents are nondeterministic, with element validity
167/// established by `slice_validity_assume` (a compiler hook that emits a quantified
168/// assumption constraining each element's raw bits to the element type's layout niche;
169/// a no-op for element types whose every bit pattern is valid, e.g. integers).
170///
171/// This model is used by the compiler to generate nondeterministic `&[T]` arguments for
172/// automatic harnesses (`kani autoharness`) when the element type qualifies; verification
173/// results hold for ALL slice lengths (functions that iterate over the slice surface any
174/// insufficient loop bound as an unwinding-assertion failure rather than passing silently).
175///
176/// This model is *optional*: it requires `alloc` and thus has no `core::kani` counterpart,
177/// c.f. `KaniModel::is_optional`.
178#[kanitool::fn_marker = "AnySliceRefUnboundedModel"]
179#[inline(never)]
180#[doc(hidden)]
181pub fn any_slice_ref_unbounded<T>() -> &'static [T] {
182    let len: usize = crate::any();
183    let elem = std::mem::size_of::<T>();
184    if elem == 0 {
185        // ZST slices: no storage needed, any length is fine.
186        return unsafe { std::slice::from_raw_parts(std::ptr::NonNull::dangling().as_ptr(), len) };
187    }
188    crate::assume(len <= (isize::MAX as usize) / elem);
189    let layout = std::alloc::Layout::array::<T>(len.max(1)).unwrap();
190    let ptr = unsafe { std::alloc::alloc(layout) };
191    crate::assume(!ptr.is_null());
192    slice_validity_assume::<T>(ptr, len);
193    unsafe { std::slice::from_raw_parts(ptr as *const T, len) }
194}
195
196/// Generate a mutable slice of *unbounded* nondeterministic length: as
197/// `any_slice_ref_unbounded`, but returning `&mut [T]`. Each call produces a fresh (leaked)
198/// allocation, so the returned slice is exclusive by construction; writes through it are
199/// unconstrained by other generated values.
200///
201/// This model is *optional*: it requires `alloc`, c.f. `KaniModel::is_optional`.
202#[kanitool::fn_marker = "AnySliceMutUnboundedModel"]
203#[inline(never)]
204#[doc(hidden)]
205pub fn any_slice_mut_unbounded<T>() -> &'static mut [T] {
206    let len: usize = crate::any();
207    let elem = std::mem::size_of::<T>();
208    if elem == 0 {
209        return unsafe {
210            std::slice::from_raw_parts_mut(std::ptr::NonNull::dangling().as_ptr(), len)
211        };
212    }
213    crate::assume(len <= (isize::MAX as usize) / elem);
214    let layout = std::alloc::Layout::array::<T>(len.max(1)).unwrap();
215    let ptr = unsafe { std::alloc::alloc(layout) };
216    crate::assume(!ptr.is_null());
217    slice_validity_assume::<T>(ptr, len);
218    unsafe { std::slice::from_raw_parts_mut(ptr as *mut T, len) }
219}
220
221/// Generate a `Vec` of *unbounded* nondeterministic length: a fresh allocation of
222/// nondeterministic size whose contents are nondeterministic, with element validity
223/// established by `slice_validity_assume` (c.f. `any_slice_ref_unbounded`), handed to
224/// `Vec::from_raw_parts` with `capacity` equal to the allocated element count (`len.max(1)`
225/// for non-ZSTs, since the allocation uses `Layout::array::<T>(len.max(1))` to avoid a
226/// zero-sized allocation; `usize::MAX` for ZSTs). The allocation thus came from the global
227/// allocator with exactly the layout `Vec`'s safety contract requires for `capacity`, so `Vec`
228/// frees it correctly on drop.
229///
230/// This model is used by the compiler to generate nondeterministic `Vec<T>` arguments for
231/// automatic harnesses (`kani autoharness`) when the element type qualifies; verification
232/// results hold for ALL lengths. Optional: requires `alloc`.
233#[kanitool::fn_marker = "AnyVecUnboundedModel"]
234#[inline(never)]
235#[doc(hidden)]
236pub fn any_vec_unbounded<T>() -> Vec<T> {
237    let len: usize = crate::any();
238    let elem = std::mem::size_of::<T>();
239    if elem == 0 {
240        // For ZSTs, Vec never allocates and uses a dangling pointer; constructing from a
241        // dangling pointer with any len is the documented pattern (and loop-free, which
242        // matters: generation code must not itself be bounded by unwinding).
243        return unsafe {
244            Vec::from_raw_parts(std::ptr::NonNull::dangling().as_ptr(), len, usize::MAX)
245        };
246    }
247    crate::assume(len <= (isize::MAX as usize) / elem);
248    let layout = std::alloc::Layout::array::<T>(len.max(1)).unwrap();
249    let ptr = unsafe { std::alloc::alloc(layout) };
250    crate::assume(!ptr.is_null());
251    slice_validity_assume::<T>(ptr, len);
252    unsafe { Vec::from_raw_parts(ptr as *mut T, len, len.max(1)) }
253}
254
255/// Compiler hook (c.f. `KaniHook::SliceValidityAssume`): assume that every element of the
256/// `len`-element `T`-array at `ptr` has raw bits within `T`'s layout niche. Lowered directly
257/// to a quantified goto assumption; a no-op when `T` has no niche. The default body is
258/// unreachable: calls are always intercepted during code generation.
259#[kanitool::fn_marker = "SliceValidityAssumeHook"]
260#[inline(never)]
261#[doc(hidden)]
262pub fn slice_validity_assume<T>(_ptr: *const u8, _len: usize) {
263    #[cfg(not(kani))]
264    unreachable!("kani::slice_validity_assume is a verification-only hook");
265}
266
267/// Nondeterministic functions for instantiating `Fn`/`FnMut`/`FnOnce`-bounded type
268/// parameters of automatic harnesses: the parameter is instantiated with the *function
269/// item type* of the matching-arity model below (function items implement all three `Fn`
270/// traits and are zero-sized, so generating the value is trivial). Each call returns a
271/// fresh nondeterministic value, which over-approximates the behavior of every real
272/// closure with that signature (including stateful `FnMut` closures); verifying the
273/// harness against this instantiation therefore covers the function-under-test's own code
274/// for any closure behavior.
275///
276/// These models are *optional* (c.f. `KaniModel::is_optional`).
277#[kanitool::fn_marker = "NondetFn0Model"]
278#[inline(never)]
279#[doc(hidden)]
280pub fn nondet_fn0<R: Arbitrary>() -> R {
281    crate::any()
282}
283
284#[kanitool::fn_marker = "NondetFn1Model"]
285#[inline(never)]
286#[doc(hidden)]
287pub fn nondet_fn1<A, R: Arbitrary>(_a: A) -> R {
288    crate::any()
289}
290
291#[kanitool::fn_marker = "NondetFn1RefModel"]
292#[inline(never)]
293#[doc(hidden)]
294/// Region-polymorphic: the fn item's late-bound lifetime lets it satisfy HRTB bounds
295/// like `for<'a> Fn(&'a T) -> R` that the early-bound by-value models cannot.
296pub fn nondet_fn1_ref<T, R: Arbitrary>(_a: &T) -> R {
297    crate::any()
298}
299
300#[kanitool::fn_marker = "NondetFn2RefRefModel"]
301#[inline(never)]
302#[doc(hidden)]
303pub fn nondet_fn2_ref_ref<A, B, R: Arbitrary>(_a: &A, _b: &B) -> R {
304    crate::any()
305}
306
307#[kanitool::fn_marker = "NondetFn2RefValModel"]
308#[inline(never)]
309#[doc(hidden)]
310pub fn nondet_fn2_ref_val<A, B, R: Arbitrary>(_a: &A, _b: B) -> R {
311    crate::any()
312}
313
314#[kanitool::fn_marker = "NondetFn2ValRefModel"]
315#[inline(never)]
316#[doc(hidden)]
317pub fn nondet_fn2_val_ref<A, B, R: Arbitrary>(_a: A, _b: &B) -> R {
318    crate::any()
319}
320
321#[kanitool::fn_marker = "NondetFn2Model"]
322#[inline(never)]
323#[doc(hidden)]
324pub fn nondet_fn2<A, B, R: Arbitrary>(_a: A, _b: B) -> R {
325    crate::any()
326}
327
328#[kanitool::fn_marker = "NondetFn3Model"]
329#[inline(never)]
330#[doc(hidden)]
331pub fn nondet_fn3<A, B, C, R: Arbitrary>(_a: A, _b: B, _c: C) -> R {
332    crate::any()
333}