Skip to content

Commit

Permalink
Adding if to prevent borrowing suggestion in structs rust-lang#71136
Browse files Browse the repository at this point in the history
  • Loading branch information
kper committed May 3, 2020
1 parent 7184d13 commit dfbc143
Showing 1 changed file with 46 additions and 6 deletions.
52 changes: 46 additions & 6 deletions src/librustc_trait_selection/traits/error_reporting/suggestions.rs
Expand Up @@ -562,13 +562,42 @@ 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
// might solve the problem. In cases like this, the important part is the
// 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,
Expand All @@ -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<Foo>
// }
// ```

err.span_suggestion(
span,
"consider borrowing here",
format!("&{}", snippet),
Applicability::MaybeIncorrect,
);
}
return true;
}
}
Expand Down

0 comments on commit dfbc143

Please sign in to comment.