Skip to content

const trait checks allow calling non-const methods #88155

Closed

Description

cc https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/const.20impl.20trait.20const.20check

This requires 2 different crates:

// crate-a
#![feature(const_fn_trait_bound)]
#![feature(const_trait_impl)]
#![feature(const_trait_bound_opt_out)]
#![allow(incomplete_features)]

pub trait A {
    fn assoc() -> bool;
}

pub const fn foo<T: ?const A>() -> bool {
    T::assoc()
}

// crate-b
#![feature(const_fn_trait_bound)]
#![feature(const_trait_impl)]
#![feature(const_trait_bound_opt_out)]
#![allow(incomplete_features)]
extern crate a;

struct Foo;

impl a::A for Foo {
    fn assoc() -> bool {
        println!("hey ho");
        true
    }
}

static F: bool =  a::foo::<Foo>();

fn main() {
    println!("{}", F);
}

results in

error[E0080]: could not evaluate static initializer
  --> /home/lcnr/wtf/a/src/lib.rs:11:5
   |
11 |     T::assoc()
   |     ^^^^^^^^^^
   |     |
   |     calling non-const function `<Foo as A>::assoc`
   |     inside `foo::<Foo>` at /home/lcnr/wtf/a/src/lib.rs:11:5
   |
  ::: src/main.rs:15:19
   |
15 | static F: bool =  a::foo::<Foo>();
   |                   --------------- inside `F` at src/main.rs:15:19

relevant code

if !permitted {
// if trait's impls are all const, permit the call.
let mut const_impls = true;
tcx.for_each_relevant_impl(trait_id, substs.type_at(0), |imp| {
if const_impls {
if let hir::Constness::NotConst = tcx.impl_constness(imp) {
const_impls = false;
}
}
});
if const_impls {
permitted = true;
}
}

with #86986 we don't find any impl for PartialEq which might apply here which causes us to incorrectly accept https://github.com/rust-lang/rust/blob/master/src/test/ui/rfc-2632-const-trait-impl/call-generic-method-fail.rs

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

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.F-const_trait_impl`#![feature(const_trait_impl)]`

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions