Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use multipart_suggestions more #86754

Merged
merged 1 commit into from
Jul 31, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions compiler/rustc_errors/src/diagnostic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,30 @@ impl Diagnostic {
self
}

/// Prints out a message with multiple suggested edits of the code.
/// See also [`Diagnostic::span_suggestion()`].
pub fn multipart_suggestions(
&mut self,
msg: &str,
suggestions: impl Iterator<Item = Vec<(Span, String)>>,
applicability: Applicability,
) -> &mut Self {
self.suggestions.push(CodeSuggestion {
substitutions: suggestions
.map(|sugg| Substitution {
parts: sugg
.into_iter()
.map(|(span, snippet)| SubstitutionPart { snippet, span })
.collect(),
})
.collect(),
msg: msg.to_owned(),
style: SuggestionStyle::ShowCode,
applicability,
tool_metadata: Default::default(),
});
self
}
/// Prints out a message with a suggested edit of the code. If the suggestion is presented
/// inline, it will only show the message and not the suggestion.
///
Expand Down
14 changes: 14 additions & 0 deletions compiler/rustc_errors/src/diagnostic_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,20 @@ impl<'a> DiagnosticBuilder<'a> {
self
}

/// See [`Diagnostic::multipart_suggestions()`].
pub fn multipart_suggestions(
&mut self,
msg: &str,
suggestions: impl Iterator<Item = Vec<(Span, String)>>,
applicability: Applicability,
) -> &mut Self {
if !self.0.allow_suggestions {
return self;
}
self.0.diagnostic.multipart_suggestions(msg, suggestions, applicability);
self
}

