Skip to content

Suboptimal diagnostic with a missing fn const #89007

Open
@leonardo-m

Description

@leonardo-m

(This is a spinoff of Issue 88424).
Here the signature of new_unchecked lacks a "const" and the compiler doesn't give me enough help to see/fix the problem:

#![feature(
    const_fn_trait_bound,
    const_panic,
    const_trait_impl,
    generic_const_exprs,
)]

#![allow(incomplete_features)]

pub trait ToFromUsize {
    fn to_usize(self) -> usize;
    fn from_usize(x: usize) -> Self;
    const MAX: Self;
}
impl const ToFromUsize for usize {
    fn to_usize(self) -> usize { self }
    fn from_usize(x: usize) -> Self { x }
    const MAX: Self = Self::MAX;
}

pub const fn assert_nonzero(n: usize) -> usize {
    assert!(n > 0);
    n
}

pub const fn is_contained(n: usize, m: usize) -> usize {
    assert!(n <= m);
    n
}

pub const fn is_representable<Ti: ~const ToFromUsize>(n: usize) -> usize {
    assert!(n <= Ti::MAX.to_usize());
    n
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Default)]
#[repr(transparent)]
pub struct Foo<Ti: ToFromUsize + Copy, const N: usize>(Ti)
where [(); assert_nonzero(N)]:,
      [(); is_representable::<Ti>(N - 1)]:;

impl<Ti: ToFromUsize + Copy, const N: usize> Foo<Ti, N>
where [(); assert_nonzero(N)]:,
      [(); is_representable::<Ti>(N - 1)]: {

    pub unsafe fn new_unchecked(i: Ti) -> Self where Ti: ~const ToFromUsize {
        Self(i)
    }
}

fn main() {}

It gives:

error: `~const` is not allowed here
  --> ...\test2.rs:46:58
   |
46 |     pub unsafe fn new_unchecked(i: Ti) -> Self where Ti: ~const ToFromUsize {
   |                                                          ^^^^^^^^^^^^^^^^^^
   |
   = note: only allowed on bounds on traits' associated types and functions, const fns, const impls and its associated functions

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions