Skip to content

Commit cf33c38

Browse files
authored
Rollup merge of #159744 - chenyukang:yukang-fix-106138-unary-op-inference, r=jackh726
Allow unary operand types to be inferred later Fixes #106138 Fix the inference issue by allowing `Not` and `Neg` operand types to remain unresolved until obligations and constraints can determine them. closes #26830
2 parents 080cc27 + a97890a commit cf33c38

9 files changed

Lines changed: 332 additions & 22 deletions

‎compiler/rustc_hir_typeck/src/expr.rs‎

Lines changed: 33 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -426,35 +426,46 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
426426
return Ty::new_error(tcx, guar);
427427
}
428428

429-
let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t);
429+
// Resolve what we can for `Not` and `Neg`, but allow later constraints
430+
// to determine an unresolved operand type,
431+
// so we call `deeply_resolve_ignoring_regions_with_obligations` for them.
430432
match unop {
431-
hir::UnOp::Deref => self.lookup_derefing(expr, oprnd, oprnd_t).unwrap_or_else(|| {
432-
let mut err =
433-
self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t });
434-
let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None);
435-
if let Some(sp) =
436-
tcx.sess.psess.complete_stmt_exprs_before_bin_op_lookalike.borrow().get(&sp)
437-
{
438-
err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
439-
}
440-
// The operand may be an uncalled function, in which case it is its return type
441-
// the user meant to dereference. Only suggest the call when that return type is
442-
// itself dereferenceable, mirroring the checks `lookup_derefing` just failed.
443-
self.suggest_fn_call(&mut err, oprnd, oprnd_t, |output| {
444-
output.builtin_deref(true).is_some()
445-
|| self.tcx.lang_items().deref_trait().is_some_and(|deref_trait| {
446-
self.type_implements_trait(deref_trait, [output], self.param_env)
447-
.may_apply()
448-
})
449-
});
450-
Ty::new_error(tcx, err.emit_err())
451-
}),
433+
hir::UnOp::Deref => {
434+
// Dereferencing must distinguish builtin pointers from
435+
// overloaded `Deref`, so it still requires a structurally resolved type.
436+
//
437+
// This is necessary as raw pointers do not implement `Deref`.
438+
let oprnd_t = self.structurally_resolve_type(expr.span, oprnd_t);
439+
self.lookup_derefing(expr, oprnd, oprnd_t).unwrap_or_else(|| {
440+
let mut err =
441+
self.dcx().create_err(CantDereference { span: expr.span, ty: oprnd_t });
442+
let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None);
443+
if let Some(sp) =
444+
tcx.sess.psess.complete_stmt_exprs_before_bin_op_lookalike.borrow().get(&sp)
445+
{
446+
err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
447+
}
448+
// The operand may be an uncalled function, in which case it is its return type
449+
// the user meant to dereference. Only suggest the call when that return type is
450+
// itself dereferenceable, mirroring the checks `lookup_derefing` just failed.
451+
self.suggest_fn_call(&mut err, oprnd, oprnd_t, |output| {
452+
output.builtin_deref(true).is_some()
453+
|| self.tcx.lang_items().deref_trait().is_some_and(|deref_trait| {
454+
self.type_implements_trait(deref_trait, [output], self.param_env)
455+
.may_apply()
456+
})
457+
});
458+
Ty::new_error(tcx, err.emit_err())
459+
})
460+
}
452461
hir::UnOp::Not => {
462+
let oprnd_t = self.deeply_resolve_ignoring_regions_with_obligations(oprnd_t);
453463
let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
454464
// If it's builtin, we can reuse the type, this helps inference.
455465
if oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool { oprnd_t } else { result }
456466
}
457467
hir::UnOp::Neg => {
468+
let oprnd_t = self.deeply_resolve_ignoring_regions_with_obligations(oprnd_t);
458469
let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
459470
// If it's builtin, we can reuse the type, this helps inference.
460471
if oprnd_t.is_numeric() { oprnd_t } else { result }
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
//! Regression test for https://github.com/rust-lang/rust/issues/106138.
2+
//! An unresolved dereference must not treat a raw pointer as an overloaded `Deref`.
3+
4+
fn make<T>() -> T {
5+
loop {}
6+
}
7+
8+
fn main() {
9+
let pointer = make();
10+
//~^ ERROR type annotations needed
11+
let value = unsafe { *pointer };
12+
let _: *const u8 = pointer;
13+
let _: u8 = value;
14+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
error[E0282]: type annotations needed
2+
--> $DIR/unary-deref-late-raw-pointer-inference-issue-106138.rs:9:9
3+
|
4+
LL | let pointer = make();
5+
| ^^^^^^^
6+
LL |
7+
LL | let value = unsafe { *pointer };
8+
| -------- type must be known at this point
9+
|
10+
help: consider giving `pointer` an explicit type
11+
|
12+
LL | let pointer: /* Type */ = make();
13+
| ++++++++++++
14+
15+
error: aborting due to 1 previous error
16+
17+
For more information about this error, try `rustc --explain E0282`.
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//! Regression test for https://github.com/rust-lang/rust/issues/26830.
2+
//! Unary negation should allow later constraints to determine its operand type.
3+
4+
//@ check-pass
5+
6+
fn make<T>() -> T {
7+
loop {}
8+
}
9+
10+
fn constrained_by_value() {
11+
let input = make();
12+
let output = -input;
13+
let _: i32 = input;
14+
let _: i32 = output;
15+
}
16+
17+
fn constrained_by_borrow() {
18+
let input = make();
19+
let output = -input;
20+
let _: &i32 = &input;
21+
let _: i32 = output;
22+
}
23+
24+
fn main() {
25+
constrained_by_value();
26+
constrained_by_borrow();
27+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//! Regression test for https://github.com/rust-lang/rust/issues/106138.
2+
//! From comment https://github.com/rust-lang/rust/pull/107567#discussion_r1093589448
3+
//! Unary operator inference must not assume that the associated output type equals `Self`.
4+
5+
#[derive(Copy, Clone, Default)]
6+
struct A;
7+
8+
struct B;
9+
10+
impl std::ops::Not for A {
11+
type Output = B;
12+
13+
fn not(self) -> B {
14+
B
15+
}
16+
}
17+
18+
#[derive(Copy, Clone)]
19+
struct NoNot;
20+
21+
fn make<T>() -> T {
22+
loop {}
23+
}
24+
25+
fn resolved_without_impl() {
26+
let value = make();
27+
let _ = !value;
28+
//~^ ERROR the trait bound `NoNot: Not` is not satisfied
29+
let _: NoNot = value;
30+
}
31+
32+
fn unconstrained() {
33+
let value = make();
34+
//~^ ERROR type annotations needed
35+
let _ = !value;
36+
}
37+
38+
fn main() {
39+
let x = Default::default();
40+
//~^ ERROR cannot call associated function on trait
41+
let _: A = !x;
42+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
error[E0277]: the trait bound `NoNot: Not` is not satisfied
2+
--> $DIR/unary-op-associated-output-mismatch-issue-106138.rs:27:13
3+
|
4+
LL | let _ = !value;
5+
| ^^^^^^ unsatisfied trait bound
6+
|
7+
help: the trait `Not` is not implemented for `NoNot`
8+
--> $DIR/unary-op-associated-output-mismatch-issue-106138.rs:19:1
9+
|
10+
LL | struct NoNot;
11+
| ^^^^^^^^^^^^
12+
13+
error[E0284]: type annotations needed
14+
--> $DIR/unary-op-associated-output-mismatch-issue-106138.rs:33:9
15+
|
16+
LL | let value = make();
17+
| ^^^^^
18+
LL |
19+
LL | let _ = !value;
20+
| ------ type must be known at this point
21+
|
22+
= note: cannot satisfy `<_ as Not>::Output == _`
23+
= note: the type must also implement `Not`
24+
help: consider giving `value` an explicit type
25+
|
26+
LL | let value: /* Type */ = make();
27+
| ++++++++++++
28+
29+
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
30+
--> $DIR/unary-op-associated-output-mismatch-issue-106138.rs:39:13
31+
|
32+
LL | let x = Default::default();
33+
| ^^^^^^^^^^^^^^^^^^ cannot call associated function of trait
34+
|
35+
help: use a fully-qualified path to a specific available implementation
36+
|
37+
LL | let x = </* self type */ as Default>::default();
38+
| +++++++++++++++++++ +
39+
40+
error: aborting due to 3 previous errors
41+
42+
Some errors have detailed explanations: E0277, E0284, E0790.
43+
For more information about an error, try `rustc --explain E0277`.
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
//! Regression test for https://github.com/rust-lang/rust/issues/106138.
2+
//! Unary operators should allow their operand types to be inferred by later constraints.
3+
4+
//@ check-pass
5+
6+
use std::ops::Not;
7+
8+
// Indexing is a place projection, so `a[i]` autoderefs `a` and yields a `bool`.
9+
// `!` is applied to that value: as a value operator it does not autoderef its
10+
// operand itself, unlike the place projection `a[i]`.
11+
fn not_index(x: &Vec<bool>) {
12+
let closure = |i, a: &Vec<bool>| !a[i];
13+
let _ = closure(0, x);
14+
}
15+
16+
// Likewise, the `-` is applied to the `i32` produced by `a[i]`.
17+
fn neg_index(x: &Vec<i32>) {
18+
let closure = |i, a: &Vec<i32>| -a[i];
19+
let _ = closure(0, x);
20+
}
21+
22+
// Since the unary operators do not autoderef, these use `impl Not for &u32` and
23+
// `impl Neg for &i32` rather than dereferencing to `u32`/`i32` first.
24+
fn not_reference(x: &u32) -> u32 {
25+
!x
26+
}
27+
28+
fn neg_reference(x: &i32) -> i32 {
29+
-x
30+
}
31+
32+
#[derive(Copy, Clone, Default)]
33+
struct Input;
34+
35+
struct Output;
36+
37+
impl Not for Input {
38+
type Output = Output;
39+
40+
fn not(self) -> Self::Output {
41+
Output
42+
}
43+
}
44+
45+
fn output_differs_from_operand() {
46+
let input = Default::default();
47+
let output = !input;
48+
let _: Input = input;
49+
let _: Output = output;
50+
}
51+
52+
fn output_expectation_differs_from_operand() {
53+
let input = Default::default();
54+
let _: Output = !input;
55+
let _: Input = input;
56+
}
57+
58+
fn main() {
59+
not_index(&vec![true]);
60+
neg_index(&vec![1]);
61+
let _ = not_reference(&1);
62+
let _ = neg_reference(&1);
63+
output_differs_from_operand();
64+
output_expectation_differs_from_operand();
65+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
use std::ops::{Deref, Index, Neg, Not};
2+
3+
struct Inner {
4+
value: u32,
5+
}
6+
7+
// `Inner` implements everything that the operators and place projections look
8+
// up, so the contrast below is only about whether `Wrapper` is autoderef'd.
9+
impl Not for Inner {
10+
type Output = Inner;
11+
12+
fn not(self) -> Inner {
13+
self
14+
}
15+
}
16+
17+
impl Neg for Inner {
18+
type Output = Inner;
19+
20+
fn neg(self) -> Inner {
21+
self
22+
}
23+
}
24+
25+
impl Index<usize> for Inner {
26+
type Output = u32;
27+
28+
fn index(&self, _: usize) -> &u32 {
29+
&self.value
30+
}
31+
}
32+
33+
struct Wrapper(Inner);
34+
35+
impl Deref for Wrapper {
36+
type Target = Inner;
37+
38+
fn deref(&self) -> &Inner {
39+
&self.0
40+
}
41+
}
42+
43+
fn main() {
44+
let wrapper = Wrapper(Inner { value: 0 });
45+
46+
// Field access and indexing are place projections, so they autoderef
47+
// `Wrapper` to `Inner` and both of these compile.
48+
let _ = wrapper.value;
49+
let _ = wrapper[0];
50+
51+
// `!` and `-` are value operators instead: they look up `Not` and `Neg` on
52+
// the operand type itself and do not autoderef it. `Wrapper` implements
53+
// neither trait, so both are rejected even though `Inner` does implement
54+
// them and `Wrapper` derefs to `Inner`.
55+
let _ = !wrapper;
56+
//~^ ERROR cannot apply unary operator `!` to type `Wrapper`
57+
58+
let _ = -wrapper;
59+
//~^ ERROR cannot apply unary operator `-` to type `Wrapper`
60+
}
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
error[E0600]: cannot apply unary operator `!` to type `Wrapper`
2+
--> $DIR/unary-op-no-autoderef.rs:55:13
3+
|
4+
LL | let _ = !wrapper;
5+
| ^^^^^^^^ cannot apply unary operator `!`
6+
|
7+
note: an implementation of `Not` might be missing for `Wrapper`
8+
--> $DIR/unary-op-no-autoderef.rs:33:1
9+
|
10+
LL | struct Wrapper(Inner);
11+
| ^^^^^^^^^^^^^^ must implement `Not`
12+
note: the trait `Not` must be implemented
13+
--> $SRC_DIR/core/src/ops/bit.rs:LL:COL
14+
15+
error[E0600]: cannot apply unary operator `-` to type `Wrapper`
16+
--> $DIR/unary-op-no-autoderef.rs:58:13
17+
|
18+
LL | let _ = -wrapper;
19+
| ^^^^^^^^ cannot apply unary operator `-`
20+
|
21+
note: an implementation of `Neg` might be missing for `Wrapper`
22+
--> $DIR/unary-op-no-autoderef.rs:33:1
23+
|
24+
LL | struct Wrapper(Inner);
25+
| ^^^^^^^^^^^^^^ must implement `Neg`
26+
note: the trait `Neg` must be implemented
27+
--> $SRC_DIR/core/src/ops/arith.rs:LL:COL
28+
29+
error: aborting due to 2 previous errors
30+
31+
For more information about this error, try `rustc --explain E0600`.

0 commit comments

Comments
 (0)