Skip to content

Loop contracts: for loops over iterators without a KaniIntoIter impl (e.g. char::DecodeUtf16) cannot carry a contract #4907

Description

@Talha-Dmr

Requested feature: allow #[kani::loop_invariant] on a for loop over any Iterator, not only over the types that implement kani::KaniIntoIter (at this commit: arrays, &[T], &mut [T] and slice::Iter<T> with T: Copy, Range, StepBy, Chain, Zip, Map, Enumerate, Take, Rev). For example, there could be a fallback that lowers for x in it to let mut it = it.into_iter(); while let Some(x) = it.next(), keeping the invariant on the loop head.

Use case: verifying std code for unbounded input length. The only loop of alloc::string::String::from_utf16 is

for c in char::decode_utf16(v.iter().cloned()) { ... }

This loop is written directly in the function under verification, so it can be annotated. But DecodeUtf16<Cloned<slice::Iter<'_, u16>>> has no KaniIntoIter impl, so the contract is rejected at compile time. Rewriting the production loop only for verification is not acceptable in model-checking/verify-rust-std.

Link to relevant documentation: https://model-checking.github.io/kani/reference/experimental/loop-contracts.html (Limitations, item 1).

Test case (Kani 0.67.0 built from source at 152c6a8, CBMC 6.10.0, Arch Linux x86_64):

#![feature(stmt_expr_attributes)]
#![feature(proc_macro_hygiene)]

pub fn from_utf16_copy(v: &[u16]) -> Option<String> {
    let mut ret = String::with_capacity(v.len());
    #[kani::loop_invariant(kani::index <= v.len())]
    for c in char::decode_utf16(v.iter().cloned()) {
        let Ok(c) = c else { return None; };
        ret.push(c);
    }
    Some(ret)
}

#[kani::proof]
fn check_from_utf16() {
    let a: [u16; 4] = kani::any();
    let n: usize = kani::any_where(|n: &usize| *n <= 4);
    let _ = from_utf16_copy(&a[..n]);
}
kani for_decode_utf16.rs -Z loop-contracts
error[E0277]: the trait bound `std::char::DecodeUtf16<std::iter::Cloned<std::slice::Iter<'_, u16>>>: kani::KaniIntoIter` is not satisfied
 --> for_decode_utf16.rs:8:14
  = help: the following other types implement trait `kani::KaniIntoIter`:

Note: kani::index is a natural thing to use here, but a length-based fallback would not be available for iterators like DecodeUtf16 whose item count is not known in advance. A while let-style lowering, where the invariant refers to the iterator state, would still be useful.

Doc note: at this commit the loop-contracts page lists while let loops as unsupported. The loop_invariant macro in library/kani_macros/src/sysroot/loop_contracts/mod.rs, however, rewrites while let into loop + match. If that is intended to be supported, the Limitations list could be updated.

Activity

  1. added
    Z-Contracts
    on Sep 29, 2026
  2. added this to the Contracts milestone on Sep 29, 2026
  3. added
    [C] Feature / Enhancement
    [E] Unsupported Construct
    on Nov 6, 2026
  4. self-assigned this
    on Nov 6, 2026
  5. feliperodri commented on Nov 10, 2026

    @feliperodri
    Member

    Three more common iterator types without KaniIntoIter, all hit in real crates (rand_core 0.10.1 utils::read_words, bitflags 2.13.2 parser::to_writer/from_str and the iter module):

    #![feature(stmt_expr_attributes, proc_macro_hygiene)]
    
    #[kani::proof]
    fn slice_iter_mut() {
        let mut a: [u8; 4] = kani::any();
        #[kani::loop_invariant(true)]
        for x in a.iter_mut() { *x = 0; }
    }
    // error[E0277]: the trait bound `std::slice::IterMut<'_, u8>: kani::KaniIntoIter` is not satisfied
    
    #[kani::proof]
    fn by_ref_iter() {
        let a: [u8; 4] = kani::any();
        let mut it = a.iter();
        let mut n = 0u8;
        #[kani::loop_invariant(n <= 4)]
        for _x in it.by_ref() { n += 1; }
    }
    // error[E0277]: the trait bound `&mut std::slice::Iter<'_, u8>: kani::KaniIntoIter` is not satisfied
    
    #[kani::proof]
    fn str_split() {
        let s = "a|b|c";
        let mut n = 0u8;
        #[kani::loop_invariant(n <= 5)]
        for _p in s.split('|') { n += 1; }
    }
    // error[E0277]: the trait bound `std::str::Split<'_, char>: kani::KaniIntoIter` is not satisfied

    (cargo kani -Z loop-contracts.) iter_mut() and &mut I (by_ref, for x in &mut it) are probably the most common cases in library code. The fallback suggested above (while let Some(x) = it.next() with the invariant on the loop head) would cover all three.

    For context: in our runs, agents could not give a loop contract to 5 such loops in two crates, and the next run will let them rewrite the loop as an index-based while loop when that preserves the semantics, which a fallback in Kani would make unnecessary.


    Found while evaluating the Kani agent plugin (#5059) on popular crates (run on Kani built from main at 47689dc, reports 0.68.0, CBMC 6.11.0, nightly-2026-10-23). The text was written with AI assistance; the snippets were run by hand on that build.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Z-Contracts[C] Feature / Enhancement[E] Unsupported Construct

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions