1
Fork 0

Rollup merge of #64342 - glorv:master, r=varkor

factor out pluralisation remains after #64280

there are two case that doesn't not match the original macro pattern at [here](https://github.com/rust-lang/rust/blob/master/src/librustc_lint/unused.rs#L146) and [here](https://github.com/rust-lang/rust/blob/master/src/libsyntax/parse/diagnostics.rs#L539) as the provided param is already a bool or the check condition is not `x != 1`, so I change the macro accept a boolean expr instead of number to fit all the cases.

@Centril  please review

Fixes #64238.
This commit is contained in:
Mazdak Farrokhzad 2019-09-21 16:01:26 +02:00 committed by GitHub
commit d021dba048
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
17 changed files with 56 additions and 45 deletions

View file

@ -7,7 +7,7 @@
use crate::lint::{LintPass, LateLintPass, LintArray}; use crate::lint::{LintPass, LateLintPass, LintArray};
use crate::middle::stability; use crate::middle::stability;
use crate::session::Session; use crate::session::Session;
use errors::{Applicability, DiagnosticBuilder}; use errors::{Applicability, DiagnosticBuilder, pluralise};
use syntax::ast; use syntax::ast;
use syntax::source_map::Span; use syntax::source_map::Span;
use syntax::symbol::Symbol; use syntax::symbol::Symbol;
@ -524,7 +524,7 @@ pub(crate) fn add_elided_lifetime_in_path_suggestion(
}; };
db.span_suggestion( db.span_suggestion(
replace_span, replace_span,
&format!("indicate the anonymous lifetime{}", if n >= 2 { "s" } else { "" }), &format!("indicate the anonymous lifetime{}", pluralise!(n)),
suggestion, suggestion,
Applicability::MachineApplicable Applicability::MachineApplicable
); );

View file

@ -17,7 +17,7 @@ use crate::ty::{self, DefIdTree, GenericParamDefKind, TyCtxt};
use crate::rustc::lint; use crate::rustc::lint;
use crate::session::Session; use crate::session::Session;
use crate::util::nodemap::{DefIdMap, FxHashMap, FxHashSet, HirIdMap, HirIdSet}; use crate::util::nodemap::{DefIdMap, FxHashMap, FxHashSet, HirIdMap, HirIdSet};
use errors::{Applicability, DiagnosticBuilder}; use errors::{Applicability, DiagnosticBuilder, pluralise};
use rustc_macros::HashStable; use rustc_macros::HashStable;
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::Cell; use std::cell::Cell;
@ -3047,7 +3047,7 @@ pub fn report_missing_lifetime_specifiers(
span, span,
E0106, E0106,
"missing lifetime specifier{}", "missing lifetime specifier{}",
if count > 1 { "s" } else { "" } pluralise!(count)
) )
} }

View file

@ -33,7 +33,7 @@ use crate::ty::subst::Subst;
use crate::ty::SubtypePredicate; use crate::ty::SubtypePredicate;
use crate::util::nodemap::{FxHashMap, FxHashSet}; use crate::util::nodemap::{FxHashMap, FxHashSet};
use errors::{Applicability, DiagnosticBuilder}; use errors::{Applicability, DiagnosticBuilder, pluralise};
use std::fmt; use std::fmt;
use syntax::ast; use syntax::ast;
use syntax::symbol::{sym, kw}; use syntax::symbol::{sym, kw};
@ -1214,7 +1214,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
_ => format!("{} {}argument{}", _ => format!("{} {}argument{}",
arg_length, arg_length,
if distinct && arg_length > 1 { "distinct " } else { "" }, if distinct && arg_length > 1 { "distinct " } else { "" },
if arg_length == 1 { "" } else { "s" }), pluralise!(arg_length))
} }
}; };

View file

