1
Fork 0

Rollup merge of #93634 - matthiaskrgr:clippy_complexity_jan_2022, r=oli-obk

compiler: clippy::complexity fixes

useless_format
map_flatten
useless_conversion
needless_bool
filter_next
clone_on_copy
needless_option_as_deref
This commit is contained in:
Matthias Krüger 2022-02-18 16:23:33 +01:00 committed by GitHub
commit a144ea1c4b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
22 changed files with 39 additions and 45 deletions

View file

@ -230,7 +230,7 @@ impl AttrItem {
} }
pub fn meta_kind(&self) -> Option<MetaItemKind> { pub fn meta_kind(&self) -> Option<MetaItemKind> {
Some(MetaItemKind::from_mac_args(&self.args)?) MetaItemKind::from_mac_args(&self.args)
} }
} }

View file

@ -823,7 +823,7 @@ fn maybe_stage_features(sess: &Session, krate: &ast::Crate) {
); );
let mut all_stable = true; let mut all_stable = true;
for ident in for ident in
attr.meta_item_list().into_iter().flatten().map(|nested| nested.ident()).flatten() attr.meta_item_list().into_iter().flatten().flat_map(|nested| nested.ident())
{ {
let name = ident.name; let name = ident.name;
let stable_since = lang_features let stable_since = lang_features

View file

@ -292,7 +292,7 @@ pub unsafe fn create_module<'ll>(
"sign-return-address-all\0".as_ptr().cast(), "sign-return-address-all\0".as_ptr().cast(),
pac_opts.leaf.into(), pac_opts.leaf.into(),
); );
let is_bkey = if pac_opts.key == PAuthKey::A { false } else { true }; let is_bkey: bool = pac_opts.key != PAuthKey::A;
llvm::LLVMRustAddModuleFlag( llvm::LLVMRustAddModuleFlag(
llmod, llmod,
llvm::LLVMModFlagBehavior::Error, llvm::LLVMModFlagBehavior::Error,

View file

@ -476,7 +476,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
mir::ProjectionElem::Subslice { from, to, from_end } => { mir::ProjectionElem::Subslice { from, to, from_end } => {
let mut subslice = cg_base.project_index(bx, bx.cx().const_usize(from as u64)); let mut subslice = cg_base.project_index(bx, bx.cx().const_usize(from as u64));
let projected_ty = let projected_ty =
PlaceTy::from_ty(cg_base.layout.ty).projection_ty(tcx, elem.clone()).ty; PlaceTy::from_ty(cg_base.layout.ty).projection_ty(tcx, *elem).ty;
subslice.layout = bx.cx().layout_of(self.monomorphize(projected_ty)); subslice.layout = bx.cx().layout_of(self.monomorphize(projected_ty));
if subslice.layout.is_unsized() { if subslice.layout.is_unsized() {

View file

@ -1039,7 +1039,7 @@ fn check_matcher_core(
)); ));
err.span_suggestion( err.span_suggestion(
span, span,
&format!("try a `pat_param` fragment specifier instead"), "try a `pat_param` fragment specifier instead",
suggestion, suggestion,
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );

View file

@ -198,7 +198,7 @@ fn deprecation_message(
} else { } else {
let since = since.as_ref().map(Symbol::as_str); let since = since.as_ref().map(Symbol::as_str);
if since.as_deref() == Some("TBD") { if since == Some("TBD") {
format!("use of {} `{}` that will be deprecated in a future Rust version", kind, path) format!("use of {} `{}` that will be deprecated in a future Rust version", kind, path)
} else { } else {
format!( format!(

View file

@ -855,7 +855,7 @@ impl<'tcx> Relate<'tcx> for ty::ProjectionPredicate<'tcx> {
) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> { ) -> RelateResult<'tcx, ty::ProjectionPredicate<'tcx>> {
Ok(ty::ProjectionPredicate { Ok(ty::ProjectionPredicate {
projection_ty: relation.relate(a.projection_ty, b.projection_ty)?, projection_ty: relation.relate(a.projection_ty, b.projection_ty)?,
term: relation.relate(a.term, b.term)?.into(), term: relation.relate(a.term, b.term)?,
}) })
} }
} }

View file

@ -210,7 +210,7 @@ impl<'tcx> TyCtxt<'tcx> {
pub fn all_impls(self, def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx { pub fn all_impls(self, def_id: DefId) -> impl Iterator<Item = DefId> + 'tcx {
let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(def_id); let TraitImpls { blanket_impls, non_blanket_impls } = self.trait_impls_of(def_id);
blanket_impls.iter().chain(non_blanket_impls.iter().map(|(_, v)| v).flatten()).cloned() blanket_impls.iter().chain(non_blanket_impls.iter().flat_map(|(_, v)| v)).cloned()
} }
} }

View file

@ -140,7 +140,7 @@ fn covered_code_regions<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Vec<&'tcx Cod
let body = mir_body(tcx, def_id); let body = mir_body(tcx, def_id);
body.basic_blocks() body.basic_blocks()
.iter() .iter()
.map(|data| { .flat_map(|data| {
data.statements.iter().filter_map(|statement| match statement.kind { data.statements.iter().filter_map(|statement| match statement.kind {
StatementKind::Coverage(box ref coverage) => { StatementKind::Coverage(box ref coverage) => {
if is_inlined(body, statement) { if is_inlined(body, statement) {
@ -152,7 +152,6 @@ fn covered_code_regions<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Vec<&'tcx Cod
_ => None, _ => None,
}) })
}) })
.flatten()
.collect() .collect()
} }

View file

@ -220,18 +220,16 @@ pub fn partition<'tcx>(
let mut cgus: Vec<_> = post_inlining.codegen_units.iter_mut().collect(); let mut cgus: Vec<_> = post_inlining.codegen_units.iter_mut().collect();
cgus.sort_by_key(|cgu| cgu.size_estimate()); cgus.sort_by_key(|cgu| cgu.size_estimate());
let dead_code_cgu = if let Some(cgu) = cgus let dead_code_cgu =
.into_iter() if let Some(cgu) = cgus.into_iter().rev().find(|cgu| {
.rev() cgu.items().iter().any(|(_, (linkage, _))| *linkage == Linkage::External)
.filter(|cgu| cgu.items().iter().any(|(_, (linkage, _))| *linkage == Linkage::External)) }) {
.next() cgu
{ } else {
cgu // If there are no CGUs that have externally linked items,
} else { // then we just pick the first CGU as a fallback.
// If there are no CGUs that have externally linked items, &mut post_inlining.codegen_units[0]
// then we just pick the first CGU as a fallback. };
&mut post_inlining.codegen_units[0]
};
dead_code_cgu.make_code_coverage_dead_code_cgu(); dead_code_cgu.make_code_coverage_dead_code_cgu();
} }

View file

@ -2156,7 +2156,7 @@ impl<'a> Parser<'a> {
| PatKind::TupleStruct(qself @ None, path, _) | PatKind::TupleStruct(qself @ None, path, _)
| PatKind::Path(qself @ None, path) => match &first_pat.kind { | PatKind::Path(qself @ None, path) => match &first_pat.kind {
PatKind::Ident(_, ident, _) => { PatKind::Ident(_, ident, _) => {
path.segments.insert(0, PathSegment::from_ident(ident.clone())); path.segments.insert(0, PathSegment::from_ident(*ident));
path.span = new_span; path.span = new_span;
show_sugg = true; show_sugg = true;
first_pat = pat; first_pat = pat;
@ -2183,8 +2183,8 @@ impl<'a> Parser<'a> {
Path { Path {
span: new_span, span: new_span,
segments: vec![ segments: vec![
PathSegment::from_ident(old_ident.clone()), PathSegment::from_ident(*old_ident),
PathSegment::from_ident(ident.clone()), PathSegment::from_ident(*ident),
], ],
tokens: None, tokens: None,
}, },
@ -2194,7 +2194,7 @@ impl<'a> Parser<'a> {
} }
PatKind::Path(old_qself, old_path) => { PatKind::Path(old_qself, old_path) => {
let mut segments = old_path.segments.clone(); let mut segments = old_path.segments.clone();
segments.push(PathSegment::from_ident(ident.clone())); segments.push(PathSegment::from_ident(*ident));
let path = PatKind::Path( let path = PatKind::Path(
old_qself.clone(), old_qself.clone(),
Path { span: new_span, segments, tokens: None }, Path { span: new_span, segments, tokens: None },

View file

@ -260,7 +260,7 @@ impl<'a> Parser<'a> {
let ate_comma = self.eat(&token::Comma); let ate_comma = self.eat(&token::Comma);
if self.eat_keyword_noexpect(kw::Where) { if self.eat_keyword_noexpect(kw::Where) {
let msg = &format!("cannot define duplicate `where` clauses on an item"); let msg = "cannot define duplicate `where` clauses on an item";
let mut err = self.struct_span_err(self.token.span, msg); let mut err = self.struct_span_err(self.token.span, msg);
err.span_label(lo, "previous `where` clause starts here"); err.span_label(lo, "previous `where` clause starts here");
err.span_suggestion_verbose( err.span_suggestion_verbose(

View file

@ -1362,8 +1362,7 @@ impl<'a> Resolver<'a> {
.filter(|(_, module)| { .filter(|(_, module)| {
current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module) current_module.is_ancestor_of(module) && !ptr::eq(current_module, *module)
}) })
.map(|(_, module)| module.kind.name()) .flat_map(|(_, module)| module.kind.name()),
.flatten(),
) )
.filter(|c| !c.to_string().is_empty()) .filter(|c| !c.to_string().is_empty())
.collect::<Vec<_>>(); .collect::<Vec<_>>();
@ -1859,7 +1858,7 @@ crate fn show_candidates(
let instead = if instead { " instead" } else { "" }; let instead = if instead { " instead" } else { "" };
let mut msg = format!("consider importing {} {}{}", determiner, kind, instead); let mut msg = format!("consider importing {} {}{}", determiner, kind, instead);
for note in accessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() { for note in accessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
err.note(note); err.note(note);
} }
@ -1942,7 +1941,7 @@ crate fn show_candidates(
multi_span.push_span_label(span, format!("`{}`: not accessible", name)); multi_span.push_span_label(span, format!("`{}`: not accessible", name));
} }
for note in inaccessible_path_strings.iter().map(|cand| cand.3.as_ref()).flatten() { for note in inaccessible_path_strings.iter().flat_map(|cand| cand.3.as_ref()) {
err.note(note); err.note(note);
} }

View file

@ -1163,7 +1163,7 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
err.span_suggestion( err.span_suggestion(
span, span,
&"use this syntax instead", &"use this syntax instead",
format!("{path_str}"), path_str.to_string(),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }

View file

@ -1437,8 +1437,7 @@ impl<'a, 'tcx> InferCtxtPrivExt<'a, 'tcx> for InferCtxt<'a, 'tcx> {
self.tcx self.tcx
.associated_items(did) .associated_items(did)
.in_definition_order() .in_definition_order()
.filter(|assoc| assoc.ident(self.tcx) == trait_assoc_ident) .find(|assoc| assoc.ident(self.tcx) == trait_assoc_ident)
.next()
}, },
) )
}) })

View file

@ -959,7 +959,7 @@ fn opt_normalize_projection_type<'a, 'b, 'tcx>(
infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone()); infcx.inner.borrow_mut().projection_cache().insert_term(cache_key, result.clone());
} }
obligations.extend(result.obligations); obligations.extend(result.obligations);
Ok(Some(result.value.into())) Ok(Some(result.value))
} }
Ok(Projected::NoProgress(projected_ty)) => { Ok(Projected::NoProgress(projected_ty)) => {
let result = Normalized { value: projected_ty, obligations: vec![] }; let result = Normalized { value: projected_ty, obligations: vec![] };

View file

@ -211,8 +211,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
); );
let all_candidate_names: Vec<_> = all_candidates() let all_candidate_names: Vec<_> = all_candidates()
.map(|r| self.tcx().associated_items(r.def_id()).in_definition_order()) .flat_map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
.flatten()
.filter_map( .filter_map(
|item| if item.kind == ty::AssocKind::Type { Some(item.name) } else { None }, |item| if item.kind == ty::AssocKind::Type { Some(item.name) } else { None },
) )

View file

@ -392,7 +392,7 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b
"when the type does not implement `Copy`, \ "when the type does not implement `Copy`, \
wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped", wrap it inside a `ManuallyDrop<_>` and ensure it is manually dropped",
vec![ vec![
(ty_span.shrink_to_lo(), format!("std::mem::ManuallyDrop<")), (ty_span.shrink_to_lo(), "std::mem::ManuallyDrop<".into()),
(ty_span.shrink_to_hi(), ">".into()), (ty_span.shrink_to_hi(), ">".into()),
], ],
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,

View file

@ -340,7 +340,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) { let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
Some(ident) => format!("{}: ", ident), Some(ident) => format!("{}: ", ident),
None => format!(""), None => String::new(),
}; };
match &compatible_variants[..] { match &compatible_variants[..] {
@ -683,7 +683,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) { let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
Some(ident) => format!("{}: ", ident), Some(ident) => format!("{}: ", ident),
None => format!(""), None => String::new(),
}; };
if let Some(hir::Node::Expr(hir::Expr { if let Some(hir::Node::Expr(hir::Expr {
@ -875,7 +875,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}; };
let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) { let prefix = match self.maybe_get_struct_pattern_shorthand_field(expr) {
Some(ident) => format!("{}: ", ident), Some(ident) => format!("{}: ", ident),
None => format!(""), None => String::new(),
}; };
let (span, suggestion) = if self.is_else_if_block(expr) { let (span, suggestion) = if self.is_else_if_block(expr) {
// Don't suggest nonsense like `else *if` // Don't suggest nonsense like `else *if`

View file

@ -246,7 +246,7 @@ impl DropRangesBuilder {
fn add_control_edge(&mut self, from: PostOrderId, to: PostOrderId) { fn add_control_edge(&mut self, from: PostOrderId, to: PostOrderId) {
trace!("adding control edge from {:?} to {:?}", from, to); trace!("adding control edge from {:?} to {:?}", from, to);
self.node_mut(from.into()).successors.push(to.into()); self.node_mut(from).successors.push(to);
} }
} }

View file

@ -527,7 +527,7 @@ impl DropRangesBuilder {
fn drop_at(&mut self, value: TrackedValue, location: PostOrderId) { fn drop_at(&mut self, value: TrackedValue, location: PostOrderId) {
let value = self.tracked_value_index(value); let value = self.tracked_value_index(value);
self.node_mut(location.into()).drops.push(value); self.node_mut(location).drops.push(value);
} }
fn reinit_at(&mut self, value: TrackedValue, location: PostOrderId) { fn reinit_at(&mut self, value: TrackedValue, location: PostOrderId) {
@ -537,7 +537,7 @@ impl DropRangesBuilder {
// ignore this. // ignore this.
None => return, None => return,
}; };
self.node_mut(location.into()).reinits.push(value); self.node_mut(location).reinits.push(value);
} }
/// Looks up PostOrderId for any control edges added by HirId and adds a proper edge for them. /// Looks up PostOrderId for any control edges added by HirId and adds a proper edge for them.

View file

@ -527,7 +527,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
// FIXME(associated_const_equality): add a useful error message here. // FIXME(associated_const_equality): add a useful error message here.
tcx.ty_error_with_message( tcx.ty_error_with_message(
DUMMY_SP, DUMMY_SP,
&format!("Could not find associated const on trait"), "Could not find associated const on trait",
) )
} }
} }