diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index dd6eb73a3a0aa..8959fb945b89d 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -3533,6 +3533,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .must_apply_modulo_regions() { let sm = self.tcx.sess.source_map(); + // If the span of rhs_expr or lhs_expr is in an external macro, + // we should not suggest to swap the equality. See issue #139050 + if rhs_expr.span.in_external_macro(sm) || lhs_expr.span.in_external_macro(sm) { + return; + } + if let Ok(rhs_snippet) = sm.span_to_snippet(rhs_expr.span) && let Ok(lhs_snippet) = sm.span_to_snippet(lhs_expr.span) { diff --git a/tests/ui/typeck/suggestions/sugg-swap-equality-in-macro-issue-139050.rs b/tests/ui/typeck/suggestions/sugg-swap-equality-in-macro-issue-139050.rs new file mode 100644 index 0000000000000..16c9e9614dfe1 --- /dev/null +++ b/tests/ui/typeck/suggestions/sugg-swap-equality-in-macro-issue-139050.rs @@ -0,0 +1,13 @@ +// if we use lhs == rhs in a macro, we should not suggest to swap the equality +// because the origin span of lhs and rhs can not be found. See issue #139050 + +use std::fmt::Debug; + +pub fn foo(mut iter: I, value: &I::Item) +where + Item: Eq + Debug, //~ ERROR cannot find type `Item` in this scope [E0412] +{ + debug_assert_eq!(iter.next(), Some(value)); //~ ERROR mismatched types [E0308] + assert_eq!(iter.next(), Some(value)); //~ ERROR mismatched types [E0308] +} +fn main() {} diff --git a/tests/ui/typeck/suggestions/sugg-swap-equality-in-macro-issue-139050.stderr b/tests/ui/typeck/suggestions/sugg-swap-equality-in-macro-issue-139050.stderr new file mode 100644 index 0000000000000..aef1353b5a046 --- /dev/null +++ b/tests/ui/typeck/suggestions/sugg-swap-equality-in-macro-issue-139050.stderr @@ -0,0 +1,28 @@ +error[E0412]: cannot find type `Item` in this scope + --> $DIR/sugg-swap-equality-in-macro-issue-139050.rs:8:5 + | +LL | Item: Eq + Debug, + | ^^^^ not found in this scope + +error[E0308]: mismatched types + --> $DIR/sugg-swap-equality-in-macro-issue-139050.rs:10:35 + | +LL | debug_assert_eq!(iter.next(), Some(value)); + | ^^^^^^^^^^^ expected `Option<::Item>`, found `Option<&::Item>` + | + = note: expected enum `Option<_>` + found enum `Option<&_>` + +error[E0308]: mismatched types + --> $DIR/sugg-swap-equality-in-macro-issue-139050.rs:11:29 + | +LL | assert_eq!(iter.next(), Some(value)); + | ^^^^^^^^^^^ expected `Option<::Item>`, found `Option<&::Item>` + | + = note: expected enum `Option<_>` + found enum `Option<&_>` + +error: aborting due to 3 previous errors + +Some errors have detailed explanations: E0308, E0412. +For more information about an error, try `rustc --explain E0308`.