@ -196,7 +196,7 @@ impl<'tcx> ty::TyS<'tcx> {
let n = tcx.lift_to_global(&n).unwrap(); let n = tcx.lift_to_global(&n).unwrap();
match n.try_eval_usize(tcx, ty::ParamEnv::empty()) { match n.try_eval_usize(tcx, ty::ParamEnv::empty()) {
Some(n) => { Some(n) => {
format!("array of {} element{}", n, if n != 1 { "s" } else { "" }).into() format!("array of {} element{}", n, pluralise!(n)).into()
} }
None => "array".into(), None => "array".into(),
} }

View file

@ -9,7 +9,7 @@ use lint::{LintPass, EarlyLintPass, LateLintPass};
use syntax::ast; use syntax::ast;
use syntax::attr; use syntax::attr;
use syntax::errors::Applicability; use syntax::errors::{Applicability, pluralise};
use syntax::feature_gate::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP}; use syntax::feature_gate::{AttributeType, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP};
use syntax::print::pprust; use syntax::print::pprust;
use syntax::symbol::{kw, sym}; use syntax::symbol::{kw, sym};
@ -48,7 +48,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
} }
let ty = cx.tables.expr_ty(&expr); let ty = cx.tables.expr_ty(&expr);
let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", false); let type_permits_lack_of_use = check_must_use_ty(cx, ty, &expr, s.span, "", "", 1);
let mut fn_warned = false; let mut fn_warned = false;
let mut op_warned = false; let mut op_warned = false;
@ -135,7 +135,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
span: Span, span: Span,
descr_pre: &str, descr_pre: &str,
descr_post: &str, descr_post: &str,
plural: bool, plural_len: usize,
) -> bool { ) -> bool {
if ty.is_unit() || cx.tcx.is_ty_uninhabited_from( if ty.is_unit() || cx.tcx.is_ty_uninhabited_from(
cx.tcx.hir().get_module_parent(expr.hir_id), ty) cx.tcx.hir().get_module_parent(expr.hir_id), ty)
@ -143,13 +143,13 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
return true; return true;
} }
let plural_suffix = if plural { "s" } else { "" }; let plural_suffix = pluralise!(plural_len);
match ty.sty { match ty.sty {
ty::Adt(..) if ty.is_box() => { ty::Adt(..) if ty.is_box() => {
let boxed_ty = ty.boxed_ty(); let boxed_ty = ty.boxed_ty();
let descr_pre = &format!("{}boxed ", descr_pre); let descr_pre = &format!("{}boxed ", descr_pre);
check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural) check_must_use_ty(cx, boxed_ty, expr, span, descr_pre, descr_post, plural_len)
} }
ty::Adt(def, _) => { ty::Adt(def, _) => {
check_must_use_def(cx, def.did, span, descr_pre, descr_post) check_must_use_def(cx, def.did, span, descr_pre, descr_post)
@ -202,7 +202,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() { for (i, ty) in tys.iter().map(|k| k.expect_ty()).enumerate() {
let descr_post = &format!(" in tuple element {}", i); let descr_post = &format!(" in tuple element {}", i);
let span = *spans.get(i).unwrap_or(&span); let span = *spans.get(i).unwrap_or(&span);
if check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, plural) { if check_must_use_ty(
cx,
ty,
expr,
span,
descr_pre,
descr_post,
plural_len
) {
has_emitted = true; has_emitted = true;
} }
} }
@ -216,7 +224,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnusedResults {
descr_pre, descr_pre,
plural_suffix, plural_suffix,
); );
check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, true) check_must_use_ty(cx, ty, expr, span, descr_pre, descr_post, n as usize + 1)
} }
// Otherwise, we don't lint, to avoid false positives. // Otherwise, we don't lint, to avoid false positives.
_ => false, _ => false,

View file

