1
Fork 0

clippy fixes for librustdoc

fixes clippy warnings of type:
match_like_matches_macro
or_fun_call
op_ref
needless_return
let_and_return
single_char_add_str
useless_format
unnecessary_sort_by
match_ref_pats
redundant_field_names
This commit is contained in:
Matthias Krüger 2020-12-31 02:49:44 +01:00
parent a609fb45ef
commit a5807ac61c
15 changed files with 58 additions and 88 deletions

View file

@ -738,11 +738,11 @@ impl<'a, 'tcx> AutoTraitFinder<'a, 'tcx> {
} }
fn is_fn_ty(&self, tcx: TyCtxt<'_>, ty: &Type) -> bool { fn is_fn_ty(&self, tcx: TyCtxt<'_>, ty: &Type) -> bool {
match &ty { match ty {
&&Type::ResolvedPath { ref did, .. } => { &Type::ResolvedPath { did, .. } => {
*did == tcx.require_lang_item(LangItem::Fn, None) did == tcx.require_lang_item(LangItem::Fn, None)
|| *did == tcx.require_lang_item(LangItem::FnMut, None) || did == tcx.require_lang_item(LangItem::FnMut, None)
|| *did == tcx.require_lang_item(LangItem::FnOnce, None) || did == tcx.require_lang_item(LangItem::FnOnce, None)
} }
_ => false, _ => false,
} }

View file

@ -177,10 +177,7 @@ impl Cfg {
Cfg::Any(ref sub_cfgs) | Cfg::All(ref sub_cfgs) => { Cfg::Any(ref sub_cfgs) | Cfg::All(ref sub_cfgs) => {
sub_cfgs.first().map(Cfg::should_capitalize_first_letter).unwrap_or(false) sub_cfgs.first().map(Cfg::should_capitalize_first_letter).unwrap_or(false)
} }
Cfg::Cfg(name, _) => match name { Cfg::Cfg(name, _) => name == sym::debug_assertions || name == sym::target_endian,
sym::debug_assertions | sym::target_endian => true,
_ => false,
},
} }
} }
@ -188,18 +185,13 @@ impl Cfg {
match *self { match *self {
Cfg::False | Cfg::True => false, Cfg::False | Cfg::True => false,
Cfg::Any(..) | Cfg::All(..) | Cfg::Cfg(..) => true, Cfg::Any(..) | Cfg::All(..) | Cfg::Cfg(..) => true,
Cfg::Not(ref child) => match **child { Cfg::Not(box Cfg::Cfg(..)) => true,
Cfg::Cfg(..) => true, Cfg::Not(..) => false,
_ => false,
},
} }
} }
fn should_use_with_in_description(&self) -> bool { fn should_use_with_in_description(&self) -> bool {
match *self { matches!(self, Cfg::Cfg(sym::target_feature, _))
Cfg::Cfg(name, _) if name == sym::target_feature => true,
_ => false,
}
} }
/// Attempt to simplify this cfg by assuming that `assume` is already known to be true, will /// Attempt to simplify this cfg by assuming that `assume` is already known to be true, will

View file

