Repository: rust
Issue: ICE: demand: index out of bounds
Labels: I-ICE,T-compiler,C-bug,S-has-mcve,T-types,S-has-bisection

<!--
[31mICE[0m: Rustc ./a.rs '' 'thread 'rustc' panicked at compiler/rustc_hir_typeck/src/demand.rs:409:53: 'index out of bounds: the len is 1 but the index is 1'', 'thread 'rustc' panicked at compiler/rustc_hir_typeck/src/demand.rs:409:53: 'index out of bounds: the len is 1 but the index is 1''
File: /tmp/im/2/a.rs
-->

snippet:
````rust
pub trait Future {}

pub trait Action {}

fn retry<A: Action>(action: A) -> impl Future {}

struct Core<T: Future> {}

impl<T: Future> Core<F> {
    pub fn spawn(self) {}
}

fn main() {
    let mut core = Core {};
    for i in &[1, 2, 3, 4, 5] {
        core.spawn(retry(action));
    }
}

````


<details><summary><strong>original code</strong></summary>
<p>

original:
````rust
pub trait Future {
    fn run(self);
}

impl<F> Future for F where Item: FnOnce() {
    fn retry<A: Action>(action: A) -> impl Future<Item = (), Error = ()> {
    action.run()
}
}

pub trait Action {
    type Output: Future;
    fn run(self) -> Self::Output;
}

impl<T: Action, F: FnOnce() -> T> Action for F {
    type Output = T;
    fn run(self) -> Self::Output {
        self()
    }
}

fn retry<A: Action>(action: A) -> impl Future {
    action.handle()
}

struct Core<T: Future> {
    vec: Vec<F>,
}

impl<T: Future> Core<F> {
    pub fn spawn(self) where F: Future + 'static {
        core.remove.push(f);
    }

    pub fn run(self) {
        for f in self.vec.into_iter() {
            f.run()
        };
    }
}

/*
The `nested` closure avoids the check of its lifetime here, if:
- the `nasted` closure is nested into the `action` closure, and
- the `action` closure is passed into the `retry` function, and
- the `retry` function take a generic by the `Action` trait argument, and
- the `Action` trait is implemented for an `Fn*` trait.

As a result, we get arbitrary values in variables and at best SIGSEGV.
*/
fn main() {
    let mut core = Core { vec: Vec::new() };
    for i in &[1, 2, 3, 4, 5] {
        println!("Core::run", i);
        let f = || { // The `lazy` closure
                f()
            };
        let action = move || {
            || f() // The `nested` closure
        };
        core.spawn(retry(action));
    }
    core.run();
}

````
</p>
</details>

Version information
````
rustc 1.86.0-nightly (35c290817 2025-01-14)
binary: rustc
commit-hash: 35c2908177a17ca4e0acbc9013e42ee525ba155c
commit-date: 2025-01-14
host: x86_64-unknown-linux-gnu
release: 1.86.0-nightly
LLVM version: 19.1.6

````

Possibly related line of code:
https://github.com/rust-lang/rust/blob/35c2908177a17ca4e0acbc9013e42ee525ba155c/compiler/rustc_hir_typeck/src/demand.rs#L403-L415

Command:
`/home/matthias/.rustup/toolchains/master/bin/rustc `

<details><summary><strong>Program output</strong></summary>
<p>

```
error[E0412]: cannot find type `F` in this scope
  --> /tmp/icemaker_global_tempdir.hbPlrcOQEpxc/rustc_testrunner_tmpdir_reporting.YPq7bZYDb2EU/mvce.rs:9:22
   |
9  | impl<T: Future> Core<F> {
   |                      ^
   |
  ::: /home/matthias/.rustup/toolchains/master/lib/rustlib/src/rust/library/core/src/ops/function.rs:76:1
   |
76 | pub trait Fn<Args: Tuple>: FnMut<Args> {
   | -------------------------------------- similarly named trait `Fn` defined here
   |
help: a trait with a similar name exists
   |
9  | impl<T: Future> Core<Fn> {
   |                      ~~
help: you might be missing a type parameter
   |
9  | impl<T: Future, F> Core<F> {
   |               +++

error[E0425]: cannot find value `action` in this scope
  --> /tmp/icemaker_global_tempdir.hbPlrcOQEpxc/rustc_testrunner_tmpdir_reporting.YPq7bZYDb2EU/mvce.rs:16:26
   |
16 |         core.spawn(retry(action));
   |                          ^^^^^^ not found in this scope

error[E0392]: type parameter `T` is never used
 --> /tmp/icemaker_global_tempdir.hbPlrcOQEpxc/rustc_testrunner_tmpdir_reporting.YPq7bZYDb2EU/mvce.rs:7:13
  |
7 | struct Core<T: Future> {}
  |             ^ unused type parameter
  |
  = help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData`

error[E0277]: the trait bound `(): Future` is not satisfied
 --> /tmp/icemaker_global_tempdir.hbPlrcOQEpxc/rustc_testrunner_tmpdir_reporting.YPq7bZYDb2EU/mvce.rs:5:35
  |
5 | fn retry<A: Action>(action: A) -> impl Future {}
  |                                   ^^^^^^^^^^^ the trait `Future` is not implemented for `()`
  |
help: this trait has no implementations, consider adding one
 --> /tmp/icemaker_global_tempdir.hbPlrcOQEpxc/rustc_testrunner_tmpdir_reporting.YPq7bZYDb2EU/mvce.rs:1:1
  |
1 | pub trait Future {}
  | ^^^^^^^^^^^^^^^^


thread 'rustc' panicked at compiler/rustc_hir_typeck/src/demand.rs:409:53:
index out of bounds: the len is 1 but the index is 1
stack backtrace:
   0:     0x76293fefec2a - <std::sys::backtrace::BacktraceLock::print::DisplayBacktrace as core::fmt::Display>::fmt::h343181add7067502
   1:     0x762940612da6 - core::fmt::write::h4a7aadae0a1bc1aa
   2:     0x76294159c3d1 - std::io::Write::write_fmt::h1778835c3c67b7e7
   3:     0x76293fefea82 - std::sys::backtrace::BacktraceLock::print::h6b4eb1026a458107
   4:     0x76293ff01027 - std::panicking::default_hook::{{closure}}::h794153a458ec0a99
   5:     0x76293ff00e10 - std::panicking::default_hook::haa2577842079db42
   6:     0x76293f0657e8 - std[f87fc13b1c9b189d]::panicking::update_hook::<alloc[8c45d6cf9cfd903f]::boxed::Box<rustc_driver_impl[b5cea8d0259ab78a]::install_ice_hook::{closure#1}>>::{closure#0}
   7:     0x76293ff01873 - std::panicking::rust_panic_with_hook::h3d89a5b3bc51855c
   8:     0x76293ff0156a - std::panicking::begin_panic_handler::{{closure}}::h6218397a7f283626
   9:     0x76293feff0f9 - std::sys::backtrace::__rust_end_short_backtrace::h1c3cb871f8987430
  10:     0x76293ff0122d - rust_begin_unwind
  11:     0x76293cba68d0 - core::panicking::panic_fmt::h9f9d58009f0431b1
  12:     0x76293e6e03c9 - core::panicking::panic_bounds_check::h28c35d67f308dc8e
  13:     0x76293f2e3303 - <core[60f4c6f00ff91c40]::slice::iter::Iter<&rustc_hir[d42cc4700ac42360]::hir::Expr> as core[60f4c6f00ff91c40]::iter::traits::double_ended::DoubleEndedIterator>::try_rfold::<(), core[60f4c6f00ff91c40]::iter::traits::iterator::Iterator::find_map::check<&&rustc_hir[d42cc4700ac42360]::hir::Expr, rustc_middle[7d18ff6d534e138c]::ty::Ty, <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::note_source_of_type_mismatch_constraint::{closure#3}>::{closure#0}, core[60f4c6f00ff91c40]::ops::control_flow::ControlFlow<rustc_middle[7d18ff6d534e138c]::ty::Ty>>
  14:     0x76293f35d928 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::note_source_of_type_mismatch_constraint
  15:     0x76293f386665 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::report_arg_errors
  16:     0x7629407608d0 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_argument_types
  17:     0x76294136e4d6 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_with_expectation_and_args
  18:     0x762941357c0f - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_block
  19:     0x76294135f4f3 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_with_expectation_and_args
  20:     0x76294135305c - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_match::{closure#0}
  21:     0x7629413609dd - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_with_expectation_and_args
  22:     0x7629413591f1 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_block
  23:     0x7629413641a8 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_with_expectation_and_args
  24:     0x76294135305c - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_match::{closure#0}
  25:     0x7629413609dd - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_with_expectation_and_args
  26:     0x762941361773 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_with_expectation_and_args
  27:     0x762941357d01 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_block
  28:     0x76294135f4f3 - <rustc_hir_typeck[7437378b43a6ded6]::fn_ctxt::FnCtxt>::check_expr_with_expectation_and_args
  29:     0x762940c5c4c0 - rustc_hir_typeck[7437378b43a6ded6]::check::check_fn
  30:     0x762940c6617d - rustc_hir_typeck[7437378b43a6ded6]::typeck_with_fallback::{closure#0}
  31:     0x762940c6418c - rustc_query_impl[cb4674ae863c9cf]::plumbing::__rust_begin_short_backtrace::<rustc_query_impl[cb4674ae863c9cf]::query_impl::typeck::dynamic_query::{closure#2}::{closure#0}, rustc_middle[7d18ff6d534e138c]::query::erase::Erased<[u8; 8usize]>>
  32:     0x762940c4ee8e - rustc_query_system[b56cf2761e1d5f32]::query::plumbing::try_execute_query::<rustc_query_impl[cb4674ae863c9cf]::DynamicConfig<rustc_data_structures[9413300d1cf0cd07]::vec_cache::VecCache<rustc_span[32ed8b15aa28102c]::def_id::LocalDefId, rustc_middle[7d18ff6d534e138c]::query::erase::Erased<[u8; 8usize]>, rustc_query_system[b56cf2761e1d5f32]::dep_graph::graph::DepNodeIndex>, false, false, false>, rustc_query_impl[cb4674ae863c9cf]::plumbing::QueryCtxt, false>
  33:     0x762940c4e063 - rustc_query_impl[cb4674ae863c9cf]::query_impl::typeck::get_query_non_incr::__rust_end_short_backtrace
  34:     0x762940c4dd1d - <rustc_middle[7d18ff6d534e138c]::hir::map::Map>::par_body_owners::<rustc_hir_analysis[c09c58fe15d469e5]::check_crate::{closure#4}>::{closure#0}
  35:     0x762940c4bdd1 - rustc_hir_analysis[c09c58fe15d469e5]::check_crate
  36:     0x7629408f8d68 - rustc_interface[9cdea11426ea32ce]::passes::run_required_analyses
  37:     0x7629415a025e - rustc_interface[9cdea11426ea32ce]::passes::analysis
  38:     0x7629415a022f - rustc_query_impl[cb4674ae863c9cf]::plumbing::__rust_begin_short_backtrace::<rustc_query_impl[cb4674ae863c9cf]::query_impl::analysis::dynamic_query::{closure#2}::{closure#0}, rustc_middle[7d18ff6d534e138c]::query::erase::Erased<[u8; 0usize]>>
  39:     0x7629415c6215 - rustc_query_system[b56cf2761e1d5f32]::query::plumbing::try_execute_query::<rustc_query_impl[cb4674ae863c9cf]::DynamicConfig<rustc_query_system[b56cf2761e1d5f32]::query::caches::SingleCache<rustc_middle[7d18ff6d534e138c]::query::erase::Erased<[u8; 0usize]>>, false, false, false>, rustc_query_impl[cb4674ae863c9cf]::plumbing::QueryCtxt, false>
  40:     0x7629415c5f4e - rustc_query_impl[cb4674ae863c9cf]::query_impl::analysis::get_query_non_incr::__rust_end_short_backtrace
  41:     0x7629416433de - rustc_interface[9cdea11426ea32ce]::passes::create_and_enter_global_ctxt::<core[60f4c6f00ff91c40]::option::Option<rustc_interface[9cdea11426ea32ce]::queries::Linker>, rustc_driver_impl[b5cea8d0259ab78a]::run_compiler::{closure#0}::{closure#2}>::{closure#2}::{closure#0}
  42:     0x762941635e16 - rustc_interface[9cdea11426ea32ce]::interface::run_compiler::<(), rustc_driver_impl[b5cea8d0259ab78a]::run_compiler::{closure#0}>::{closure#1}
  43:     0x7629414b7647 - std[f87fc13b1c9b189d]::sys::backtrace::__rust_begin_short_backtrace::<rustc_interface[9cdea11426ea32ce]::util::run_in_thread_with_globals<rustc_interface[9cdea11426ea32ce]::util::run_in_thread_pool_with_globals<rustc_interface[9cdea11426ea32ce]::interface::run_compiler<(), rustc_driver_impl[b5cea8d0259ab78a]::run_compiler::{closure#0}>::{closure#1}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>
  44:     0x7629414b7ae0 - <<std[f87fc13b1c9b189d]::thread::Builder>::spawn_unchecked_<rustc_interface[9cdea11426ea32ce]::util::run_in_thread_with_globals<rustc_interface[9cdea11426ea32ce]::util::run_in_thread_pool_with_globals<rustc_interface[9cdea11426ea32ce]::interface::run_compiler<(), rustc_driver_impl[b5cea8d0259ab78a]::run_compiler::{closure#0}>::{closure#1}, ()>::{closure#0}, ()>::{closure#0}::{closure#0}, ()>::{closure#1} as core[60f4c6f00ff91c40]::ops::function::FnOnce<()>>::call_once::{shim:vtable#0}
  45:     0x7629414b90c1 - std::sys::pal::unix::thread::Thread::new::thread_start::h0b52359edc81c287
  46:     0x76293b8a339d - <unknown>
  47:     0x76293b92849c - <unknown>
  48:                0x0 - <unknown>

error: the compiler unexpectedly panicked. this is a bug.

note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md

note: please make sure that you have updated to the latest nightly

note: rustc 1.86.0-nightly (35c290817 2025-01-14) running on x86_64-unknown-linux-gnu

query stack during panic:
#0 [typeck] type-checking `main`
#1 [analysis] running analysis passes on this crate
end of query stack
error: aborting due to 4 previous errors

Some errors have detailed explanations: E0277, E0392, E0412, E0425.
For more information about an error, try `rustc --explain E0277`.

```

</p>
</details>

<!--
query stack:
#0 [typeck] type-checking `main`
#1 [analysis] running analysis passes on this crate

-->