Skip to content

Error when autoderef of smart pointer occurs in const fn is unclear #91496

Closed
@SNCPlay42

Description

@SNCPlay42

Given the following code:

use std::ops::Deref;

struct Foo;

impl Foo {
    const fn foo(&self) {}
}

struct SmartPointer(Foo);

impl Deref for SmartPointer {
    type Target = Foo;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

pub const fn bar() {
    Foo.foo(); // fine
    SmartPointer(Foo).foo(); // fails since we can't constly deref
}

The current output is:

error[E0015]: calls in constant functions are limited to constant functions, tuple structs and tuple variants
  --> src/lib.rs:21:5
   |
21 |     SmartPointer(Foo).foo(); // fails since we can't constly deref
   |     ^^^^^^^^^^^^^^^^^^^^^^^

It's unclear from the diagnostic that the problem is not the call of foo itself (which is a const fn) but that SmartPointer would have to be dereferenced.

Ideally the output should look like:

error[E0015]: `SmartPointer` cannot be dereferenced in constant functions
  --> src/lib.rs:21:5
   |
21 |     SmartPointer(Foo).foo(); // fails since we can't constly deref
   |     ^^^^^^^^^^^^^^^^^^^^^^^ dereference occurs due to method call
   |
   = note: operators in constant functions are limited to intrinsic operations

Perhaps more generally, the compiler should avoid referring to non-intrinsic operators as "calls" in const errors, or explain that it means calling the operator method. This is usually less of a problem because an operator appears in the span.

@rustbot label A-const-fn

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)A-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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