Skip to content

Diagnostics for ambiguous number types could be better #40985

Closed
@Rufflewind

Description

@Rufflewind

Ambiguous integer or float type variable can lead to some rather confusing error messages. Consider:

fn main() {
    println!("{:?}", 2.0.powi(2));
    println!("{:?}", 2.0 as u32);
}

Method calls on an ambiguous number type

The first error says that {float} doesn't have a method called powi, but taken naively that's not true: both f32 and f64 have methods powi. The actual problem is that the type inference doesn't know which floating point type the user wants.

The help is even more confusing, because it suggests the user to use a deprecated trait that's not even documented anymore.

rustc 1.18.0-nightly (5c94997b6 2017-03-30)
error: no method named `powi` found for type `{float}` in the current scope
 --> <anon>:2:26
  |
2 |     println!("{:?}", 2.0.powi(2));
  |                          ^^^^
  |
  = help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
  = help: candidate #1: `use core::num::Float;`

Casting an ambiguous number type

Likewise, when casting one could again run into the same problem. Here, it complains that the cast is "non-scalar" but naively {float} sounds like a perfectly scalar type! In reality the problem is that casting requires the source type to be non-ambiguous.

error: non-scalar cast: `{float}` as `u32`
 --> <anon>:3:22
  |
3 |     println!("{:?}", 2.0 as u32);
  |                      ^^^^^^^^^^

error: aborting due to 2 previous errors

Suggestion

Tentative PR: master...Rufflewind:ambiguous-number-type

Tweak the error messages a bit when the type is {float} or {integer}. Also, perhaps suggestions for deprecated traits could be suppressed?

rustc 1.18.0-nightly (5c94997b6 2017-03-30)
error: no method named `powi` found for the ambiguous type `{float}` in the current scope
 --> <anon>:2:26
  |
2 |     println!("{:?}", 2.0.powi(2));
  |                          ^^^^
  |
  = help: if you meant to call the `powi` method of, say, `f64`, consider adding some type annotations to clarify that `{float}` should be `f64`

error: casting from an ambiguous type: `{float}` as `u32`
 --> <anon>:3:22
  |
3 |     println!("{:?}", 2.0 as u32);
  |                      ^^^^^^^^^^

error: aborting due to 2 previous errors

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.WG-diagnosticsWorking group: Diagnostics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions