Skip to content

Commit dfbc143

Browse files
committed
Adding if to prevent borrowing suggestion in structs #71136
1 parent 7184d13 commit dfbc143

File tree

1 file changed

+46
-6
lines changed

1 file changed

+46
-6
lines changed

src/librustc_trait_selection/traits/error_reporting/suggestions.rs

+46-6
Original file line numberDiff line numberDiff line change
@@ -562,13 +562,42 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
562562
param_env,
563563
new_trait_ref.without_const().to_predicate(),
564564
);
565+
565566
if self.predicate_must_hold_modulo_regions(&new_obligation) {
566567
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
567568
// We have a very specific type of error, where just borrowing this argument
568569
// might solve the problem. In cases like this, the important part is the
569570
// original type obligation, not the last one that failed, which is arbitrary.
570571
// Because of this, we modify the error to refer to the original obligation and
571572
// return early in the caller.
573+
574+
575+
let has_colon = self
576+
.tcx
577+
.sess
578+
.source_map()
579+
.span_to_snippet(span)
580+
.map(|w| w.contains(":"))
581+
.unwrap_or(false);
582+
583+
let has_double_colon = self
584+
.tcx
585+
.sess
586+
.source_map()
587+
.span_to_snippet(span)
588+
.map(|w| w.contains("::"))
589+
.unwrap_or(false);
590+
591+
let has_bracket = self
592+
.tcx
593+
.sess
594+
.source_map()
595+
.span_to_snippet(span)
596+
.map(|w| w.contains("{"))
597+
.unwrap_or(false);
598+
599+
600+
572601
let msg = format!(
573602
"the trait bound `{}: {}` is not satisfied",
574603
found,
@@ -591,12 +620,23 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
591620
obligation.parent_trait_ref.skip_binder().print_only_trait_path(),
592621
),
593622
);
594-
err.span_suggestion(
595-
span,
596-
"consider borrowing here",
597-
format!("&{}", snippet),
598-
Applicability::MaybeIncorrect,
599-
);
623+
624+
// This if is to prevent a special edge-case
625+
if !has_colon || has_double_colon || has_bracket {
626+
// We don't want a borrowing suggestion on the fields in structs,
627+
// ```
628+
// struct Foo {
629+
// the_foos: Vec<Foo>
630+
// }
631+
// ```
632+
633+
err.span_suggestion(
634+
span,
635+
"consider borrowing here",
636+
format!("&{}", snippet),
637+
Applicability::MaybeIncorrect,
638+
);
639+
}
600640
return true;
601641
}
602642
}

0 commit comments

Comments
 (0)