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

compiler: clippy::complexity fixes #121523

Merged
merged 1 commit into from
Feb 24, 2024
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
2 changes: 1 addition & 1 deletion compiler/rustc_ast_lowering/src/delegation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
} else {
self.tcx.fn_arg_names(sig_id).len()
};
let inputs = self.arena.alloc_from_iter((0..args_count).into_iter().map(|arg| hir::Ty {
let inputs = self.arena.alloc_from_iter((0..args_count).map(|arg| hir::Ty {
hir_id: self.next_id(),
kind: hir::TyKind::InferDelegation(sig_id, hir::InferDelegationKind::Input(arg)),
span: self.lower_span(param_span),
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1559,7 +1559,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
// A bare path doesn't need a `let` assignment, it's already a simple
// binding access.
// As a new binding wasn't added, we don't need to modify the advancing call.
sugg.push((loop_span.with_hi(pat_span.lo()), format!("while let Some(")));
sugg.push((loop_span.with_hi(pat_span.lo()), "while let Some(".to_string()));
sugg.push((
pat_span.shrink_to_hi().with_hi(head.span.lo()),
") = ".to_string(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,13 @@ impl OutlivesSuggestionBuilder {

for (r, bound) in unified.into_iter() {
if !unified_already.contains(fr) {
suggested.push(SuggestedConstraint::Equal(fr_name.clone(), bound));
suggested.push(SuggestedConstraint::Equal(fr_name, bound));
unified_already.insert(r);
}
}

if !other.is_empty() {
let other =
other.iter().map(|(_, rname)| rname.clone()).collect::<SmallVec<_>>();
let other = other.iter().map(|(_, rname)| *rname).collect::<SmallVec<_>>();
suggested.push(SuggestedConstraint::Outlives(fr_name, other))
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/diagnostics/region_errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
.iter()
.rfind(|param| param.def_id.to_def_id() == defid)
.is_some() {
suggestions.push((bounded_span.shrink_to_hi(), format!(" + 'static")));
suggestions.push((bounded_span.shrink_to_hi(), " + 'static".to_string()));
}
});
});
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_const_eval/src/interpret/intern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ pub fn intern_const_alloc_recursive<
alloc.1.mutability = base_mutability;
alloc.1.provenance().ptrs().iter().map(|&(_, prov)| prov).collect()
} else {
intern_shallow(ecx, base_alloc_id, base_mutability).unwrap().map(|prov| prov).collect()
intern_shallow(ecx, base_alloc_id, base_mutability).unwrap().collect()
};
// We need to distinguish "has just been interned" from "was already in `tcx`",
// so we track this in a separate set.
Expand Down Expand Up @@ -277,7 +277,7 @@ impl<'mir, 'tcx: 'mir, M: super::intern::CompileTimeMachine<'mir, 'tcx, !>>
// We are not doing recursive interning, so we don't currently support provenance.
// (If this assertion ever triggers, we should just implement a
// proper recursive interning loop -- or just call `intern_const_alloc_recursive`.
if !self.tcx.try_get_global_alloc(prov.alloc_id()).is_some() {
if self.tcx.try_get_global_alloc(prov.alloc_id()).is_none() {
panic!("`intern_with_temp_alloc` with nested allocations");
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_errors/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -844,7 +844,7 @@ impl DiagCtxt {
.emitted_diagnostic_codes
.iter()
.filter_map(|&code| {
if registry.try_find_description(code).is_ok().clone() {
if registry.try_find_description(code).is_ok() {
Some(code.to_string())
} else {
None
Expand Down
15 changes: 3 additions & 12 deletions compiler/rustc_expand/src/mbe/transcribe.rs
Original file line number Diff line number Diff line change
Expand Up @@ -555,23 +555,14 @@ fn count_repetitions<'a>(
) -> PResult<'a, usize> {
// Recursively count the number of matches in `matched` at given depth
// (or at the top-level of `matched` if no depth is given).
fn count<'a>(
cx: &ExtCtxt<'a>,
depth_curr: usize,
depth_max: usize,
matched: &NamedMatch,
sp: &DelimSpan,
) -> PResult<'a, usize> {
Comment on lines -558 to -564
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cx and sp were only used in recursion and thus removed

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wow that's a cool lint!

fn count<'a>(depth_curr: usize, depth_max: usize, matched: &NamedMatch) -> PResult<'a, usize> {
match matched {
MatchedTokenTree(_) | MatchedNonterminal(_) => Ok(1),
MatchedSeq(named_matches) => {
if depth_curr == depth_max {
Ok(named_matches.len())
} else {
named_matches
.iter()
.map(|elem| count(cx, depth_curr + 1, depth_max, elem, sp))
.sum()
named_matches.iter().map(|elem| count(depth_curr + 1, depth_max, elem)).sum()
}
}
}
Expand Down Expand Up @@ -612,7 +603,7 @@ fn count_repetitions<'a>(
return Err(cx.dcx().create_err(CountRepetitionMisplaced { span: sp.entire() }));
}

count(cx, depth_user, depth_max, matched, sp)
count(depth_user, depth_max, matched)
}

/// Returns a `NamedMatch` item declared on the LHS given an arbitrary [Ident]
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_typeck/src/_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,12 +401,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
{
// check that the `if` expr without `else` is the fn body's expr
if expr.span == sp {
return self.get_fn_decl(hir_id).and_then(|(_, fn_decl, _)| {
return self.get_fn_decl(hir_id).map(|(_, fn_decl, _)| {
let (ty, span) = match fn_decl.output {
hir::FnRetTy::DefaultReturn(span) => ("()".to_string(), span),
hir::FnRetTy::Return(ty) => (ty_to_string(ty), ty.span),
};
Some((span, format!("expected `{ty}` because of this return type")))
(span, format!("expected `{ty}` because of this return type"))
});
}
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,15 +846,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let item_name = item_segment.ident;
let result = self
.resolve_fully_qualified_call(span, item_name, ty.normalized, qself.span, hir_id)
.and_then(|r| {
.map(|r| {
// lint bare trait if the method is found in the trait
if span.edition().at_least_rust_2021()
&& let Some(diag) =
self.dcx().steal_diagnostic(qself.span, StashKey::TraitMissingMethod)
{
diag.emit();
}
Ok(r)
r
})
.or_else(|error| {
let guar = self
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -555,9 +555,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
{
let args = self.infcx.fresh_args_for_item(call_name.span, assoc.def_id);
let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(tcx, args);
let fn_sig =
self.instantiate_binder_with_fresh_vars(call_name.span, FnCall, fn_sig);
Some((assoc, fn_sig));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lol

Copy link
Member

@lukas-code lukas-code Feb 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this entire similar_assoc closure doesn't actually do anything except return None? It should probably be fixed or removed entirely.

return Some((assoc, fn_sig)); seems to be what the author intended here.


self.instantiate_binder_with_fresh_vars(call_name.span, FnCall, fn_sig);
}
None
};
Expand Down
23 changes: 9 additions & 14 deletions compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1061,20 +1061,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
return;
}

let scope = self
.tcx
.hir()
.parent_iter(id)
.filter(|(_, node)| {
matches!(
node,
Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
| Node::Item(_)
| Node::TraitItem(_)
| Node::ImplItem(_)
)
})
.next();
let scope = self.tcx.hir().parent_iter(id).find(|(_, node)| {
matches!(
node,
Node::Expr(Expr { kind: ExprKind::Closure(..), .. })
| Node::Item(_)
| Node::TraitItem(_)
| Node::ImplItem(_)
)
});
let in_closure =
matches!(scope, Some((_, Node::Expr(Expr { kind: ExprKind::Closure(..), .. }))));

Expand Down
8 changes: 2 additions & 6 deletions compiler/rustc_hir_typeck/src/method/suggest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,9 +370,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
};
if let Some(file) = file {
err.note(format!("the full type name has been written to '{}'", file.display()));
err.note(format!(
"consider using `--verbose` to print the full type name to the console"
));
err.note("consider using `--verbose` to print the full type name to the console");
}

err
Expand Down Expand Up @@ -497,9 +495,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {

if let Some(file) = ty_file {
err.note(format!("the full type name has been written to '{}'", file.display(),));
err.note(format!(
"consider using `--verbose` to print the full type name to the console"
));
err.note("consider using `--verbose` to print the full type name to the console");
}
if rcvr_ty.references_error() {
err.downgrade_to_delayed_bug();
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/pat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2035,7 +2035,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
slice: Option<&'tcx Pat<'tcx>>,
span: Span,
) -> Option<Ty<'tcx>> {
if !slice.is_none() {
if slice.is_some() {
return None;
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1938,7 +1938,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
"the full type name has been written to '{}'",
path.display(),
));
diag.note(format!("consider using `--verbose` to print the full type name to the console"));
diag.note("consider using `--verbose` to print the full type name to the console");
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/print/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ pub trait Printer<'tcx>: Sized {
_,
hir::CoroutineSource::Closure,
)) = self.tcx().coroutine_kind(def_id)
&& args.len() >= parent_args.len() + 1
&& args.len() > parent_args.len()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wtf

{
return self.path_generic_args(
|cx| cx.print_def_path(def_id, parent_args),
Expand Down
19 changes: 7 additions & 12 deletions compiler/rustc_mir_build/src/thir/pattern/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,19 +223,14 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
// If we are handling a range with associated constants (e.g.
// `Foo::<'a>::A..=Foo::B`), we need to put the ascriptions for the associated
// constants somewhere. Have them on the range pattern.
for ascr in [lo_ascr, hi_ascr] {
if let Some(ascription) = ascr {
kind = PatKind::AscribeUserType {
ascription,
subpattern: Box::new(Pat { span, ty, kind }),
};
}
for ascription in [lo_ascr, hi_ascr].into_iter().flatten() {
kind = PatKind::AscribeUserType {
ascription,
subpattern: Box::new(Pat { span, ty, kind }),
};
}
for inline_const in [lo_inline, hi_inline] {
if let Some(def) = inline_const {
kind =
PatKind::InlineConstant { def, subpattern: Box::new(Pat { span, ty, kind }) };
}
for def in [lo_inline, hi_inline].into_iter().flatten() {
kind = PatKind::InlineConstant { def, subpattern: Box::new(Pat { span, ty, kind }) };
}
Ok(kind)
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_parse/src/validate_attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta
// results in `ast::ExprKind::Err`. In that case we delay
// the error because an earlier error will have already
// been reported.
let msg = format!("attribute value must be a literal");
let msg = "attribute value must be a literal";
let mut err = sess.dcx.struct_span_err(expr.span, msg);
if let ast::ExprKind::Err = expr.kind {
err.downgrade_to_delayed_bug();
Expand Down
16 changes: 6 additions & 10 deletions compiler/rustc_pattern_analysis/src/constructor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -694,18 +694,14 @@ impl<Cx: TypeCx> Clone for Constructor<Cx> {
fn clone(&self) -> Self {
match self {
Constructor::Struct => Constructor::Struct,
Constructor::Variant(idx) => Constructor::Variant(idx.clone()),
Constructor::Variant(idx) => Constructor::Variant(*idx),
Constructor::Ref => Constructor::Ref,
Constructor::Slice(slice) => Constructor::Slice(slice.clone()),
Constructor::Slice(slice) => Constructor::Slice(*slice),
Constructor::UnionField => Constructor::UnionField,
Constructor::Bool(b) => Constructor::Bool(b.clone()),
Constructor::IntRange(range) => Constructor::IntRange(range.clone()),
Constructor::F32Range(lo, hi, end) => {
Constructor::F32Range(lo.clone(), hi.clone(), end.clone())
}
Constructor::F64Range(lo, hi, end) => {
Constructor::F64Range(lo.clone(), hi.clone(), end.clone())
}
Constructor::Bool(b) => Constructor::Bool(*b),
Constructor::IntRange(range) => Constructor::IntRange(*range),
Constructor::F32Range(lo, hi, end) => Constructor::F32Range(lo.clone(), *hi, *end),
Constructor::F64Range(lo, hi, end) => Constructor::F64Range(lo.clone(), *hi, *end),
Constructor::Str(value) => Constructor::Str(value.clone()),
Constructor::Opaque(inner) => Constructor::Opaque(inner.clone()),
Constructor::Or => Constructor::Or,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_resolve/src/late/diagnostics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1582,7 +1582,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
None => ("/* fields */".to_string(), Applicability::HasPlaceholders),
};
let pad = match field_ids {
Some(field_ids) if field_ids.is_empty() => "",
Some([]) => "",
_ => " ",
};
err.span_suggestion(
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_session/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1264,7 +1264,7 @@ fn validate_commandline_args_with_session_available(sess: &Session) {
// LLVM CFI using rustc LTO requires a single codegen unit.
if sess.is_sanitizer_cfi_enabled()
&& sess.lto() == config::Lto::Fat
&& !(sess.codegen_units().as_usize() == 1)
&& (sess.codegen_units().as_usize() != 1)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

amazing

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
&& (sess.codegen_units().as_usize() != 1)
&& sess.codegen_units().as_usize() != 1

Why doesn't the unused_parens lint trigger here?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the lint avoids triggering when mixed-precedence operators are involved because it can be useful to clarify them explicitly. here it's a bit silly though, yeah.

{
sess.dcx().emit_err(errors::SanitizerCfiRequiresSingleCodegenUnit);
}
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_smir/src/rustc_smir/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,10 @@ impl<'tcx> Context for TablesWrapper<'tcx> {
let crates: Vec<stable_mir::Crate> = [LOCAL_CRATE]
.iter()
.chain(tables.tcx.crates(()).iter())
.map(|crate_num| {
.filter_map(|crate_num| {
let crate_name = tables.tcx.crate_name(*crate_num).to_string();
(name == crate_name).then(|| smir_crate(tables.tcx, *crate_num))
})
.flatten()
.collect();
crates
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1283,9 +1283,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
"the full type name has been written to '{}'",
file.display()
));
err.note(format!(
"consider using `--verbose` to print full type name to the console"
));
err.note(
"consider using `--verbose` to print full type name to the console",
);
}

if imm_ref_self_ty_satisfies_pred && mut_ref_self_ty_satisfies_pred {
Expand Down Expand Up @@ -2869,9 +2869,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
"the full name for the type has been written to '{}'",
file.display(),
));
err.note(format!(
"consider using `--verbose` to print the full type name to the console"
));
err.note(
"consider using `--verbose` to print the full type name to the console",
);
}
}
ObligationCauseCode::RepeatElementCopy {
Expand Down Expand Up @@ -3339,9 +3339,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
"the full type name has been written to '{}'",
file.display(),
));
err.note(format!(
"consider using `--verbose` to print the full type name to the console"
));
err.note(
"consider using `--verbose` to print the full type name to the console",
);
}
let mut parent_predicate = parent_trait_pred;
let mut data = &data.derived;
Expand Down Expand Up @@ -3395,9 +3395,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
"the full type name has been written to '{}'",
file.display(),
));
err.note(format!(
"consider using `--verbose` to print the full type name to the console"
));
err.note(
"consider using `--verbose` to print the full type name to the console",
);
}
}
// #74711: avoid a stack overflow
Expand Down
7 changes: 2 additions & 5 deletions compiler/rustc_trait_selection/src/traits/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1031,12 +1031,9 @@ fn assemble_candidates_from_impls<'cx, 'tcx>(
{
candidate_set.mark_ambiguous();
true
} else if obligation.predicate.args.type_at(0).to_opt_closure_kind().is_some()
&& obligation.predicate.args.type_at(1).to_opt_closure_kind().is_some()
{
true
} else {
false
obligation.predicate.args.type_at(0).to_opt_closure_kind().is_some()
Comment on lines -1034 to +1035
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure whether this is really better 🤷

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think if cond { true } else { false } is kinda silly 😅

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

alone yes, but in an else if chain, keeping it consistent can be nicer

&& obligation.predicate.args.type_at(1).to_opt_closure_kind().is_some()
}
} else if lang_items.discriminant_kind_trait() == Some(trait_ref.def_id) {
match self_ty.kind() {
Expand Down
Loading