@ -26,6 +26,8 @@
use crate::Resolver; use crate::Resolver;
use crate::resolve_imports::ImportDirectiveSubclass; use crate::resolve_imports::ImportDirectiveSubclass;
use errors::pluralise;
use rustc::util::nodemap::NodeMap; use rustc::util::nodemap::NodeMap;
use rustc::{lint, ty}; use rustc::{lint, ty};
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
@ -295,7 +297,7 @@ impl Resolver<'_> {
}).collect::<Vec<String>>(); }).collect::<Vec<String>>();
span_snippets.sort(); span_snippets.sort();
let msg = format!("unused import{}{}", let msg = format!("unused import{}{}",
if len > 1 { "s" } else { "" }, pluralise!(len),
if !span_snippets.is_empty() { if !span_snippets.is_empty() {
format!(": {}", span_snippets.join(", ")) format!(": {}", span_snippets.join(", "))
} else { } else {

View file

@ -11,7 +11,7 @@ use crate::{Resolver, ResolutionError, Segment, ModuleKind};
use crate::{names_to_string, module_to_string}; use crate::{names_to_string, module_to_string};
use crate::diagnostics::Suggestion; use crate::diagnostics::Suggestion;
use errors::Applicability; use errors::{Applicability, pluralise};
use rustc_data_structures::ptr_key::PtrKey; use rustc_data_structures::ptr_key::PtrKey;
use rustc::ty; use rustc::ty;
@ -728,7 +728,7 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
let msg = format!( let msg = format!(
"unresolved import{} {}", "unresolved import{} {}",
if paths.len() > 1 { "s" } else { "" }, pluralise!(paths.len()),
paths.join(", "), paths.join(", "),
); );

View file

@ -1346,7 +1346,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
span, span,
E0191, E0191,
"the value of the associated type{} {} must be specified", "the value of the associated type{} {} must be specified",
if associated_types.len() == 1 { "" } else { "s" }, pluralise!(associated_types.len()),
names, names,
); );
let (suggest, potential_assoc_types_spans) = let (suggest, potential_assoc_types_spans) =

View file

@ -17,7 +17,7 @@ use crate::util::common::ErrorReported;
use crate::util::nodemap::FxHashMap; use crate::util::nodemap::FxHashMap;
use crate::astconv::AstConv as _; use crate::astconv::AstConv as _;
use errors::{Applicability, DiagnosticBuilder}; use errors::{Applicability, DiagnosticBuilder, pluralise};
use syntax::ast; use syntax::ast;
use syntax::symbol::{Symbol, kw, sym}; use syntax::symbol::{Symbol, kw, sym};
use syntax::source_map::Span; use syntax::source_map::Span;
@ -1178,7 +1178,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
struct_span_err!(tcx.sess, span, E0063, struct_span_err!(tcx.sess, span, E0063,
"missing field{} {}{} in initializer of `{}`", "missing field{} {}{} in initializer of `{}`",
if remaining_fields.len() == 1 { "" } else { "s" }, pluralise!(remaining_fields.len()),
remaining_fields_names, remaining_fields_names,
truncated_fields_error, truncated_fields_error,
adt_ty) adt_ty)

View file

@ -5,7 +5,7 @@ use crate::check::FnCtxt;
use crate::middle::lang_items::FnOnceTraitLangItem; use crate::middle::lang_items::FnOnceTraitLangItem;
use crate::namespace::Namespace; use crate::namespace::Namespace;
use crate::util::nodemap::FxHashSet; use crate::util::nodemap::FxHashSet;
use errors::{Applicability, DiagnosticBuilder}; use errors::{Applicability, DiagnosticBuilder, pluralise};
use rustc::hir::{self, ExprKind, Node, QPath}; use rustc::hir::{self, ExprKind, Node, QPath};
use rustc::hir::def::{Res, DefKind}; use rustc::hir::def::{Res, DefKind};
use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId}; use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, DefId};
@ -560,7 +560,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let help = format!("{an}other candidate{s} {were} found in the following \ let help = format!("{an}other candidate{s} {were} found in the following \
trait{s}, perhaps add a `use` for {one_of_them}:", trait{s}, perhaps add a `use` for {one_of_them}:",
an = if candidates.len() == 1 {"an" } else { "" }, an = if candidates.len() == 1 {"an" } else { "" },
s = if candidates.len() == 1 { "" } else { "s" }, s = pluralise!(candidates.len()),
were = if candidates.len() == 1 { "was" } else { "were" }, were = if candidates.len() == 1 { "was" } else { "were" },
one_of_them = if candidates.len() == 1 { one_of_them = if candidates.len() == 1 {
"it" "it"

View file

@ -88,7 +88,7 @@ pub mod intrinsic;
mod op; mod op;
use crate::astconv::{AstConv, PathSeg}; use crate::astconv::{AstConv, PathSeg};
use errors::{Applicability, DiagnosticBuilder, DiagnosticId}; use errors::{Applicability, DiagnosticBuilder, DiagnosticId, pluralise};
use rustc::hir::{self, ExprKind, GenericArg, ItemKind, Node, PatKind, QPath}; use rustc::hir::{self, ExprKind, GenericArg, ItemKind, Node, PatKind, QPath};
use rustc::hir::def::{CtorOf, Res, DefKind}; use rustc::hir::def::{CtorOf, Res, DefKind};
use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc::hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
@ -4935,5 +4935,5 @@ fn fatally_break_rust(sess: &Session) {
} }
fn potentially_plural_count(count: usize, word: &str) -> String { fn potentially_plural_count(count: usize, word: &str) -> String {
format!("{} {}{}", count, word, if count == 1 { "" } else { "s" }) format!("{} {}{}", count, word, pluralise!(count))
} }

View file

@ -1,6 +1,6 @@
use crate::check::FnCtxt; use crate::check::FnCtxt;
use crate::util::nodemap::FxHashMap; use crate::util::nodemap::FxHashMap;
use errors::{Applicability, DiagnosticBuilder}; use errors::{Applicability, DiagnosticBuilder, pluralise};
use rustc::hir::{self, PatKind, Pat, HirId}; use rustc::hir::{self, PatKind, Pat, HirId};
use rustc::hir::def::{Res, DefKind, CtorKind}; use rustc::hir::def::{Res, DefKind, CtorKind};
use rustc::hir::pat_util::EnumerateAndAdjustIterator; use rustc::hir::pat_util::EnumerateAndAdjustIterator;
@ -684,8 +684,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
fn e0023(&self, pat_span: Span, res: Res, subpats: &'tcx [P<Pat>], fields: &[ty::FieldDef]) { fn e0023(&self, pat_span: Span, res: Res, subpats: &'tcx [P<Pat>], fields: &[ty::FieldDef]) {
let subpats_ending = if subpats.len() == 1 { "" } else { "s" }; let subpats_ending = pluralise!(subpats.len());
let fields_ending = if fields.len() == 1 { "" } else { "s" }; let fields_ending = pluralise!(fields.len());
let res_span = self.tcx.def_span(res.def_id()); let res_span = self.tcx.def_span(res.def_id());
struct_span_err!( struct_span_err!(
self.tcx.sess, self.tcx.sess,
@ -1103,10 +1103,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
E0527, E0527,
"pattern requires {} element{} but array has {}", "pattern requires {} element{} but array has {}",
min_len, min_len,
if min_len != 1 { "s" } else { "" }, pluralise!(min_len),
size, size,
) )
.span_label(span, format!("expected {} element{}", size, if size != 1 { "s" } else { "" })) .span_label(span, format!("expected {} element{}", size, pluralise!(size)))
.emit(); .emit();
} }
@ -1117,14 +1117,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
E0528, E0528,
"pattern requires at least {} element{} but array has {}", "pattern requires at least {} element{} but array has {}",
min_len, min_len,
if min_len != 1 { "s" } else { "" }, pluralise!(min_len),
size, size,
).span_label( ).span_label(
span, span,
format!( format!(
"pattern cannot match array of {} element{}", "pattern cannot match array of {} element{}",
size, size,
if size != 1 { "s" } else { "" }, pluralise!(size),
), ),
).emit(); ).emit();
} }

