Skip to content

"Calls in const functions are limited to..." error should specifically say what part isn't const #92380

Closed
@clarfonthey

Description

@clarfonthey

Given the following code: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6d59a86fd2dbb93ed78e8f9108afe083

struct Test;
impl Test {
    fn not_const_fn(self) -> Self {
        self
    }
    
    const fn const_fn(self) -> Self {
        self
    }
    
    const fn i_am_error(self) -> Self {
        self.const_fn().not_const_fn()
    }
    
    const fn i_am_also_error(self) -> Self {
        self.not_const_fn().const_fn()
    }
}

The current output is:

error[E0015]: calls in constant functions are limited to constant functions, tuple structs and tuple variants
  --> src/lib.rs:13:9
   |
13 |         self.const_fn().not_const_fn()
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error[E0015]: calls in constant functions are limited to constant functions, tuple structs and tuple variants
  --> src/lib.rs:17:9
   |
17 |         self.not_const_fn().const_fn()
   |         ^^^^^^^^^^^^^^^^^^^

Although the carets technically make it clear which function is at fault since you can check what the outermost call is, this really kind of sucks. The actual source of the error can further be obscured if the functions are called through traits or macros, since it's harder to determine the actual non-const function that caused the error.

A few things that I think would help, in no particular order:

  1. If it's a function the user wrote (in the same crate), we should suggest to add a const to the definition of the function. If this is too hard initially, we can simply tell them to do this without explicitly pointing out where the definition is. No matter what, it wouldn't be machine-applicable, since it'd require quite a bit of work to follow the function and its dependencies to make sure they all can be marked as const.
  2. If it's a function that the user did not write (outside the crate), we should simply clarify the full path.
  3. If it's a trait method, we should mimic the same behaviour but suggest changing the impl to impl const, instead of just annotating the function. If the user doesn't have the necessary features enabled, we should also point out what features the user would have to enable.

Metadata

Metadata

Assignees

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