/// See [`Diagnostic::span_suggestion_short()`].
pub fn span_suggestion_short(
&mut self,
Expand Down
23 changes: 12 additions & 11 deletions compiler/rustc_mir/src/borrow_check/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use rustc_middle::mir::{
use rustc_middle::ty::{self, suggest_constraining_type_param, Ty};
use rustc_span::source_map::DesugaringKind;
use rustc_span::symbol::sym;
use rustc_span::{MultiSpan, Span, DUMMY_SP};
use rustc_span::{BytePos, MultiSpan, Span, DUMMY_SP};
use rustc_trait_selection::infer::InferCtxtExt;

use crate::dataflow::drop_flag_effects;
Expand Down Expand Up @@ -1393,18 +1393,19 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
let tcx = self.infcx.tcx;
let args_span = use_span.args_or_use();

let suggestion = match tcx.sess.source_map().span_to_snippet(args_span) {
Ok(mut string) => {
let (sugg_span, suggestion) = match tcx.sess.source_map().span_to_snippet(args_span) {
Ok(string) => {
if string.starts_with("async ") {
string.insert_str(6, "move ");
let pos = args_span.lo() + BytePos(6);
(args_span.with_lo(pos).with_hi(pos), "move ".to_string())
} else if string.starts_with("async|") {
string.insert_str(5, " move");
let pos = args_span.lo() + BytePos(5);
(args_span.with_lo(pos).with_hi(pos), " move".to_string())
} else {
string.insert_str(0, "move ");
};
string
(args_span.shrink_to_lo(), "move ".to_string())
}
}
Err(_) => "move |<args>| <body>".to_string(),
Err(_) => (args_span, "move |<args>| <body>".to_string()),
};
let kind = match use_span.generator_kind() {
Some(generator_kind) => match generator_kind {
Expand All @@ -1420,8 +1421,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {

let mut err =
self.cannot_capture_in_long_lived_closure(args_span, kind, captured_var, var_span);
err.span_suggestion(
args_span,
err.span_suggestion_verbose(
sugg_span,
&format!(
"to force the {} to take ownership of {} (and any \
other referenced variables), use the `move` keyword",
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/parser/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1770,7 +1770,7 @@ impl<'a> Parser<'a> {
let mut err = self.struct_span_err(span, &msg);
let sp = self.sess.source_map().start_point(self.token.span);
if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
self.sess.expr_parentheses_needed(&mut err, *sp, None);
self.sess.expr_parentheses_needed(&mut err, *sp);
}
err.span_label(span, "expected expression");
err
Expand Down
14 changes: 6 additions & 8 deletions compiler/rustc_parse/src/parser/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,7 @@ impl<'a> Parser<'a> {
&format!("expected expression, found `{}`", pprust::token_to_string(&self.token),),
);
err.span_label(self.token.span, "expected expression");
self.sess.expr_parentheses_needed(&mut err, lhs.span, Some(pprust::expr_to_string(&lhs)));
self.sess.expr_parentheses_needed(&mut err, lhs.span);
err.emit();
}

Expand Down Expand Up @@ -696,20 +696,18 @@ impl<'a> Parser<'a> {
let expr =
mk_expr(self, lhs, self.mk_ty(path.span, TyKind::Path(None, path)));

let expr_str = self
.span_to_snippet(expr.span)
.unwrap_or_else(|_| pprust::expr_to_string(&expr));

self.struct_span_err(self.token.span, &msg)
.span_label(
self.look_ahead(1, |t| t.span).to(span_after_type),
"interpreted as generic arguments",
)
.span_label(self.token.span, format!("not interpreted as {}", op_noun))
.span_suggestion(
expr.span,
.multipart_suggestion(
&format!("try {} the cast value", op_verb),
format!("({})", expr_str),
vec![
(expr.span.shrink_to_lo(), "(".to_string()),
(expr.span.shrink_to_hi(), ")".to_string()),
],
Applicability::MachineApplicable,
)
.emit();
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/parser/pat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ impl<'a> Parser<'a> {

let sp = self.sess.source_map().start_point(self.token.span);
if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) {
self.sess.expr_parentheses_needed(&mut err, *sp, None);
self.sess.expr_parentheses_needed(&mut err, *sp);
}

Err(err)
Expand Down
20 changes: 6 additions & 14 deletions compiler/rustc_session/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -228,20 +228,12 @@ impl ParseSess {

/// Extend an error with a suggestion to wrap an expression with parentheses to allow the
/// parser to continue parsing the following operation as part of the same expression.
pub fn expr_parentheses_needed(
&self,
err: &mut DiagnosticBuilder<'_>,
span: Span,
alt_snippet: Option<String>,
) {
if let Some(snippet) = self.source_map().span_to_snippet(span).ok().or(alt_snippet) {
err.span_suggestion(
span,
"parentheses are required to parse this as an expression",
format!("({})", snippet),
Applicability::MachineApplicable,
);
}
pub fn expr_parentheses_needed(&self, err: &mut DiagnosticBuilder<'_>, span: Span) {
err.multipart_suggestion(
"parentheses are required to parse this as an expression",
vec![(span.shrink_to_lo(), "(".to_string()), (span.shrink_to_hi(), ")".to_string())],
Applicability::MachineApplicable,
);
}

pub fn save_proc_macro_span(&self, span: Span) -> usize {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1163,15 +1163,18 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
if is_object_safe {
// Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`.
// Get all the return values and collect their span and suggestion.
if let Some(mut suggestions) = visitor
let mut suggestions: Vec<_> = visitor
.returns
.iter()
.map(|expr| {
let snip = sm.span_to_snippet(expr.span).ok()?;
Some((expr.span, format!("Box::new({})", snip)))
.flat_map(|expr| {
vec![
(expr.span.shrink_to_lo(), "Box::new(".to_string()),
(expr.span.shrink_to_hi(), ")".to_string()),
]
.into_iter()
})
.collect::<Option<Vec<_>>>()
{
.collect();
if !suggestions.is_empty() {
// Add the suggestion for the return type.
suggestions.push((ret_ty.span, format!("Box<dyn {}>", trait_obj)));
err.multipart_suggestion(
Expand Down
Loading