View file

@ -8,6 +8,7 @@ use crate::tokenstream::{DelimSpan, TokenStream, TokenTree, TreeAndJoint};
use smallvec::{smallvec, SmallVec}; use smallvec::{smallvec, SmallVec};
use errors::pluralise;
use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::Lrc; use rustc_data_structures::sync::Lrc;
use syntax_pos::hygiene::{ExpnId, Transparency}; use syntax_pos::hygiene::{ExpnId, Transparency};
@ -348,10 +349,10 @@ impl LockstepIterSize {
"meta-variable `{}` repeats {} time{}, but `{}` repeats {} time{}", "meta-variable `{}` repeats {} time{}, but `{}` repeats {} time{}",
l_id, l_id,
l_len, l_len,
if l_len != 1 { "s" } else { "" }, pluralise!(l_len),
r_id, r_id,
r_len, r_len,
if r_len != 1 { "s" } else { "" }, pluralise!(r_len),
); );
LockstepIterSize::Contradiction(msg) LockstepIterSize::Contradiction(msg)
} }

View file

@ -11,7 +11,7 @@ use crate::ptr::P;
use crate::symbol::{kw, sym}; use crate::symbol::{kw, sym};
use crate::ThinVec; use crate::ThinVec;
use crate::util::parser::AssocOp; use crate::util::parser::AssocOp;
use errors::{Applicability, DiagnosticBuilder, DiagnosticId}; use errors::{Applicability, DiagnosticBuilder, DiagnosticId, pluralise};
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use syntax_pos::{Span, DUMMY_SP, MultiSpan, SpanSnippetError}; use syntax_pos::{Span, DUMMY_SP, MultiSpan, SpanSnippetError};
use log::{debug, trace}; use log::{debug, trace};
@ -532,15 +532,15 @@ impl<'a> Parser<'a> {
self.eat_to_tokens(&[&end]); self.eat_to_tokens(&[&end]);
let span = lo.until(self.token.span); let span = lo.until(self.token.span);
let plural = number_of_gt > 1 || number_of_shr >= 1; let total_num_of_gt = number_of_gt + number_of_shr * 2;
self.diagnostic() self.diagnostic()
.struct_span_err( .struct_span_err(
span, span,
&format!("unmatched angle bracket{}", if plural { "s" } else { "" }), &format!("unmatched angle bracket{}", pluralise!(total_num_of_gt)),
) )
.span_suggestion( .span_suggestion(
span, span,
&format!("remove extra angle bracket{}", if plural { "s" } else { "" }), &format!("remove extra angle bracket{}", pluralise!(total_num_of_gt)),
String::new(), String::new(),
Applicability::MachineApplicable, Applicability::MachineApplicable,
) )

View file

@ -9,7 +9,7 @@ use crate::symbol::kw;
use std::mem; use std::mem;
use log::debug; use log::debug;
use errors::{Applicability}; use errors::{Applicability, pluralise};
/// Specifies how to parse a path. /// Specifies how to parse a path.
#[derive(Copy, Clone, PartialEq)] #[derive(Copy, Clone, PartialEq)]
@ -347,20 +347,19 @@ impl<'a> Parser<'a> {
let span = lo.with_hi( let span = lo.with_hi(
lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count) lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
); );
let plural = snapshot.unmatched_angle_bracket_count > 1;
self.diagnostic() self.diagnostic()
.struct_span_err( .struct_span_err(
span, span,
&format!( &format!(
"unmatched angle bracket{}", "unmatched angle bracket{}",
if plural { "s" } else { "" } pluralise!(snapshot.unmatched_angle_bracket_count)
), ),
) )
.span_suggestion( .span_suggestion(
span, span,
&format!( &format!(
"remove extra angle bracket{}", "remove extra angle bracket{}",
if plural { "s" } else { "" } pluralise!(snapshot.unmatched_angle_bracket_count)
), ),
String::new(), String::new(),
Applicability::MachineApplicable, Applicability::MachineApplicable,

View file

@ -11,7 +11,7 @@ use crate::symbol::{kw};
use rustc_target::spec::abi::Abi; use rustc_target::spec::abi::Abi;
use errors::{Applicability}; use errors::{Applicability, pluralise};
/// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`, /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
/// `IDENT<<u8 as Trait>::AssocTy>`. /// `IDENT<<u8 as Trait>::AssocTy>`.
@ -397,7 +397,7 @@ impl<'a> Parser<'a> {
} }
if !negative_bounds.is_empty() || was_negative { if !negative_bounds.is_empty() || was_negative {
let plural = negative_bounds.len() > 1; let negative_bounds_len = negative_bounds.len();
let last_span = negative_bounds.last().map(|sp| *sp); let last_span = negative_bounds.last().map(|sp| *sp);
let mut err = self.struct_span_err( let mut err = self.struct_span_err(
negative_bounds, negative_bounds,
@ -420,7 +420,7 @@ impl<'a> Parser<'a> {
} }
err.span_suggestion_hidden( err.span_suggestion_hidden(
bound_list, bound_list,
&format!("remove the trait bound{}", if plural { "s" } else { "" }), &format!("remove the trait bound{}", pluralise!(negative_bounds_len)),
new_bound_list, new_bound_list,
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );

View file

@ -5,6 +5,7 @@ use fmt_macros as parse;
use errors::DiagnosticBuilder; use errors::DiagnosticBuilder;
use errors::Applicability; use errors::Applicability;
use errors::pluralise;
use syntax::ast; use syntax::ast;
use syntax::ext::base::{self, *}; use syntax::ext::base::{self, *};
@ -299,7 +300,7 @@ impl<'a, 'b> Context<'a, 'b> {
&format!( &format!(
"{} positional argument{} in format string, but {}", "{} positional argument{} in format string, but {}",
count, count,
if count != 1 { "s" } else { "" }, pluralise!(count),
self.describe_num_args(), self.describe_num_args(),
), ),
); );