Skip to content

Improve error message for deref field on native ptr #11004

Closed
@pnkfelix

Description

@pnkfelix

On the ~T and &T pointer types, we support auto-deref as necessary, desugaring expressions like a.f to (*a).f, (**a).f, (***a).f, etc.

We do not perform such auto-deref on the native unsafe *T.

That's okay with me; if you are writing unsafe code, it makes some sense that you should have to think more carefully about each level of deference you are performing.

But I think we could do better on the error message you get when you write code that is expecting that sort of auto-deref:

struct A { x: int, y: f64 }

#[cfg(not(works))]
unsafe fn access(n:*A) -> (int, f64) {
    let x : int = n.x;
    let y : f64 = n.y;
    (x, y)
}

#[cfg(works)]
unsafe fn access(n:*A) -> (int, f64) {
    let x : int = (*n).x;
    let y : f64 = (*n).y;
    (x, y)
}

fn main() {
    use std::cast;
    let a :  A = A { x: 3, y: 3.14 };
    let p : &A = &a;
    let (x,y) = unsafe {
        let n : *A = cast::transmute(p);
        access(n)
    };
    println!("x: {}, y: {}", x, y);
}

rustc interaction:

% rustc /tmp/a.rs
/tmp/a.rs:5:18: 5:21 error: attempted access of field `x` on type `*A`, 
                     but no field with that name was found
/tmp/a.rs:5     let x : int = n.x;
                              ^~~
/tmp/a.rs:6:18: 6:21 error: attempted access of field `y` on type `*A`, 
                     but no field with that name was found
/tmp/a.rs:6     let y : f64 = n.y;
                              ^~~
error: aborting due to 2 previous errors
task 'rustc' failed at 'explicit failure', 
  /Users/fklock/Dev/Mozilla/rust.git/src/libsyntax/diagnostic.rs:102
task '<main>' failed at 'explicit failure', 
  /Users/fklock/Dev/Mozilla/rust.git/src/librustc/lib.rs:391

(I'm just thinking something along the lines of an extra sentence that says "note: *A is a native pointer; perhaps you need to deref with (*expr).field)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions