From dfbc143e65dd4dc8499f7296ddc7889854a8cc7d Mon Sep 17 00:00:00 2001 From: Kevin Per Date: Sun, 3 May 2020 11:00:25 +0200 Subject: [PATCH] Adding if to prevent borrowing suggestion in structs #71136 --- .../traits/error_reporting/suggestions.rs | 52 ++++++++++++++++--- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs index 5ec2d68ab2a7d..37f567401b74a 100644 --- a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs +++ b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs @@ -562,6 +562,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { param_env, new_trait_ref.without_const().to_predicate(), ); + if self.predicate_must_hold_modulo_regions(&new_obligation) { if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { // We have a very specific type of error, where just borrowing this argument @@ -569,6 +570,34 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { // original type obligation, not the last one that failed, which is arbitrary. // Because of this, we modify the error to refer to the original obligation and // return early in the caller. + + + let has_colon = self + .tcx + .sess + .source_map() + .span_to_snippet(span) + .map(|w| w.contains(":")) + .unwrap_or(false); + + let has_double_colon = self + .tcx + .sess + .source_map() + .span_to_snippet(span) + .map(|w| w.contains("::")) + .unwrap_or(false); + + let has_bracket = self + .tcx + .sess + .source_map() + .span_to_snippet(span) + .map(|w| w.contains("{")) + .unwrap_or(false); + + + let msg = format!( "the trait bound `{}: {}` is not satisfied", found, @@ -591,12 +620,23 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { obligation.parent_trait_ref.skip_binder().print_only_trait_path(), ), ); - err.span_suggestion( - span, - "consider borrowing here", - format!("&{}", snippet), - Applicability::MaybeIncorrect, - ); + + // This if is to prevent a special edge-case + if !has_colon || has_double_colon || has_bracket { + // We don't want a borrowing suggestion on the fields in structs, + // ``` + // struct Foo { + // the_foos: Vec + // } + // ``` + + err.span_suggestion( + span, + "consider borrowing here", + format!("&{}", snippet), + Applicability::MaybeIncorrect, + ); + } return true; } }