From 3d80dd983d4048f0a480a76421cf30773d2a9081 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 26 Apr 2023 23:07:16 +0000 Subject: [PATCH 01/17] Clean up some builtin operator typeck logic --- compiler/rustc_hir_typeck/src/lib.rs | 12 ++----- compiler/rustc_hir_typeck/src/op.rs | 23 ++++++++----- compiler/rustc_hir_typeck/src/place_op.rs | 42 ++++++++++++----------- 3 files changed, 39 insertions(+), 38 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 5ccac9a69252d..46318043b78cf 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -461,15 +461,9 @@ fn fatally_break_rust(sess: &Session) { )); } -fn has_expected_num_generic_args( - tcx: TyCtxt<'_>, - trait_did: Option, - expected: usize, -) -> bool { - trait_did.map_or(true, |trait_did| { - let generics = tcx.generics_of(trait_did); - generics.count() == expected + if generics.has_self { 1 } else { 0 } - }) +fn has_expected_num_generic_args(tcx: TyCtxt<'_>, trait_did: DefId, expected: usize) -> bool { + let generics = tcx.generics_of(trait_did); + generics.count() == expected + if generics.has_self { 1 } else { 0 } } pub fn provide(providers: &mut Providers) { diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index a52c94cb00c53..9b6c1077a4002 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -719,7 +719,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Op::Binary(op, _) => op.span, Op::Unary(_, span) => span, }; - let (opname, trait_did) = lang_item_for_op(self.tcx, op, span); + let (opname, Some(trait_did)) = lang_item_for_op(self.tcx, op, span) else { + // Bail if the operator trait is not defined. + return Err(vec![]); + }; debug!( "lookup_op_method(lhs_ty={:?}, op={:?}, opname={:?}, trait_did={:?})", @@ -759,18 +762,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }, ); - let method = trait_did.and_then(|trait_did| { - self.lookup_method_in_trait(cause.clone(), opname, trait_did, lhs_ty, Some(input_types)) - }); - - match (method, trait_did) { - (Some(ok), _) => { + let method = self.lookup_method_in_trait( + cause.clone(), + opname, + trait_did, + lhs_ty, + Some(input_types), + ); + match method { + Some(ok) => { let method = self.register_infer_ok_obligations(ok); self.select_obligations_where_possible(|_| {}); Ok(method) } - (None, None) => Err(vec![]), - (None, Some(trait_did)) => { + None => { let (obligation, _) = self.obligation_for_method(cause, trait_did, lhs_ty, Some(input_types)); // FIXME: This should potentially just add the obligation to the `FnCtxt` diff --git a/compiler/rustc_hir_typeck/src/place_op.rs b/compiler/rustc_hir_typeck/src/place_op.rs index 2cca45de5e971..1f7e7ba9f5b2d 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -200,9 +200,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Option>> { debug!("try_overloaded_place_op({:?},{:?},{:?})", span, base_ty, op); - let (imm_tr, imm_op) = match op { + let (Some(imm_tr), imm_op) = (match op { PlaceOp::Deref => (self.tcx.lang_items().deref_trait(), sym::deref), PlaceOp::Index => (self.tcx.lang_items().index_trait(), sym::index), + }) else { + // Bail if `Deref` or `Index` isn't defined. + return None; }; // If the lang item was declared incorrectly, stop here so that we don't @@ -219,15 +222,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return None; } - imm_tr.and_then(|trait_did| { - self.lookup_method_in_trait( - self.misc(span), - Ident::with_dummy_span(imm_op), - trait_did, - base_ty, - Some(arg_tys), - ) - }) + self.lookup_method_in_trait( + self.misc(span), + Ident::with_dummy_span(imm_op), + imm_tr, + base_ty, + Some(arg_tys), + ) } fn try_mutable_overloaded_place_op( @@ -239,9 +240,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) -> Option>> { debug!("try_mutable_overloaded_place_op({:?},{:?},{:?})", span, base_ty, op); - let (mut_tr, mut_op) = match op { + let (Some(mut_tr), mut_op) = (match op { PlaceOp::Deref => (self.tcx.lang_items().deref_mut_trait(), sym::deref_mut), PlaceOp::Index => (self.tcx.lang_items().index_mut_trait(), sym::index_mut), + }) else { + // Bail if `DerefMut` or `IndexMut` isn't defined. + return None; }; // If the lang item was declared incorrectly, stop here so that we don't @@ -258,15 +262,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return None; } - mut_tr.and_then(|trait_did| { - self.lookup_method_in_trait( - self.misc(span), - Ident::with_dummy_span(mut_op), - trait_did, - base_ty, - Some(arg_tys), - ) - }) + self.lookup_method_in_trait( + self.misc(span), + Ident::with_dummy_span(mut_op), + mut_tr, + base_ty, + Some(arg_tys), + ) } /// Convert auto-derefs, indices, etc of an expression from `Deref` and `Index` From 015acc261101aa7efcd3b72c31ff5f320dda65e3 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 27 Apr 2023 00:57:13 +0000 Subject: [PATCH 02/17] Provide RHS type hint when reporting operator error --- compiler/rustc_hir_typeck/src/op.rs | 13 ++++ tests/ui/binop/eq-arr.rs | 7 +++ tests/ui/binop/eq-arr.stderr | 22 +++++++ tests/ui/binop/eq-vec.rs | 13 ++++ tests/ui/binop/eq-vec.stderr | 24 ++++++++ tests/ui/binop/issue-28837.stderr | 60 +++++++++---------- tests/ui/binop/issue-3820.stderr | 4 +- ...-span-PartialEq-enum-struct-variant.stderr | 4 +- .../derives-span-PartialEq-enum.stderr | 4 +- .../derives-span-PartialEq-struct.stderr | 4 +- ...derives-span-PartialEq-tuple-struct.stderr | 4 +- ...eriving-no-inner-impl-error-message.stderr | 4 +- .../note-unsupported.stderr | 4 +- tests/ui/issues/issue-62375.stderr | 4 +- .../assignment-operator-unimplemented.stderr | 4 +- .../or-patterns-syntactic-fail.stderr | 4 +- tests/ui/span/issue-39018.stderr | 4 +- tests/ui/suggestions/invalid-bin-op.stderr | 4 +- .../restrict-type-not-param.stderr | 4 +- tests/ui/type/type-unsatisfiable.usage.stderr | 4 +- 20 files changed, 137 insertions(+), 58 deletions(-) create mode 100644 tests/ui/binop/eq-arr.rs create mode 100644 tests/ui/binop/eq-arr.stderr create mode 100644 tests/ui/binop/eq-vec.rs create mode 100644 tests/ui/binop/eq-vec.stderr diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index 9b6c1077a4002..3f7f2d6e1e118 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -776,6 +776,19 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Ok(method) } None => { + // This path may do some inference, so make sure we've really + // doomed compilation so as to not accidentally stabilize new + // inference or something here... + self.tcx.sess.delay_span_bug(span, "this path really should be doomed..."); + // Guide inference for the RHS expression if it's provided -- + // this will allow us to better error reporting, at the expense + // of making some error messages a bit more specific. + if let Some((rhs_expr, rhs_ty)) = opt_rhs + && rhs_ty.is_ty_var() + { + self.check_expr_coercible_to_type(rhs_expr, rhs_ty, None); + } + let (obligation, _) = self.obligation_for_method(cause, trait_did, lhs_ty, Some(input_types)); // FIXME: This should potentially just add the obligation to the `FnCtxt` diff --git a/tests/ui/binop/eq-arr.rs b/tests/ui/binop/eq-arr.rs new file mode 100644 index 0000000000000..a77c4c5aabcdd --- /dev/null +++ b/tests/ui/binop/eq-arr.rs @@ -0,0 +1,7 @@ +fn main() { + struct X; + //~^ HELP consider annotating `X` with `#[derive(PartialEq)]` + let xs = [X, X, X]; + let eq = xs == [X, X, X]; + //~^ ERROR binary operation `==` cannot be applied to type `[X; 3]` +} diff --git a/tests/ui/binop/eq-arr.stderr b/tests/ui/binop/eq-arr.stderr new file mode 100644 index 0000000000000..a22f8e3ab0c79 --- /dev/null +++ b/tests/ui/binop/eq-arr.stderr @@ -0,0 +1,22 @@ +error[E0369]: binary operation `==` cannot be applied to type `[X; 3]` + --> $DIR/eq-arr.rs:5:17 + | +LL | let eq = xs == [X, X, X]; + | -- ^^ --------- [X; 3] + | | + | [X; 3] + | +note: an implementation of `PartialEq` might be missing for `X` + --> $DIR/eq-arr.rs:2:5 + | +LL | struct X; + | ^^^^^^^^ must implement `PartialEq` +help: consider annotating `X` with `#[derive(PartialEq)]` + | +LL + #[derive(PartialEq)] +LL | struct X; + | + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0369`. diff --git a/tests/ui/binop/eq-vec.rs b/tests/ui/binop/eq-vec.rs new file mode 100644 index 0000000000000..17ce8df856425 --- /dev/null +++ b/tests/ui/binop/eq-vec.rs @@ -0,0 +1,13 @@ +fn main() { + #[derive(Debug)] + enum Foo { + //~^ HELP consider annotating `Foo` with `#[derive(PartialEq)]` + Bar, + Qux, + } + + let vec1 = vec![Foo::Bar, Foo::Qux]; + let vec2 = vec![Foo::Bar, Foo::Qux]; + assert_eq!(vec1, vec2); + //~^ ERROR binary operation `==` cannot be applied to type `Vec` +} diff --git a/tests/ui/binop/eq-vec.stderr b/tests/ui/binop/eq-vec.stderr new file mode 100644 index 0000000000000..0a98cddfe05a9 --- /dev/null +++ b/tests/ui/binop/eq-vec.stderr @@ -0,0 +1,24 @@ +error[E0369]: binary operation `==` cannot be applied to type `Vec` + --> $DIR/eq-vec.rs:11:5 + | +LL | assert_eq!(vec1, vec2); + | ^^^^^^^^^^^^^^^^^^^^^^ + | | + | Vec + | Vec + | +note: an implementation of `PartialEq` might be missing for `Foo` + --> $DIR/eq-vec.rs:3:5 + | +LL | enum Foo { + | ^^^^^^^^ must implement `PartialEq` + = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info) +help: consider annotating `Foo` with `#[derive(PartialEq)]` + | +LL + #[derive(PartialEq)] +LL | enum Foo { + | + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0369`. diff --git a/tests/ui/binop/issue-28837.stderr b/tests/ui/binop/issue-28837.stderr index bb9f3b8af0ff1..6c98edd3af8e8 100644 --- a/tests/ui/binop/issue-28837.stderr +++ b/tests/ui/binop/issue-28837.stderr @@ -6,11 +6,11 @@ LL | a + a; | | | A | -note: an implementation of `Add<_>` might be missing for `A` +note: an implementation of `Add` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `Add<_>` + | ^^^^^^^^ must implement `Add` note: the trait `Add` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL @@ -22,11 +22,11 @@ LL | a - a; | | | A | -note: an implementation of `Sub<_>` might be missing for `A` +note: an implementation of `Sub` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `Sub<_>` + | ^^^^^^^^ must implement `Sub` note: the trait `Sub` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL @@ -38,11 +38,11 @@ LL | a * a; | | | A | -note: an implementation of `Mul<_>` might be missing for `A` +note: an implementation of `Mul` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `Mul<_>` + | ^^^^^^^^ must implement `Mul` note: the trait `Mul` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL @@ -54,11 +54,11 @@ LL | a / a; | | | A | -note: an implementation of `Div<_>` might be missing for `A` +note: an implementation of `Div` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `Div<_>` + | ^^^^^^^^ must implement `Div` note: the trait `Div` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL @@ -70,11 +70,11 @@ LL | a % a; | | | A | -note: an implementation of `Rem<_>` might be missing for `A` +note: an implementation of `Rem` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `Rem<_>` + | ^^^^^^^^ must implement `Rem` note: the trait `Rem` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL @@ -86,11 +86,11 @@ LL | a & a; | | | A | -note: an implementation of `BitAnd<_>` might be missing for `A` +note: an implementation of `BitAnd` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `BitAnd<_>` + | ^^^^^^^^ must implement `BitAnd` note: the trait `BitAnd` must be implemented --> $SRC_DIR/core/src/ops/bit.rs:LL:COL @@ -102,11 +102,11 @@ LL | a | a; | | | A | -note: an implementation of `BitOr<_>` might be missing for `A` +note: an implementation of `BitOr` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `BitOr<_>` + | ^^^^^^^^ must implement `BitOr` note: the trait `BitOr` must be implemented --> $SRC_DIR/core/src/ops/bit.rs:LL:COL @@ -118,11 +118,11 @@ LL | a << a; | | | A | -note: an implementation of `Shl<_>` might be missing for `A` +note: an implementation of `Shl` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `Shl<_>` + | ^^^^^^^^ must implement `Shl` note: the trait `Shl` must be implemented --> $SRC_DIR/core/src/ops/bit.rs:LL:COL @@ -134,11 +134,11 @@ LL | a >> a; | | | A | -note: an implementation of `Shr<_>` might be missing for `A` +note: an implementation of `Shr` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `Shr<_>` + | ^^^^^^^^ must implement `Shr` note: the trait `Shr` must be implemented --> $SRC_DIR/core/src/ops/bit.rs:LL:COL @@ -150,11 +150,11 @@ LL | a == a; | | | A | -note: an implementation of `PartialEq<_>` might be missing for `A` +note: an implementation of `PartialEq` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `PartialEq<_>` + | ^^^^^^^^ must implement `PartialEq` help: consider annotating `A` with `#[derive(PartialEq)]` | LL + #[derive(PartialEq)] @@ -169,11 +169,11 @@ LL | a != a; | | | A | -note: an implementation of `PartialEq<_>` might be missing for `A` +note: an implementation of `PartialEq` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `PartialEq<_>` + | ^^^^^^^^ must implement `PartialEq` help: consider annotating `A` with `#[derive(PartialEq)]` | LL + #[derive(PartialEq)] @@ -188,11 +188,11 @@ LL | a < a; | | | A | -note: an implementation of `PartialOrd<_>` might be missing for `A` +note: an implementation of `PartialOrd` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `PartialOrd<_>` + | ^^^^^^^^ must implement `PartialOrd` help: consider annotating `A` with `#[derive(PartialEq, PartialOrd)]` | LL + #[derive(PartialEq, PartialOrd)] @@ -207,11 +207,11 @@ LL | a <= a; | | | A | -note: an implementation of `PartialOrd<_>` might be missing for `A` +note: an implementation of `PartialOrd` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `PartialOrd<_>` + | ^^^^^^^^ must implement `PartialOrd` help: consider annotating `A` with `#[derive(PartialEq, PartialOrd)]` | LL + #[derive(PartialEq, PartialOrd)] @@ -226,11 +226,11 @@ LL | a > a; | | | A | -note: an implementation of `PartialOrd<_>` might be missing for `A` +note: an implementation of `PartialOrd` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `PartialOrd<_>` + | ^^^^^^^^ must implement `PartialOrd` help: consider annotating `A` with `#[derive(PartialEq, PartialOrd)]` | LL + #[derive(PartialEq, PartialOrd)] @@ -245,11 +245,11 @@ LL | a >= a; | | | A | -note: an implementation of `PartialOrd<_>` might be missing for `A` +note: an implementation of `PartialOrd` might be missing for `A` --> $DIR/issue-28837.rs:1:1 | LL | struct A; - | ^^^^^^^^ must implement `PartialOrd<_>` + | ^^^^^^^^ must implement `PartialOrd` help: consider annotating `A` with `#[derive(PartialEq, PartialOrd)]` | LL + #[derive(PartialEq, PartialOrd)] diff --git a/tests/ui/binop/issue-3820.stderr b/tests/ui/binop/issue-3820.stderr index c313ed6037f3a..cfa78a41dbf08 100644 --- a/tests/ui/binop/issue-3820.stderr +++ b/tests/ui/binop/issue-3820.stderr @@ -6,11 +6,11 @@ LL | let w = u * 3; | | | Thing | -note: an implementation of `Mul<_>` might be missing for `Thing` +note: an implementation of `Mul<{integer}>` might be missing for `Thing` --> $DIR/issue-3820.rs:1:1 | LL | struct Thing { - | ^^^^^^^^^^^^ must implement `Mul<_>` + | ^^^^^^^^^^^^ must implement `Mul<{integer}>` note: the trait `Mul` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL diff --git a/tests/ui/derives/derives-span-PartialEq-enum-struct-variant.stderr b/tests/ui/derives/derives-span-PartialEq-enum-struct-variant.stderr index 9fc25f2ade426..e3b17431f89af 100644 --- a/tests/ui/derives/derives-span-PartialEq-enum-struct-variant.stderr +++ b/tests/ui/derives/derives-span-PartialEq-enum-struct-variant.stderr @@ -7,11 +7,11 @@ LL | #[derive(PartialEq)] LL | x: Error | ^^^^^^^^ | -note: an implementation of `PartialEq<_>` might be missing for `Error` +note: an implementation of `PartialEq` might be missing for `Error` --> $DIR/derives-span-PartialEq-enum-struct-variant.rs:4:1 | LL | struct Error; - | ^^^^^^^^^^^^ must implement `PartialEq<_>` + | ^^^^^^^^^^^^ must implement `PartialEq` = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialEq)]` | diff --git a/tests/ui/derives/derives-span-PartialEq-enum.stderr b/tests/ui/derives/derives-span-PartialEq-enum.stderr index f56e784478d5f..d1631732a34f4 100644 --- a/tests/ui/derives/derives-span-PartialEq-enum.stderr +++ b/tests/ui/derives/derives-span-PartialEq-enum.stderr @@ -7,11 +7,11 @@ LL | #[derive(PartialEq)] LL | Error | ^^^^^ | -note: an implementation of `PartialEq<_>` might be missing for `Error` +note: an implementation of `PartialEq` might be missing for `Error` --> $DIR/derives-span-PartialEq-enum.rs:4:1 | LL | struct Error; - | ^^^^^^^^^^^^ must implement `PartialEq<_>` + | ^^^^^^^^^^^^ must implement `PartialEq` = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialEq)]` | diff --git a/tests/ui/derives/derives-span-PartialEq-struct.stderr b/tests/ui/derives/derives-span-PartialEq-struct.stderr index 76c0b0104afb6..ab6c6951fc634 100644 --- a/tests/ui/derives/derives-span-PartialEq-struct.stderr +++ b/tests/ui/derives/derives-span-PartialEq-struct.stderr @@ -7,11 +7,11 @@ LL | struct Struct { LL | x: Error | ^^^^^^^^ | -note: an implementation of `PartialEq<_>` might be missing for `Error` +note: an implementation of `PartialEq` might be missing for `Error` --> $DIR/derives-span-PartialEq-struct.rs:4:1 | LL | struct Error; - | ^^^^^^^^^^^^ must implement `PartialEq<_>` + | ^^^^^^^^^^^^ must implement `PartialEq` = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialEq)]` | diff --git a/tests/ui/derives/derives-span-PartialEq-tuple-struct.stderr b/tests/ui/derives/derives-span-PartialEq-tuple-struct.stderr index 7dae01dbb9916..865ecad0e8e6d 100644 --- a/tests/ui/derives/derives-span-PartialEq-tuple-struct.stderr +++ b/tests/ui/derives/derives-span-PartialEq-tuple-struct.stderr @@ -7,11 +7,11 @@ LL | struct Struct( LL | Error | ^^^^^ | -note: an implementation of `PartialEq<_>` might be missing for `Error` +note: an implementation of `PartialEq` might be missing for `Error` --> $DIR/derives-span-PartialEq-tuple-struct.rs:4:1 | LL | struct Error; - | ^^^^^^^^^^^^ must implement `PartialEq<_>` + | ^^^^^^^^^^^^ must implement `PartialEq` = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `Error` with `#[derive(PartialEq)]` | diff --git a/tests/ui/derives/deriving-no-inner-impl-error-message.stderr b/tests/ui/derives/deriving-no-inner-impl-error-message.stderr index 10af5d36ed936..ab99ba9fab5a6 100644 --- a/tests/ui/derives/deriving-no-inner-impl-error-message.stderr +++ b/tests/ui/derives/deriving-no-inner-impl-error-message.stderr @@ -7,11 +7,11 @@ LL | struct E { LL | x: NoCloneOrEq | ^^^^^^^^^^^^^^ | -note: an implementation of `PartialEq<_>` might be missing for `NoCloneOrEq` +note: an implementation of `PartialEq` might be missing for `NoCloneOrEq` --> $DIR/deriving-no-inner-impl-error-message.rs:1:1 | LL | struct NoCloneOrEq; - | ^^^^^^^^^^^^^^^^^^ must implement `PartialEq<_>` + | ^^^^^^^^^^^^^^^^^^ must implement `PartialEq` = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) help: consider annotating `NoCloneOrEq` with `#[derive(PartialEq)]` | diff --git a/tests/ui/destructuring-assignment/note-unsupported.stderr b/tests/ui/destructuring-assignment/note-unsupported.stderr index 8a88332b73e10..f556330070cb1 100644 --- a/tests/ui/destructuring-assignment/note-unsupported.stderr +++ b/tests/ui/destructuring-assignment/note-unsupported.stderr @@ -44,11 +44,11 @@ LL | S { x: a, y: b } += s; | | | cannot use `+=` on type `S` | -note: an implementation of `AddAssign<_>` might be missing for `S` +note: an implementation of `AddAssign` might be missing for `S` --> $DIR/note-unsupported.rs:1:1 | LL | struct S { x: u8, y: u8 } - | ^^^^^^^^ must implement `AddAssign<_>` + | ^^^^^^^^ must implement `AddAssign` note: the trait `AddAssign` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL diff --git a/tests/ui/issues/issue-62375.stderr b/tests/ui/issues/issue-62375.stderr index a6fd3700edda8..8a0e17a409a5f 100644 --- a/tests/ui/issues/issue-62375.stderr +++ b/tests/ui/issues/issue-62375.stderr @@ -6,11 +6,11 @@ LL | a == A::Value; | | | A | -note: an implementation of `PartialEq<_>` might be missing for `A` +note: an implementation of `PartialEq A {A::Value}>` might be missing for `A` --> $DIR/issue-62375.rs:1:1 | LL | enum A { - | ^^^^^^ must implement `PartialEq<_>` + | ^^^^^^ must implement `PartialEq A {A::Value}>` help: consider annotating `A` with `#[derive(PartialEq)]` | LL + #[derive(PartialEq)] diff --git a/tests/ui/mismatched_types/assignment-operator-unimplemented.stderr b/tests/ui/mismatched_types/assignment-operator-unimplemented.stderr index 2393791a9b2a8..66a85c4656af5 100644 --- a/tests/ui/mismatched_types/assignment-operator-unimplemented.stderr +++ b/tests/ui/mismatched_types/assignment-operator-unimplemented.stderr @@ -6,11 +6,11 @@ LL | a += *b; | | | cannot use `+=` on type `Foo` | -note: an implementation of `AddAssign<_>` might be missing for `Foo` +note: an implementation of `AddAssign` might be missing for `Foo` --> $DIR/assignment-operator-unimplemented.rs:1:1 | LL | struct Foo; - | ^^^^^^^^^^ must implement `AddAssign<_>` + | ^^^^^^^^^^ must implement `AddAssign` note: the trait `AddAssign` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL diff --git a/tests/ui/or-patterns/or-patterns-syntactic-fail.stderr b/tests/ui/or-patterns/or-patterns-syntactic-fail.stderr index 10d42b7e3c0b8..604bba417e6cc 100644 --- a/tests/ui/or-patterns/or-patterns-syntactic-fail.stderr +++ b/tests/ui/or-patterns/or-patterns-syntactic-fail.stderr @@ -30,11 +30,11 @@ LL | let _ = |A | B: E| (); | | | E | -note: an implementation of `BitOr<_>` might be missing for `E` +note: an implementation of `BitOr<()>` might be missing for `E` --> $DIR/or-patterns-syntactic-fail.rs:6:1 | LL | enum E { A, B } - | ^^^^^^ must implement `BitOr<_>` + | ^^^^^^ must implement `BitOr<()>` note: the trait `BitOr` must be implemented --> $SRC_DIR/core/src/ops/bit.rs:LL:COL diff --git a/tests/ui/span/issue-39018.stderr b/tests/ui/span/issue-39018.stderr index 771f21c45da68..bae9363927174 100644 --- a/tests/ui/span/issue-39018.stderr +++ b/tests/ui/span/issue-39018.stderr @@ -21,11 +21,11 @@ LL | let y = World::Hello + World::Goodbye; | | | World | -note: an implementation of `Add<_>` might be missing for `World` +note: an implementation of `Add` might be missing for `World` --> $DIR/issue-39018.rs:15:1 | LL | enum World { - | ^^^^^^^^^^ must implement `Add<_>` + | ^^^^^^^^^^ must implement `Add` note: the trait `Add` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL diff --git a/tests/ui/suggestions/invalid-bin-op.stderr b/tests/ui/suggestions/invalid-bin-op.stderr index e291cedb8357e..570afcea6434b 100644 --- a/tests/ui/suggestions/invalid-bin-op.stderr +++ b/tests/ui/suggestions/invalid-bin-op.stderr @@ -6,11 +6,11 @@ LL | let _ = s == t; | | | S | -note: an implementation of `PartialEq<_>` might be missing for `S` +note: an implementation of `PartialEq` might be missing for `S` --> $DIR/invalid-bin-op.rs:5:1 | LL | struct S(T); - | ^^^^^^^^^^^ must implement `PartialEq<_>` + | ^^^^^^^^^^^ must implement `PartialEq` help: consider annotating `S` with `#[derive(PartialEq)]` | LL + #[derive(PartialEq)] diff --git a/tests/ui/suggestions/restrict-type-not-param.stderr b/tests/ui/suggestions/restrict-type-not-param.stderr index 5434472ceecc7..3c7d42888d833 100644 --- a/tests/ui/suggestions/restrict-type-not-param.stderr +++ b/tests/ui/suggestions/restrict-type-not-param.stderr @@ -6,11 +6,11 @@ LL | a + b | | | Wrapper | -note: an implementation of `Add<_>` might be missing for `Wrapper` +note: an implementation of `Add` might be missing for `Wrapper` --> $DIR/restrict-type-not-param.rs:3:1 | LL | struct Wrapper(T); - | ^^^^^^^^^^^^^^^^^ must implement `Add<_>` + | ^^^^^^^^^^^^^^^^^ must implement `Add` note: the trait `Add` must be implemented --> $SRC_DIR/core/src/ops/arith.rs:LL:COL help: consider introducing a `where` clause, but there might be an alternative better way to express this requirement diff --git a/tests/ui/type/type-unsatisfiable.usage.stderr b/tests/ui/type/type-unsatisfiable.usage.stderr index 56e2e30afaca5..0b76ba8eb7e83 100644 --- a/tests/ui/type/type-unsatisfiable.usage.stderr +++ b/tests/ui/type/type-unsatisfiable.usage.stderr @@ -1,8 +1,8 @@ -error[E0369]: cannot subtract `(dyn Vector2 + 'static)` from `dyn Vector2` +error[E0369]: cannot subtract `dyn Vector2` from `dyn Vector2` --> $DIR/type-unsatisfiable.rs:57:20 | LL | let bar = *hey - *word; - | ---- ^ ----- (dyn Vector2 + 'static) + | ---- ^ ----- dyn Vector2 | | | dyn Vector2 From 3125979b78db0d4e2151f430d6f3f4464c086569 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Thu, 27 Apr 2023 01:32:44 +0000 Subject: [PATCH 03/17] Fix a bad binop error when we need a call --- .../rustc_hir_typeck/src/method/suggest.rs | 39 ++++++++++++------- compiler/rustc_hir_typeck/src/op.rs | 12 ++++-- tests/ui/issues/issue-62375.stderr | 9 +++-- 3 files changed, 39 insertions(+), 21 deletions(-) diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index db1f10f645fd4..43f40ada5acb6 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -27,8 +27,8 @@ use rustc_middle::traits::util::supertraits; use rustc_middle::ty::fast_reject::DeepRejectCtxt; use rustc_middle::ty::fast_reject::{simplify_type, TreatParams}; use rustc_middle::ty::print::{with_crate_prefix, with_forced_trimmed_paths}; +use rustc_middle::ty::IsSuggestable; use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeVisitableExt}; -use rustc_middle::ty::{IsSuggestable, ToPolyTraitRef}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Symbol; use rustc_span::{edit_distance, source_map, ExpnKind, FileName, MacroKind, Span}; @@ -2068,7 +2068,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut derives = Vec::<(String, Span, Symbol)>::new(); let mut traits = Vec::new(); for (pred, _, _) in unsatisfied_predicates { - let ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred)) = pred.kind().skip_binder() else { continue }; + let Some(ty::PredicateKind::Clause(ty::Clause::Trait(trait_pred))) = + pred.kind().no_bound_vars() + else { + continue + }; let adt = match trait_pred.self_ty().ty_adt_def() { Some(adt) if adt.did().is_local() => adt, _ => continue, @@ -2085,22 +2089,31 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { | sym::Hash | sym::Debug => true, _ => false, + } && match trait_pred.trait_ref.substs.as_slice() { + // Only suggest deriving if lhs == rhs... + [lhs, rhs] => { + if let Some(lhs) = lhs.as_type() + && let Some(rhs) = rhs.as_type() + { + self.can_eq(self.param_env, lhs, rhs) + } else { + false + } + }, + // Unary ops can always be derived + [_] => true, + _ => false, }; if can_derive { let self_name = trait_pred.self_ty().to_string(); let self_span = self.tcx.def_span(adt.did()); - if let Some(poly_trait_ref) = pred.to_opt_poly_trait_pred() { - for super_trait in supertraits(self.tcx, poly_trait_ref.to_poly_trait_ref()) + for super_trait in + supertraits(self.tcx, ty::Binder::dummy(trait_pred.trait_ref)) + { + if let Some(parent_diagnostic_name) = + self.tcx.get_diagnostic_name(super_trait.def_id()) { - if let Some(parent_diagnostic_name) = - self.tcx.get_diagnostic_name(super_trait.def_id()) - { - derives.push(( - self_name.clone(), - self_span, - parent_diagnostic_name, - )); - } + derives.push((self_name.clone(), self_span, parent_diagnostic_name)); } } derives.push((self_name, self_span, diagnostic_name)); diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index 3f7f2d6e1e118..e91ae4466eb87 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -408,7 +408,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }; - let is_compatible = |lhs_ty, rhs_ty| { + let is_compatible_after_call = |lhs_ty, rhs_ty| { self.lookup_op_method( lhs_ty, Some((rhs_expr, rhs_ty)), @@ -416,6 +416,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected, ) .is_ok() + // Suggest calling even if, after calling, the types don't + // implement the operator, since it'll lead to better + // diagnostics later. + || self.can_eq(self.param_env, lhs_ty, rhs_ty) }; // We should suggest `a + b` => `*a + b` if `a` is copy, and suggest @@ -436,16 +440,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { suggest_deref_binop(*lhs_deref_ty); } } else if self.suggest_fn_call(&mut err, lhs_expr, lhs_ty, |lhs_ty| { - is_compatible(lhs_ty, rhs_ty) + is_compatible_after_call(lhs_ty, rhs_ty) }) || self.suggest_fn_call(&mut err, rhs_expr, rhs_ty, |rhs_ty| { - is_compatible(lhs_ty, rhs_ty) + is_compatible_after_call(lhs_ty, rhs_ty) }) || self.suggest_two_fn_call( &mut err, rhs_expr, rhs_ty, lhs_expr, lhs_ty, - |lhs_ty, rhs_ty| is_compatible(lhs_ty, rhs_ty), + |lhs_ty, rhs_ty| is_compatible_after_call(lhs_ty, rhs_ty), ) { // Cool } diff --git a/tests/ui/issues/issue-62375.stderr b/tests/ui/issues/issue-62375.stderr index 8a0e17a409a5f..cd632e64fe5fc 100644 --- a/tests/ui/issues/issue-62375.stderr +++ b/tests/ui/issues/issue-62375.stderr @@ -11,11 +11,12 @@ note: an implementation of `PartialEq A {A::Value}>` might be missing | LL | enum A { | ^^^^^^ must implement `PartialEq A {A::Value}>` -help: consider annotating `A` with `#[derive(PartialEq)]` - | -LL + #[derive(PartialEq)] -LL | enum A { +note: the trait `PartialEq` must be implemented + --> $SRC_DIR/core/src/cmp.rs:LL:COL +help: use parentheses to construct this tuple variant | +LL | a == A::Value(/* () */); + | ++++++++++ error: aborting due to previous error From 6a89e9451f61c662d79c8293f819c3c84c8837fb Mon Sep 17 00:00:00 2001 From: Be Wilson Date: Thu, 27 Apr 2023 14:33:36 -0500 Subject: [PATCH 04/17] only error with +whole-archive,+bundle for rlibs Fixes https://github.com/rust-lang/rust/issues/110912 Checking `flavor == RlibFlavor::Normal` was accidentally lost in 601fc8b36b1962285e371cf3c54eeb3b1b9b3a74 https://github.com/rust-lang/rust/pull/105601 That caused combining +whole-archive and +bundle link modifiers on non-rlib crates to fail with a confusing error message saying that combination is unstable for rlibs. In particular, this caused the build to fail when +whole-archive was used on staticlib crates, even though +whole-archive effectively does nothing on non-bin crates because the final linker invocation is left to an external build system. --- compiler/rustc_codegen_ssa/src/back/link.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 02e21e74fadc8..eecfe13bb3eef 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -349,7 +349,10 @@ fn link_rlib<'a>( let NativeLibKind::Static { bundle: None | Some(true), whole_archive } = lib.kind else { continue; }; - if whole_archive == Some(true) && !codegen_results.crate_info.feature_packed_bundled_libs { + if whole_archive == Some(true) + && flavor == RlibFlavor::Normal + && !codegen_results.crate_info.feature_packed_bundled_libs + { sess.emit_err(errors::IncompatibleLinkingModifiers); } if flavor == RlibFlavor::Normal && let Some(filename) = lib.filename { From b51deba9ac36ee2808af8a03fe8bc6fc570cc497 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 28 Apr 2023 08:37:11 +1000 Subject: [PATCH 05/17] Remove `MemDecoder::read_raw_bytes_inherent`. It's unnecessary. Note that `MemDecoder::read_raw_bytes` how has a `&'a [u8]` return type, the same as what `read_raw_bytes_inherent` had. --- compiler/rustc_serialize/src/opaque.rs | 30 ++++++++++---------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/compiler/rustc_serialize/src/opaque.rs b/compiler/rustc_serialize/src/opaque.rs index b7976ea3b1c63..012a6406de35c 100644 --- a/compiler/rustc_serialize/src/opaque.rs +++ b/compiler/rustc_serialize/src/opaque.rs @@ -573,22 +573,6 @@ impl<'a> MemDecoder<'a> { self.read_raw_bytes(N).try_into().unwrap() } - // The trait method doesn't have a lifetime parameter, and we need a version of this - // that definitely returns a slice based on the underlying storage as opposed to - // the Decoder itself in order to implement read_str efficiently. - #[inline] - fn read_raw_bytes_inherent(&mut self, bytes: usize) -> &'a [u8] { - if bytes > self.remaining() { - Self::decoder_exhausted(); - } - // SAFETY: We just checked if this range is in-bounds above. - unsafe { - let slice = std::slice::from_raw_parts(self.current, bytes); - self.current = self.current.add(bytes); - slice - } - } - /// While we could manually expose manipulation of the decoder position, /// all current users of that method would need to reset the position later, /// incurring the bounds check of set_position twice. @@ -706,14 +690,22 @@ impl<'a> Decoder for MemDecoder<'a> { #[inline] fn read_str(&mut self) -> &str { let len = self.read_usize(); - let bytes = self.read_raw_bytes_inherent(len + 1); + let bytes = self.read_raw_bytes(len + 1); assert!(bytes[len] == STR_SENTINEL); unsafe { std::str::from_utf8_unchecked(&bytes[..len]) } } #[inline] - fn read_raw_bytes(&mut self, bytes: usize) -> &[u8] { - self.read_raw_bytes_inherent(bytes) + fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] { + if bytes > self.remaining() { + Self::decoder_exhausted(); + } + // SAFETY: We just checked if this range is in-bounds above. + unsafe { + let slice = std::slice::from_raw_parts(self.current, bytes); + self.current = self.current.add(bytes); + slice + } } #[inline] From 37c9e45186e00c197902a7c7349c18383aa0abf7 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 28 Apr 2023 08:53:13 +1000 Subject: [PATCH 06/17] Add a comment explaining the lack of `Decoder::read_enum_variant`. Because I was wondering about it, and this may save a future person from also wondering. --- compiler/rustc_serialize/src/serialize.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/compiler/rustc_serialize/src/serialize.rs b/compiler/rustc_serialize/src/serialize.rs index a6d9c7b7d4210..79c2f76c01c62 100644 --- a/compiler/rustc_serialize/src/serialize.rs +++ b/compiler/rustc_serialize/src/serialize.rs @@ -84,6 +84,11 @@ pub trait Decoder { fn read_char(&mut self) -> char; fn read_str(&mut self) -> &str; fn read_raw_bytes(&mut self, len: usize) -> &[u8]; + + // Although there is an `emit_enum_variant` method in `Encoder`, the code + // patterns in decoding are different enough to encoding that there is no + // need for a corresponding `read_enum_variant` method here. + fn peek_byte(&self) -> u8; fn position(&self) -> usize; } From 618841b8156a85ff937b755626eae0983c05da25 Mon Sep 17 00:00:00 2001 From: John Bobbo Date: Thu, 27 Apr 2023 19:48:37 -0700 Subject: [PATCH 07/17] Use `NonNull::new_unchecked` and `NonNull::len` in `rustc_arena`. --- compiler/rustc_arena/src/lib.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_arena/src/lib.rs b/compiler/rustc_arena/src/lib.rs index 345e058e1134a..236bdb99709e8 100644 --- a/compiler/rustc_arena/src/lib.rs +++ b/compiler/rustc_arena/src/lib.rs @@ -74,7 +74,7 @@ impl ArenaChunk { #[inline] unsafe fn new(capacity: usize) -> ArenaChunk { ArenaChunk { - storage: NonNull::new(Box::into_raw(Box::new_uninit_slice(capacity))).unwrap(), + storage: NonNull::new_unchecked(Box::into_raw(Box::new_uninit_slice(capacity))), entries: 0, } } @@ -85,7 +85,7 @@ impl ArenaChunk { // The branch on needs_drop() is an -O1 performance optimization. // Without the branch, dropping TypedArena takes linear time. if mem::needs_drop::() { - let slice = &mut *(self.storage.as_mut()); + let slice = self.storage.as_mut(); ptr::drop_in_place(MaybeUninit::slice_assume_init_mut(&mut slice[..len])); } } @@ -104,7 +104,7 @@ impl ArenaChunk { // A pointer as large as possible for zero-sized elements. ptr::invalid_mut(!0) } else { - self.start().add((*self.storage.as_ptr()).len()) + self.start().add(self.storage.len()) } } } @@ -288,7 +288,7 @@ impl TypedArena { // If the previous chunk's len is less than HUGE_PAGE // bytes, then this chunk will be least double the previous // chunk's size. - new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / elem_size / 2); + new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2); new_cap *= 2; } else { new_cap = PAGE / elem_size; @@ -396,7 +396,7 @@ impl DroplessArena { // If the previous chunk's len is less than HUGE_PAGE // bytes, then this chunk will be least double the previous // chunk's size. - new_cap = (*last_chunk.storage.as_ptr()).len().min(HUGE_PAGE / 2); + new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2); new_cap *= 2; } else { new_cap = PAGE; From fa133f5354ac29096d1577d5ba9c1400c2ad3b0f Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 28 Apr 2023 09:01:00 +1000 Subject: [PATCH 08/17] Remove a low-value assertion. Checking that `read_raw_bytes(len)` changes the position by `len` is a reasonable thing for a test, but isn't much use in just one of the zillion `Decodable` impls. --- compiler/rustc_serialize/src/opaque.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_serialize/src/opaque.rs b/compiler/rustc_serialize/src/opaque.rs index 012a6406de35c..6c18a8d074266 100644 --- a/compiler/rustc_serialize/src/opaque.rs +++ b/compiler/rustc_serialize/src/opaque.rs @@ -779,12 +779,7 @@ impl Encodable for IntEncodedWithFixedSize { impl<'a> Decodable> for IntEncodedWithFixedSize { #[inline] fn decode(decoder: &mut MemDecoder<'a>) -> IntEncodedWithFixedSize { - let _start_pos = decoder.position(); - let bytes = decoder.read_raw_bytes(IntEncodedWithFixedSize::ENCODED_SIZE); - let value = u64::from_le_bytes(bytes.try_into().unwrap()); - let _end_pos = decoder.position(); - debug_assert_eq!((_end_pos - _start_pos), IntEncodedWithFixedSize::ENCODED_SIZE); - - IntEncodedWithFixedSize(value) + let bytes = decoder.read_array::<{ IntEncodedWithFixedSize::ENCODED_SIZE }>(); + IntEncodedWithFixedSize(u64::from_le_bytes(bytes)) } } From 7a16d25365b5f0aa815948237c46fb1843386d7a Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 28 Apr 2023 09:06:57 +1000 Subject: [PATCH 09/17] Add some provided methods to `Encoder`/`Decoder`. The methods for `i8`, `bool`, `char`, `str` are the same for all impls, because they layered on top of other methods. --- compiler/rustc_serialize/src/opaque.rs | 76 ----------------------- compiler/rustc_serialize/src/serialize.rs | 64 ++++++++++++++++--- 2 files changed, 56 insertions(+), 84 deletions(-) diff --git a/compiler/rustc_serialize/src/opaque.rs b/compiler/rustc_serialize/src/opaque.rs index 6c18a8d074266..44d0cc8164da2 100644 --- a/compiler/rustc_serialize/src/opaque.rs +++ b/compiler/rustc_serialize/src/opaque.rs @@ -51,13 +51,6 @@ macro_rules! write_leb128 { }}; } -/// A byte that [cannot occur in UTF8 sequences][utf8]. Used to mark the end of a string. -/// This way we can skip validation and still be relatively sure that deserialization -/// did not desynchronize. -/// -/// [utf8]: https://en.wikipedia.org/w/index.php?title=UTF-8&oldid=1058865525#Codepage_layout -const STR_SENTINEL: u8 = 0xC1; - impl Encoder for MemEncoder { #[inline] fn emit_usize(&mut self, v: usize) { @@ -114,28 +107,6 @@ impl Encoder for MemEncoder { self.data.extend_from_slice(&v.to_le_bytes()); } - #[inline] - fn emit_i8(&mut self, v: i8) { - self.emit_u8(v as u8); - } - - #[inline] - fn emit_bool(&mut self, v: bool) { - self.emit_u8(if v { 1 } else { 0 }); - } - - #[inline] - fn emit_char(&mut self, v: char) { - self.emit_u32(v as u32); - } - - #[inline] - fn emit_str(&mut self, v: &str) { - self.emit_usize(v.len()); - self.emit_raw_bytes(v.as_bytes()); - self.emit_u8(STR_SENTINEL); - } - #[inline] fn emit_raw_bytes(&mut self, s: &[u8]) { self.data.extend_from_slice(s); @@ -480,28 +451,6 @@ impl Encoder for FileEncoder { self.write_all(&v.to_le_bytes()); } - #[inline] - fn emit_i8(&mut self, v: i8) { - self.emit_u8(v as u8); - } - - #[inline] - fn emit_bool(&mut self, v: bool) { - self.emit_u8(if v { 1 } else { 0 }); - } - - #[inline] - fn emit_char(&mut self, v: char) { - self.emit_u32(v as u32); - } - - #[inline] - fn emit_str(&mut self, v: &str) { - self.emit_usize(v.len()); - self.emit_raw_bytes(v.as_bytes()); - self.emit_u8(STR_SENTINEL); - } - #[inline] fn emit_raw_bytes(&mut self, s: &[u8]) { self.write_all(s); @@ -665,36 +614,11 @@ impl<'a> Decoder for MemDecoder<'a> { i16::from_le_bytes(self.read_array()) } - #[inline] - fn read_i8(&mut self) -> i8 { - self.read_byte() as i8 - } - #[inline] fn read_isize(&mut self) -> isize { read_leb128!(self, read_isize_leb128) } - #[inline] - fn read_bool(&mut self) -> bool { - let value = self.read_u8(); - value != 0 - } - - #[inline] - fn read_char(&mut self) -> char { - let bits = self.read_u32(); - std::char::from_u32(bits).unwrap() - } - - #[inline] - fn read_str(&mut self) -> &str { - let len = self.read_usize(); - let bytes = self.read_raw_bytes(len + 1); - assert!(bytes[len] == STR_SENTINEL); - unsafe { std::str::from_utf8_unchecked(&bytes[..len]) } - } - #[inline] fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] { if bytes > self.remaining() { diff --git a/compiler/rustc_serialize/src/serialize.rs b/compiler/rustc_serialize/src/serialize.rs index 79c2f76c01c62..e1bc598736fee 100644 --- a/compiler/rustc_serialize/src/serialize.rs +++ b/compiler/rustc_serialize/src/serialize.rs @@ -12,6 +12,13 @@ use std::path; use std::rc::Rc; use std::sync::Arc; +/// A byte that [cannot occur in UTF8 sequences][utf8]. Used to mark the end of a string. +/// This way we can skip validation and still be relatively sure that deserialization +/// did not desynchronize. +/// +/// [utf8]: https://en.wikipedia.org/w/index.php?title=UTF-8&oldid=1058865525#Codepage_layout +const STR_SENTINEL: u8 = 0xC1; + /// A note about error handling. /// /// Encoders may be fallible, but in practice failure is rare and there are so @@ -40,10 +47,29 @@ pub trait Encoder { fn emit_i64(&mut self, v: i64); fn emit_i32(&mut self, v: i32); fn emit_i16(&mut self, v: i16); - fn emit_i8(&mut self, v: i8); - fn emit_bool(&mut self, v: bool); - fn emit_char(&mut self, v: char); - fn emit_str(&mut self, v: &str); + + #[inline] + fn emit_i8(&mut self, v: i8) { + self.emit_u8(v as u8); + } + + #[inline] + fn emit_bool(&mut self, v: bool) { + self.emit_u8(if v { 1 } else { 0 }); + } + + #[inline] + fn emit_char(&mut self, v: char) { + self.emit_u32(v as u32); + } + + #[inline] + fn emit_str(&mut self, v: &str) { + self.emit_usize(v.len()); + self.emit_raw_bytes(v.as_bytes()); + self.emit_u8(STR_SENTINEL); + } + fn emit_raw_bytes(&mut self, s: &[u8]); fn emit_enum_variant(&mut self, v_id: usize, f: F) @@ -79,10 +105,32 @@ pub trait Decoder { fn read_i64(&mut self) -> i64; fn read_i32(&mut self) -> i32; fn read_i16(&mut self) -> i16; - fn read_i8(&mut self) -> i8; - fn read_bool(&mut self) -> bool; - fn read_char(&mut self) -> char; - fn read_str(&mut self) -> &str; + + #[inline] + fn read_i8(&mut self) -> i8 { + self.read_u8() as i8 + } + + #[inline] + fn read_bool(&mut self) -> bool { + let value = self.read_u8(); + value != 0 + } + + #[inline] + fn read_char(&mut self) -> char { + let bits = self.read_u32(); + std::char::from_u32(bits).unwrap() + } + + #[inline] + fn read_str(&mut self) -> &str { + let len = self.read_usize(); + let bytes = self.read_raw_bytes(len + 1); + assert!(bytes[len] == STR_SENTINEL); + unsafe { std::str::from_utf8_unchecked(&bytes[..len]) } + } + fn read_raw_bytes(&mut self, len: usize) -> &[u8]; // Although there is an `emit_enum_variant` method in `Encoder`, the code From a676dfa888b3d14abfa5d9b9a1045f8c1bde6793 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 28 Apr 2023 09:16:31 +1000 Subject: [PATCH 10/17] Remove `MemDecoder::read_byte`. It's just a synonym for `read_u8`. --- compiler/rustc_serialize/src/opaque.rs | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_serialize/src/opaque.rs b/compiler/rustc_serialize/src/opaque.rs index 44d0cc8164da2..0f6e4b329b87e 100644 --- a/compiler/rustc_serialize/src/opaque.rs +++ b/compiler/rustc_serialize/src/opaque.rs @@ -504,19 +504,6 @@ impl<'a> MemDecoder<'a> { panic!("MemDecoder exhausted") } - #[inline] - fn read_byte(&mut self) -> u8 { - if self.current == self.end { - Self::decoder_exhausted(); - } - // SAFETY: This type guarantees current <= end, and we just checked current == end. - unsafe { - let byte = *self.current; - self.current = self.current.add(1); - byte - } - } - #[inline] fn read_array(&mut self) -> [u8; N] { self.read_raw_bytes(N).try_into().unwrap() @@ -586,7 +573,15 @@ impl<'a> Decoder for MemDecoder<'a> { #[inline] fn read_u8(&mut self) -> u8 { - self.read_byte() + if self.current == self.end { + Self::decoder_exhausted(); + } + // SAFETY: This type guarantees current <= end, and we just checked current == end. + unsafe { + let byte = *self.current; + self.current = self.current.add(1); + byte + } } #[inline] From 23e91d4d73785f6dfac6b6ac198dc45574cabc88 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 28 Apr 2023 11:38:59 +1000 Subject: [PATCH 11/17] Remove some unnecessary derives. I was curious about how many `Encodable`/`Decodable` derives we have. Some grepping revealed that it's over 500 of each, but the number of `Encodable` ones was higher, which was weird. Most of the `Encodable`-only ones were in `hir.rs`. This commit removes them all, plus some other unnecessary derives in that file and others that I found via trial and error. --- compiler/rustc_hir/src/hir.rs | 78 ++++++++++------------ compiler/rustc_middle/src/middle/region.rs | 6 +- compiler/rustc_middle/src/traits/mod.rs | 14 ++-- compiler/rustc_middle/src/ty/adt.rs | 2 +- 4 files changed, 48 insertions(+), 52 deletions(-) diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 21b4a3370d3e3..e220a0293393e 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -26,7 +26,7 @@ use rustc_target::spec::abi::Abi; use smallvec::SmallVec; use std::fmt; -#[derive(Debug, Copy, Clone, Encodable, HashStable_Generic)] +#[derive(Debug, Copy, Clone, HashStable_Generic)] pub struct Lifetime { pub hir_id: HirId, @@ -41,8 +41,7 @@ pub struct Lifetime { pub res: LifetimeName, } -#[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)] -#[derive(HashStable_Generic)] +#[derive(Debug, Copy, Clone, HashStable_Generic)] pub enum ParamName { /// Some user-given name like `T` or `'x`. Plain(Ident), @@ -85,8 +84,7 @@ impl ParamName { } } -#[derive(Debug, Clone, PartialEq, Eq, Encodable, Hash, Copy)] -#[derive(HashStable_Generic)] +#[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable_Generic)] pub enum LifetimeName { /// User-given names or fresh (synthetic) names. Param(LocalDefId), @@ -243,13 +241,13 @@ impl<'hir> PathSegment<'hir> { } } -#[derive(Encodable, Clone, Copy, Debug, HashStable_Generic)] +#[derive(Clone, Copy, Debug, HashStable_Generic)] pub struct ConstArg { pub value: AnonConst, pub span: Span, } -#[derive(Encodable, Clone, Copy, Debug, HashStable_Generic)] +#[derive(Clone, Copy, Debug, HashStable_Generic)] pub struct InferArg { pub hir_id: HirId, pub span: Span, @@ -422,8 +420,7 @@ impl<'hir> GenericArgs<'hir> { } } -#[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)] -#[derive(HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Eq, Debug, HashStable_Generic)] pub enum GenericArgsParentheses { No, /// Bounds for `feature(return_type_notation)`, like `T: Trait`, @@ -435,8 +432,7 @@ pub enum GenericArgsParentheses { /// A modifier on a bound, currently this is only used for `?Sized`, where the /// modifier is `Maybe`. Negative bounds should also be handled here. -#[derive(Copy, Clone, PartialEq, Eq, Encodable, Hash, Debug)] -#[derive(HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)] pub enum TraitBoundModifier { None, Maybe, @@ -474,7 +470,7 @@ impl GenericBound<'_> { pub type GenericBounds<'hir> = &'hir [GenericBound<'hir>]; -#[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, Debug, HashStable_Generic)] pub enum LifetimeParamKind { // Indicates that the lifetime definition was explicitly declared (e.g., in // `fn foo<'a>(x: &'a u8) -> &'a u8 { x }`). @@ -539,7 +535,7 @@ impl<'hir> GenericParam<'hir> { /// early-bound (but can be a late-bound lifetime in functions, for example), /// or from a `for<...>` binder, in which case it's late-bound (and notably, /// does not show up in the parent item's generics). -#[derive(Debug, HashStable_Generic, PartialEq, Eq, Copy, Clone)] +#[derive(Debug, Clone, Copy, HashStable_Generic)] pub enum GenericParamSource { // Early or late-bound parameters defined on an item Generics, @@ -1097,7 +1093,7 @@ pub struct PatField<'hir> { pub span: Span, } -#[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)] pub enum RangeEnd { Included, Excluded, @@ -1197,7 +1193,7 @@ pub enum PatKind<'hir> { Slice(&'hir [Pat<'hir>], Option<&'hir Pat<'hir>>, &'hir [Pat<'hir>]), } -#[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)] pub enum BinOpKind { /// The `+` operator (addition). Add, @@ -1325,7 +1321,7 @@ impl Into for BinOpKind { pub type BinOp = Spanned; -#[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)] pub enum UnOp { /// The `*` operator (dereferencing). Deref, @@ -1450,19 +1446,19 @@ pub struct ExprField<'hir> { pub is_shorthand: bool, } -#[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)] pub enum BlockCheckMode { DefaultBlock, UnsafeBlock(UnsafeSource), } -#[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)] pub enum UnsafeSource { CompilerGenerated, UserProvided, } -#[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub struct BodyId { pub hir_id: HirId, } @@ -1506,7 +1502,7 @@ impl<'hir> Body<'hir> { } /// The type of source expression that caused this generator to be created. -#[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)] +#[derive(Clone, PartialEq, Eq, Debug, Copy, Hash)] #[derive(HashStable_Generic, Encodable, Decodable)] pub enum GeneratorKind { /// An explicit `async` block or the body of an async function. @@ -1539,7 +1535,7 @@ impl GeneratorKind { /// /// This helps error messages but is also used to drive coercions in /// type-checking (see #60424). -#[derive(Clone, PartialEq, PartialOrd, Eq, Hash, Debug, Copy)] +#[derive(Clone, PartialEq, Eq, Hash, Debug, Copy)] #[derive(HashStable_Generic, Encodable, Decodable)] pub enum AsyncGeneratorKind { /// An explicit `async` block written by the user. @@ -1649,7 +1645,7 @@ impl fmt::Display for ConstContext { /// A literal. pub type Lit = Spanned; -#[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, Debug, HashStable_Generic)] pub enum ArrayLen { Infer(HirId, Span), Body(AnonConst), @@ -1671,7 +1667,7 @@ impl ArrayLen { /// /// You can check if this anon const is a default in a const param /// `const N: usize = { ... }` with `tcx.hir().opt_const_param_default_param_def_id(..)` -#[derive(Copy, Clone, PartialEq, Eq, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, Debug, HashStable_Generic)] pub struct AnonConst { pub hir_id: HirId, pub def_id: LocalDefId, @@ -2105,7 +2101,7 @@ impl<'hir> QPath<'hir> { } /// Hints at the original code for a let statement. -#[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, Debug, HashStable_Generic)] pub enum LocalSource { /// A `match _ { .. }`. Normal, @@ -2158,7 +2154,7 @@ impl MatchSource { } /// The loop type that yielded an `ExprKind::Loop`. -#[derive(Copy, Clone, PartialEq, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, PartialEq, Debug, HashStable_Generic)] pub enum LoopSource { /// A `loop { .. }` loop. Loop, @@ -2178,7 +2174,7 @@ impl LoopSource { } } -#[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, Debug, HashStable_Generic)] pub enum LoopIdError { OutsideLoopScope, UnlabeledCfInWhileCondition, @@ -2197,7 +2193,7 @@ impl fmt::Display for LoopIdError { } } -#[derive(Copy, Clone, Encodable, Debug, HashStable_Generic)] +#[derive(Copy, Clone, Debug, HashStable_Generic)] pub struct Destination { /// This is `Some(_)` iff there is an explicit user-specified 'label pub label: Option