@ -640,10 +640,10 @@ impl Clean<Generics> for hir::Generics<'_> {
/// ///
/// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param /// [`lifetime_to_generic_param`]: rustc_ast_lowering::LoweringContext::lifetime_to_generic_param
fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool { fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool {
match param.kind { matches!(
hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided } => true, param.kind,
_ => false, hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided }
} )
} }
let impl_trait_params = self let impl_trait_params = self
@ -801,7 +801,7 @@ impl<'a, 'tcx> Clean<Generics> for (&'a ty::Generics, ty::GenericPredicates<'tcx
for (param, mut bounds) in impl_trait { for (param, mut bounds) in impl_trait {
// Move trait bounds to the front. // Move trait bounds to the front.
bounds.sort_by_key(|b| if let GenericBound::TraitBound(..) = b { false } else { true }); bounds.sort_by_key(|b| !matches!(b, GenericBound::TraitBound(..)));
if let crate::core::ImplTraitParam::ParamIndex(idx) = param { if let crate::core::ImplTraitParam::ParamIndex(idx) = param {
if let Some(proj) = impl_trait_proj.remove(&idx) { if let Some(proj) = impl_trait_proj.remove(&idx) {

View file

@ -175,11 +175,9 @@ impl Item {
} }
crate fn is_crate(&self) -> bool { crate fn is_crate(&self) -> bool {
match *self.kind { matches!(*self.kind,
StrippedItem(box ModuleItem(Module { is_crate: true, .. })) StrippedItem(box ModuleItem(Module { is_crate: true, .. }))
| ModuleItem(Module { is_crate: true, .. }) => true, | ModuleItem(Module { is_crate: true, .. }))
_ => false,
}
} }
crate fn is_mod(&self) -> bool { crate fn is_mod(&self) -> bool {
self.type_() == ItemType::Module self.type_() == ItemType::Module
@ -378,10 +376,7 @@ impl ItemKind {
} }
crate fn is_type_alias(&self) -> bool { crate fn is_type_alias(&self) -> bool {
match *self { matches!(self, ItemKind::TypedefItem(..) | ItemKind::AssocTypeItem(..))
ItemKind::TypedefItem(_, _) | ItemKind::AssocTypeItem(_, _) => true,
_ => false,
}
} }
} }
@ -674,7 +669,7 @@ impl Attributes {
span: attr.span, span: attr.span,
doc: contents, doc: contents,
kind: DocFragmentKind::Include { filename }, kind: DocFragmentKind::Include { filename },
parent_module: parent_module, parent_module,
}); });
} }
} }
@ -750,7 +745,7 @@ impl Attributes {
Some(did) => { Some(did) => {
if let Some((mut href, ..)) = href(did) { if let Some((mut href, ..)) = href(did) {
if let Some(ref fragment) = *fragment { if let Some(ref fragment) = *fragment {
href.push_str("#"); href.push('#');
href.push_str(fragment); href.push_str(fragment);
} }
Some(RenderedLink { Some(RenderedLink {
@ -945,10 +940,7 @@ crate enum GenericParamDefKind {
impl GenericParamDefKind { impl GenericParamDefKind {
crate fn is_type(&self) -> bool { crate fn is_type(&self) -> bool {
match *self { matches!(self, GenericParamDefKind::Type { .. })
GenericParamDefKind::Type { .. } => true,
_ => false,
}
} }
// FIXME(eddyb) this either returns the default of a type parameter, or the // FIXME(eddyb) this either returns the default of a type parameter, or the
@ -1292,15 +1284,12 @@ impl Type {
} }
crate fn is_full_generic(&self) -> bool { crate fn is_full_generic(&self) -> bool {
match *self { matches!(self, Type::Generic(_))
Type::Generic(_) => true,
_ => false,
}
} }
crate fn projection(&self) -> Option<(&Type, DefId, Symbol)> { crate fn projection(&self) -> Option<(&Type, DefId, Symbol)> {
let (self_, trait_, name) = match self { let (self_, trait_, name) = match self {
QPath { ref self_type, ref trait_, name } => (self_type, trait_, name), QPath { self_type, trait_, name } => (self_type, trait_, name),
_ => return None, _ => return None,
}; };
let trait_did = match **trait_ { let trait_did = match **trait_ {

View file

@ -37,10 +37,7 @@ crate enum OutputFormat {
impl OutputFormat { impl OutputFormat {
crate fn is_json(&self) -> bool { crate fn is_json(&self) -> bool {
match self { matches!(self, OutputFormat::Json)
OutputFormat::Json => true,
_ => false,
}
} }
} }

View file

@ -636,15 +636,15 @@ fn partition_source(s: &str) -> (String, String, String) {
match state { match state {
PartitionState::Attrs => { PartitionState::Attrs => {
before.push_str(line); before.push_str(line);
before.push_str("\n"); before.push('\n');
} }
PartitionState::Crates => { PartitionState::Crates => {
crates.push_str(line); crates.push_str(line);
crates.push_str("\n"); crates.push('\n');
} }
PartitionState::Other => { PartitionState::Other => {
after.push_str(line); after.push_str(line);
after.push_str("\n"); after.push('\n');
} }
} }
} }

View file

@ -61,7 +61,7 @@ crate trait DocFolder: Sized {
j.fields = j.fields.into_iter().filter_map(|x| self.fold_item(x)).collect(); j.fields = j.fields.into_iter().filter_map(|x| self.fold_item(x)).collect();
j.fields_stripped |= num_fields != j.fields.len() j.fields_stripped |= num_fields != j.fields.len()
|| j.fields.iter().any(|f| f.is_stripped()); || j.fields.iter().any(|f| f.is_stripped());
VariantItem(Variant { kind: VariantKind::Struct(j), ..i2 }) VariantItem(Variant { kind: VariantKind::Struct(j) })
} }
_ => VariantItem(i2), _ => VariantItem(i2),
} }

View file

@ -245,7 +245,7 @@ impl<'a> fmt::Display for WhereClause<'a> {
} }
match pred { match pred {
&clean::WherePredicate::BoundPredicate { ref ty, ref bounds } => { clean::WherePredicate::BoundPredicate { ty, bounds } => {
let bounds = bounds; let bounds = bounds;
if f.alternate() { if f.alternate() {
clause.push_str(&format!( clause.push_str(&format!(
@ -261,7 +261,7 @@ impl<'a> fmt::Display for WhereClause<'a> {
)); ));
} }
} }
&clean::WherePredicate::RegionPredicate { ref lifetime, ref bounds } => { clean::WherePredicate::RegionPredicate { lifetime, bounds } => {
clause.push_str(&format!( clause.push_str(&format!(
"{}: {}", "{}: {}",
lifetime.print(), lifetime.print(),
@ -272,7 +272,7 @@ impl<'a> fmt::Display for WhereClause<'a> {
.join(" + ") .join(" + ")
)); ));
} }
&clean::WherePredicate::EqPredicate { ref lhs, ref rhs } => { clean::WherePredicate::EqPredicate { lhs, rhs } => {
if f.alternate() { if f.alternate() {
clause.push_str(&format!("{:#} == {:#}", lhs.print(), rhs.print())); clause.push_str(&format!("{:#} == {:#}", lhs.print(), rhs.print()));
} else { } else {
@ -376,8 +376,8 @@ impl clean::GenericBound {
impl clean::GenericArgs { impl clean::GenericArgs {
fn print(&self) -> impl fmt::Display + '_ { fn print(&self) -> impl fmt::Display + '_ {
display_fn(move |f| { display_fn(move |f| {
match *self { match self {
clean::GenericArgs::AngleBracketed { ref args, ref bindings } => { clean::GenericArgs::AngleBracketed { args, bindings } => {
if !args.is_empty() || !bindings.is_empty() { if !args.is_empty() || !bindings.is_empty() {
if f.alternate() { if f.alternate() {
f.write_str("<")?; f.write_str("<")?;
@ -414,7 +414,7 @@ impl clean::GenericArgs {
} }
} }
} }
clean::GenericArgs::Parenthesized { ref inputs, ref output } => { clean::GenericArgs::Parenthesized { inputs, output } => {
f.write_str("(")?; f.write_str("(")?;
let mut comma = false; let mut comma = false;
for ty in inputs { for ty in inputs {
@ -501,7 +501,7 @@ crate fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
}; };
for component in &fqp[..fqp.len() - 1] { for component in &fqp[..fqp.len() - 1] {
url.push_str(component); url.push_str(component);
url.push_str("/"); url.push('/');
} }
match shortty { match shortty {
ItemType::Module => { ItemType::Module => {
@ -510,7 +510,7 @@ crate fn href(did: DefId) -> Option<(String, ItemType, Vec<String>)> {
} }
_ => { _ => {
url.push_str(shortty.as_str()); url.push_str(shortty.as_str());
url.push_str("."); url.push('.');
url.push_str(fqp.last().unwrap()); url.push_str(fqp.last().unwrap());
url.push_str(".html"); url.push_str(".html");
} }
@ -1021,7 +1021,7 @@ impl Function<'_> {
} else { } else {
if i > 0 { if i > 0 {
args.push_str(" <br>"); args.push_str(" <br>");
args_plain.push_str(" "); args_plain.push(' ');
} }
if !input.name.is_empty() { if !input.name.is_empty() {
args.push_str(&format!("{}: ", input.name)); args.push_str(&format!("{}: ", input.name));

View file

@ -489,15 +489,10 @@ impl<'a, I: Iterator<Item = Event<'a>>> SummaryLine<'a, I> {
} }
fn check_if_allowed_tag(t: &Tag<'_>) -> bool { fn check_if_allowed_tag(t: &Tag<'_>) -> bool {
match *t { matches!(
Tag::Paragraph t,
| Tag::Item Tag::Paragraph | Tag::Item | Tag::Emphasis | Tag::Strong | Tag::Link(..) | Tag::BlockQuote
| Tag::Emphasis )
| Tag::Strong
| Tag::Link(..)
| Tag::BlockQuote => true,
_ => false,
}
} }
impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> { impl<'a, I: Iterator<Item = Event<'a>>> Iterator for SummaryLine<'a, I> {

View file

@ -979,7 +979,7 @@ themePicker.onblur = handleThemeButtonsBlur;
.iter() .iter()
.map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion"))) .map(|s| format!("\"{}\"", s.to_str().expect("invalid osstring conversion")))
.collect::<Vec<_>>(); .collect::<Vec<_>>();
files.sort_unstable_by(|a, b| a.cmp(b)); files.sort_unstable();
let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(","); let subs = subs.iter().map(|s| s.to_json_string()).collect::<Vec<_>>().join(",");
let dirs = let dirs =
if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) }; if subs.is_empty() { String::new() } else { format!(",\"dirs\":[{}]", subs) };
@ -1428,7 +1428,7 @@ impl Setting {
.map(|opt| format!( .map(|opt| format!(
"<option value=\"{}\" {}>{}</option>", "<option value=\"{}\" {}>{}</option>",
opt.0, opt.0,
if &opt.0 == default_value { "selected" } else { "" }, if opt.0 == default_value { "selected" } else { "" },
opt.1, opt.1,
)) ))
.collect::<String>(), .collect::<String>(),
@ -1595,7 +1595,7 @@ impl Context<'_> {
if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) { if let Some(&(ref names, ty)) = cache.paths.get(&it.def_id) {
for name in &names[..names.len() - 1] { for name in &names[..names.len() - 1] {
url.push_str(name); url.push_str(name);
url.push_str("/"); url.push('/');
} }
url.push_str(&item_path(ty, names.last().unwrap())); url.push_str(&item_path(ty, names.last().unwrap()));
layout::redirect(&url) layout::redirect(&url)
@ -2308,7 +2308,7 @@ fn short_item_info(
let since = &since.as_str(); let since = &since.as_str();
if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) { if !stability::deprecation_in_effect(is_since_rustc_version, Some(since)) {
if *since == "TBD" { if *since == "TBD" {
format!("Deprecating in a future Rust version") String::from("Deprecating in a future Rust version")
} else { } else {
format!("Deprecating in {}", Escape(since)) format!("Deprecating in {}", Escape(since))
} }
@ -4323,9 +4323,11 @@ fn sidebar_assoc_items(it: &clean::Item) -> String {
.any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did); .any(|i| i.inner_impl().trait_.def_id() == c.deref_mut_trait_did);
let inner_impl = target let inner_impl = target
.def_id() .def_id()
.or(target .or_else(|| {
.primitive_type() target
.and_then(|prim| c.primitive_locations.get(&prim).cloned())) .primitive_type()
.and_then(|prim| c.primitive_locations.get(&prim).cloned())
})
.and_then(|did| c.impls.get(&did)); .and_then(|did| c.impls.get(&did));
if let Some(impls) = inner_impl { if let Some(impls) = inner_impl {
out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">"); out.push_str("<a class=\"sidebar-title\" href=\"#deref-methods\">");

View file

@ -132,7 +132,7 @@ impl TocBuilder {
} }
Some(entry) => { Some(entry) => {
sec_number = entry.sec_number.clone(); sec_number = entry.sec_number.clone();
sec_number.push_str("."); sec_number.push('.');
(entry.level, &entry.children) (entry.level, &entry.children)
} }
}; };

View file

@ -1276,7 +1276,7 @@ impl LinkCollector<'_, '_> {
// This could just be a normal link or a broken link // This could just be a normal link or a broken link
// we could potentially check if something is // we could potentially check if something is
// "intra-doc-link-like" and warn in that case. // "intra-doc-link-like" and warn in that case.
return None; None
} }
Err(ErrorKind::AnchorFailure(msg)) => { Err(ErrorKind::AnchorFailure(msg)) => {
anchor_failure( anchor_failure(
@ -1287,7 +1287,7 @@ impl LinkCollector<'_, '_> {
diag.link_range, diag.link_range,
msg, msg,
); );
return None; None
} }
} }
} }
@ -1383,7 +1383,7 @@ impl LinkCollector<'_, '_> {
diag.link_range, diag.link_range,
candidates.present_items().collect(), candidates.present_items().collect(),
); );
return None; None
} }
} }
Some(MacroNS) => { Some(MacroNS) => {
@ -1408,7 +1408,7 @@ impl LinkCollector<'_, '_> {
diag.link_range, diag.link_range,
smallvec![kind], smallvec![kind],
); );
return None; None
} }
} }
} }

View file

@ -59,7 +59,7 @@ fn drop_tag(
continue; continue;
} }
let last_tag_name_low = last_tag_name.to_lowercase(); let last_tag_name_low = last_tag_name.to_lowercase();
if ALLOWED_UNCLOSED.iter().any(|&at| at == &last_tag_name_low) { if ALLOWED_UNCLOSED.iter().any(|&at| at == last_tag_name_low) {
continue; continue;
} }
// `tags` is used as a queue, meaning that everything after `pos` is included inside it. // `tags` is used as a queue, meaning that everything after `pos` is included inside it.

View file

@ -26,9 +26,7 @@ crate fn strip_hidden(krate: clean::Crate, _: &DocContext<'_>) -> clean::Crate {
// strip all impls referencing stripped items // strip all impls referencing stripped items
let mut stripper = ImplStripper { retained: &retained }; let mut stripper = ImplStripper { retained: &retained };
let krate = stripper.fold_crate(krate); stripper.fold_crate(krate)
krate
} }
struct Stripper<'a> { struct Stripper<'a> {

View file

@ -70,15 +70,12 @@ impl Events {
} }
fn is_comment(&self) -> bool { fn is_comment(&self) -> bool {
match *self { matches!(self, Events::StartLineComment(_) | Events::StartComment(_) | Events::EndComment(_))
Events::StartLineComment(_) | Events::StartComment(_) | Events::EndComment(_) => true,
_ => false,
}
} }
} }
fn previous_is_line_comment(events: &[Events]) -> bool { fn previous_is_line_comment(events: &[Events]) -> bool {
if let Some(&Events::StartLineComment(_)) = events.last() { true } else { false } matches!(events.last(), Some(&Events::StartLineComment(_)))
} }
fn is_line_comment(pos: usize, v: &[u8], events: &[Events]) -> bool { fn is_line_comment(pos: usize, v: &[u8], events: &[Events]) -> bool {