Enum associated functions can name-clash with variants, but cannot be called.

0733b2b
Opened by Amar Sood at 2023-11-27 11:29:41

Description

It's currently possible to name a function associated to an enum identically to the name of one of its variants.

This function cannot be called (see below), but rather than warning at the point that the function is defined, the compiler only emits an error upon trying to call said function (and in some cases - see the 'Alternate Reproduction' - it doesn't even do that).

https://is.gd/EZQ9mL

#[derive(Debug)]
enum X {
    a
}
impl X {
    fn a() -> X {
        X::a
    }
}
fn main() {
    println!("{:?}", X::a())
}

yields:

rustc 1.15.1 (021bd294c 2017-02-08)
error: `X::a` is being called, but it is not a function
  --> <anon>:13:22
   |
13 |     println!("{:?}", X::a())
   |                      ^^^^^^
   |
   = help: did you mean to write `X::a`?
note: defined here
  --> <anon>:3:5
   |
3  |     a
   |     ^

error: aborting due to previous error

Expected behaviour:

Emit an error at the point (fn a() -> X) that the function is defined.

Alternate reproduction

Even more confusing is the code:

https://is.gd/S15gOw

#[derive(Debug)]
enum X {
    a(),
    b,
}

impl X {
    fn a() -> X {
        X::b
    }
}

fn main() {
    println!("{:?}", X::a())
}

This compiles and runs. Any guesses whether the variant or the function wins? :smile:

  1. There is a way to call the associated function, but I won't tell it to you because it will be removed soon 😄 The plan is indeed to report an error on definition of the associated function in similar way like https://github.com/rust-lang/rust/issues/36889 is reported.

    Vadim Petrochenkov at 2017-02-19 09:24:24

  2. @petrochenkov I don't see an error on the associated function yet; so presumably the "soon" is not yet here. Or did some implementation miss this case?

    Mark Rousskov at 2017-05-23 19:06:03

  3. @Mark-Simulacrum "Soon" is about resolving UFCS paths like <X>::a to variants (and resolving variants as associated items in general), the error on inherent associated items "overlapping" with variants is a separate (and also unimplemented) thing.

    Vadim Petrochenkov at 2017-05-23 21:36:24

  4. Triage: both these examples reproduce in the 2021 edition, tested on rustc 1.59.0 (9d1b2106e 2022-02-23)

    Maayan Hanin at 2022-03-21 12:00:30

  5. Enum variants are still not included into the overlap check for inherent impl items.

    Vadim Petrochenkov at 2022-03-21 14:00:27