Skip to content

Commit cf551db

Browse files
committed
improve diagnostic for raw pointer field access with ->
1 parent afa859f commit cf551db

File tree

2 files changed

+19
-16
lines changed

2 files changed

+19
-16
lines changed

compiler/rustc_hir_typeck/src/expr.rs

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -3278,21 +3278,24 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
32783278
}
32793279

32803280
fn suggest_first_deref_field(&self, err: &mut Diag<'_>, base: &hir::Expr<'_>, field: Ident) {
3281-
err.span_label(field.span, "unknown field");
3282-
let val = if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
3283-
&& base.len() < 20
3284-
{
3285-
format!("`{base}`")
3286-
} else {
3287-
"the value".to_string()
3288-
};
3289-
err.multipart_suggestion(
3290-
format!("{val} is a raw pointer; try dereferencing it"),
3291-
vec![
3292-
(base.span.shrink_to_lo(), "(*".to_string()),
3293-
(base.span.shrink_to_hi(), ")".to_string()),
3294-
],
3295-
Applicability::MaybeIncorrect,
3281+
let full_span = base.span.to(field.span);
3282+
3283+
let base_snippet = self
3284+
.tcx
3285+
.sess
3286+
.source_map()
3287+
.span_to_snippet(base.span)
3288+
.unwrap_or_else(|_| "ptr".to_string());
3289+
3290+
let replacement = format!("(*{}).{}", base_snippet, field.name);
3291+
3292+
err.span_label(full_span, "unknown field access via raw pointer");
3293+
3294+
err.span_suggestion_verbose(
3295+
full_span,
3296+
"`->` is not valid in Rust; use `.` on a dereferenced raw pointer instead",
3297+
replacement,
3298+
Applicability::MachineApplicable,
32963299
);
32973300
}
32983301

compiler/rustc_parse/messages.ftl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ parse_expected_trait_in_trait_impl_found_type = expected a trait, found type
248248
249249
parse_expr_rarrow_call = `->` used for field access or method call
250250
.suggestion = try using `.` instead
251-
.help = the `.` operator will dereference the value if needed
251+
.help = the `.` operator will dereference the value if needed (if value is raw pointer you have to derefernce it by yourself)
252252
253253
parse_extern_crate_name_with_dashes = crate name using dashes are not valid in `extern crate` statements
254254
.label = dash-separated idents are not valid

0 commit comments

Comments
 (0)