rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
96.9k stars 12.52k forks source link

closures accept ill-formed inputs #104478

Open aliemjay opened 1 year ago

aliemjay commented 1 year ago

Both of these closures should fail borrowck: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=e9855ecda2f9427454cebce7738e598d

struct MyTy<T: Trait>(T);
trait Trait {}
impl Trait for &'static str {}
fn wf<T>(_: T) {}

fn test() {
    let _: for<'x> fn(MyTy<&'x str>) = |_| {}; // PASS!

    // but it should fail for the same reason this fails:
    let _: for<'x> fn(MyTy<&'x str>) = |x| wf(x); // FAIL
}

I think we should simply do WF-checking of closure input/output types in the closure environment, but doing so would cause accidental breakages due to #104477. So #104477 should be resolved first.

@rustbot label A-NLL NLL-sound C-bug T-types A-borrow-checker

aliemjay commented 9 months ago

This is not exclusive to borrowck - typeck can also ignore the well-formedness of cloure args:

struct Iter<T: Iterator>(T);

fn foo(_: impl Fn(&Iter<u8>)) {}

fn main() {
    foo(|_| {});
}