Make comma separated lists of anything easier to make for errors

Provide a new function `listify`, meant to be used in cases similar to `pluralize!`. When you have a slice of arbitrary elements that need to be presented to the user, `listify` allows you to turn that into a list of comma separated strings.

This reduces a lot of redundant logic that happens often in diagnostics.
This commit is contained in:
Esteban Küber 2025-01-31 20:36:44 +00:00
parent 7f36543a48
commit 8e9422f94e
11 changed files with 88 additions and 148 deletions

View file

@ -8,7 +8,9 @@ use rustc_ast::{
token,
};
use rustc_data_structures::fx::FxHashSet;
use rustc_errors::{Applicability, Diag, MultiSpan, PResult, SingleLabelManySpans};
use rustc_errors::{
Applicability, Diag, MultiSpan, PResult, SingleLabelManySpans, listify, pluralize,
};
use rustc_expand::base::*;
use rustc_lint_defs::builtin::NAMED_ARGUMENTS_USED_POSITIONALLY;
use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiag, LintId};
@ -975,15 +977,11 @@ fn report_invalid_references(
} else {
MultiSpan::from_spans(invalid_refs.iter().filter_map(|&(_, span, _, _)| span).collect())
};
let arg_list = if let &[index] = &indexes[..] {
format!("argument {index}")
} else {
let tail = indexes.pop().unwrap();
format!(
"arguments {head} and {tail}",
head = indexes.into_iter().map(|i| i.to_string()).collect::<Vec<_>>().join(", ")
)
};
let arg_list = format!(
"argument{} {}",
pluralize!(indexes.len()),
listify(&indexes, |i: &usize| i.to_string()).unwrap_or_default()
);
e = ecx.dcx().struct_span_err(
span,
format!("invalid reference to positional {arg_list} ({num_args_desc})"),