Skip to content

Invalid suggestion for accessing fields on raw pointer in macros #158158

Description

@DanielEScherzer

Code

struct Demo {
    val: u32,
}

macro_rules! as_ptr {
    ($d:expr) => {
        &mut $d as *mut Demo
    };
}

macro_rules! get_value {
    ($d:expr) => {
        as_ptr!($d).val
    }
}

fn main() {
    let d = Demo { val: 123 };
    assert_eq!(123, get_value!(d));
}

Current output

Compiling playground v0.0.1 (/playground)
error[E0609]: no field `val` on type `*mut Demo`
  --> src/main.rs:13:21
   |
13 |         as_ptr!($d).val
   |                     ^^^ unknown field
...
19 |     assert_eq!(123, get_value!(d));
   |                     ------------- in this macro invocation
   |
   = note: this error originates in the macro `get_value` (in Nightly builds, run with -Z macro-backtrace for more info)
help: `$d as *mut Demo` is a raw pointer; try dereferencing it
   |
 7 -         &mut $d as *mut Demo
 7 +         &mut (*).
   |

For more information about this error, try `rustc --explain E0609`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Desired output

Rationale and extra context

At the very least,

 7 -         &mut $d as *mut Demo
 7 +         &mut (*).

is broken, if a well-formed suggestion cannot be provided it should be removed

Other cases

With

struct Demo {
    val: u32,
}

macro_rules! get_value {
    ($d:expr) => {
        $d.val
    }
}

fn main() {
    let d = Demo { val: 123 };
    let d_ptr = &d as *const Demo;
    assert_eq!(123, get_value!(d_ptr));
}

the output is still problematic, but less so since it doesn't have a suggestion to apply:

   Compiling playground v0.0.1 (/playground)
error[E0609]: no field `val` on type `*const Demo`
  --> src/main.rs:7:12
   |
 7 |         $d.val
   |            ^^^ unknown field
...
14 |     assert_eq!(123, get_value!(d_ptr));
   |                     ----------------- in this macro invocation
   |
   = note: this error originates in the macro `get_value` (in Nightly builds, run with -Z macro-backtrace for more info)
help: `d_ptr` is a raw pointer; try dereferencing it
   |
 7 ~         $d).val
 8 |     }
...
13 |     let d_ptr = &d as *const Demo;
14 ~     assert_eq!(123, get_value!((*d_ptr));
   |

For more information about this error, try `rustc --explain E0609`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Rust Version

1.96.0

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    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

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions