Skip to content

Show values that lead to an arithmetic overflow when computing constants #71134

Closed
@shepmaster

Description

@shepmaster

In Rust 1.42, this code correctly fails due to a misuse of bitwise-XOR as exponentiation:

const N: usize = 10;
const N_CELLS: usize = (N ^ 2) - 50;
error: any use of this value will cause an error
 --> src/lib.rs:2:24
  |
2 | const N_CELLS: usize = (N ^ 2) - 50;
  | -----------------------^^^^^^^^^^^^-
  |                        |
  |                        attempt to subtract with overflow
  |
  = note: `#[deny(const_err)]` on by default

However, the error message could be enhanced to show the values that lead to the overflow. One rough idea:

2 | const N_CELLS: usize = (N ^ 2) - 50;
  |                        ^^^^^^^   ^^
  |                        |         |
  |                        evaluated to 8
  |                                  |
  |                                  evaluated to 50

This originated from a Stack Overflow question: How can I guarantee that overflow will not occur in const variables?

/cc @oli-obk

Metadata

Metadata

Assignees

Labels

A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-papercutDiagnostics: An error or lint that needs small tweaks.T-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