Skip to content

Commit 05debb0

Browse files
authored
Rollup merge of #140787 - xizheyin:issue-140491, r=nnethercote
Note expr being cast when encounter NonScalar cast error Fixes #140491 I added note for `expr` so that it doesn't treat `&x as T` as `&(x as T)` but `(&x) as T`. But I'm not sure if I want to add note for all NonScalar, maybe for specific `expr_ty`? r? compiler
2 parents 738c08b + 17352e6 commit 05debb0

File tree

4 files changed

+30
-0
lines changed

4 files changed

+30
-0
lines changed

compiler/rustc_hir_typeck/src/cast.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -408,6 +408,16 @@ impl<'a, 'tcx> CastCheck<'tcx> {
408408
self.expr_ty,
409409
fcx.ty_to_string(self.cast_ty)
410410
);
411+
412+
if let Ok(snippet) = fcx.tcx.sess.source_map().span_to_snippet(self.expr_span)
413+
&& matches!(self.expr.kind, ExprKind::AddrOf(..))
414+
{
415+
err.note(format!(
416+
"casting reference expression `{}` because `&` binds tighter than `as`",
417+
snippet
418+
));
419+
}
420+
411421
let mut sugg = None;
412422
let mut sugg_mutref = false;
413423
if let ty::Ref(reg, cast_ty, mutbl) = *self.cast_ty.kind() {
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
fn my_fn(event: &Event<'_>) {}
2+
3+
struct Event<'a>(&'a ());
4+
5+
fn main() {
6+
const ptr: &fn(&Event<'_>) = &my_fn as _; //~ ERROR non-primitive cast: `&for<'a, 'b> fn(&'a Event<'b>) {my_fn}` as `&for<'a, 'b> fn(&'a Event<'b>)` [E0605]
7+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error[E0605]: non-primitive cast: `&for<'a, 'b> fn(&'a Event<'b>) {my_fn}` as `&for<'a, 'b> fn(&'a Event<'b>)`
2+
--> $DIR/func-pointer-issue-140491.rs:6:34
3+
|
4+
LL | ..._>) = &my_fn as _;
5+
| ^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
6+
|
7+
= note: casting reference expression `&my_fn` because `&` binds tighter than `as`
8+
9+
error: aborting due to 1 previous error
10+
11+
For more information about this error, try `rustc --explain E0605`.

tests/ui/coercion/issue-73886.stderr

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ error[E0605]: non-primitive cast: `&&[i32; 1]` as `&[_]`
33
|
44
LL | let _ = &&[0] as &[_];
55
| ^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
6+
|
7+
= note: casting reference expression `&&[0]` because `&` binds tighter than `as`
68

79
error[E0605]: non-primitive cast: `u32` as `Option<_>`
810
--> $DIR/issue-73886.rs:4:13

0 commit comments

Comments
 (0)