Skip to content

Commit 80932be

Browse files
committed
Auto merge of #12667 - Eh2406:clippy, r=weihanglo
Clippy ### What does this PR try to resolve? A few more small anti-patterns from our code base. Each in their own commit, found by turning on a clippy warning and manually reviewing the changes. Most of the changes are from switching to `let-else`. ### How should we test and review this PR? Internal refactoring and tests still pass. ### Additional information I know we don't like "fix clippy" PR's. Sorry. On the other hand having reviewed for these lints, I wouldn't mind turning them to warn. 🤷
2 parents 8d43632 + afe5333 commit 80932be

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+280
-392
lines changed

src/cargo/core/compiler/build_config.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use cargo_util::ProcessBuilder;
77
use serde::ser;
88
use std::cell::RefCell;
99
use std::path::PathBuf;
10-
use std::sync::Arc;
10+
use std::rc::Rc;
1111
use std::thread::available_parallelism;
1212

1313
/// Configuration information for a rustc build.
@@ -35,7 +35,7 @@ pub struct BuildConfig {
3535
pub primary_unit_rustc: Option<ProcessBuilder>,
3636
/// A thread used by `cargo fix` to receive messages on a socket regarding
3737
/// the success/failure of applying fixes.
38-
pub rustfix_diagnostic_server: Arc<RefCell<Option<RustfixDiagnosticServer>>>,
38+
pub rustfix_diagnostic_server: Rc<RefCell<Option<RustfixDiagnosticServer>>>,
3939
/// The directory to copy final artifacts to. Note that even if `out_dir` is
4040
/// set, a copy of artifacts still could be found a `target/(debug\release)`
4141
/// as usual.
@@ -113,7 +113,7 @@ impl BuildConfig {
113113
build_plan: false,
114114
unit_graph: false,
115115
primary_unit_rustc: None,
116-
rustfix_diagnostic_server: Arc::new(RefCell::new(None)),
116+
rustfix_diagnostic_server: Rc::new(RefCell::new(None)),
117117
export_dir: None,
118118
future_incompat_report: false,
119119
timing_outputs: Vec::new(),

src/cargo/core/compiler/build_context/target_info.rs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -367,9 +367,8 @@ impl TargetInfo {
367367
&*v.insert(value)
368368
}
369369
};
370-
let (prefix, suffix) = match *crate_type_info {
371-
Some((ref prefix, ref suffix)) => (prefix, suffix),
372-
None => return Ok(None),
370+
let Some((prefix, suffix)) = crate_type_info else {
371+
return Ok(None);
373372
};
374373
let mut ret = vec![FileType {
375374
suffix: suffix.clone(),
@@ -612,13 +611,12 @@ fn parse_crate_type(
612611
if not_supported {
613612
return Ok(None);
614613
}
615-
let line = match lines.next() {
616-
Some(line) => line,
617-
None => anyhow::bail!(
614+
let Some(line) = lines.next() else {
615+
anyhow::bail!(
618616
"malformed output when learning about crate-type {} information\n{}",
619617
crate_type,
620618
output_err_info(cmd, output, error)
621-
),
619+
)
622620
};
623621
let mut parts = line.trim().split("___");
624622
let prefix = parts.next().unwrap();
@@ -978,9 +976,8 @@ impl<'cfg> RustcTargetData<'cfg> {
978976
pub fn dep_platform_activated(&self, dep: &Dependency, kind: CompileKind) -> bool {
979977
// If this dependency is only available for certain platforms,
980978
// make sure we're only enabling it for that platform.
981-
let platform = match dep.platform() {
982-
Some(p) => p,
983-
None => return true,
979+
let Some(platform) = dep.platform() else {
980+
return true;
984981
};
985982
let name = self.short_name(&kind);
986983
platform.matches(name, self.cfg(kind))
@@ -1058,13 +1055,12 @@ impl RustDocFingerprint {
10581055
serde_json::to_string(&actual_rustdoc_target_data)?,
10591056
)
10601057
};
1061-
let rustdoc_data = match paths::read(&fingerprint_path) {
1062-
Ok(rustdoc_data) => rustdoc_data,
1058+
let Ok(rustdoc_data) = paths::read(&fingerprint_path) else {
10631059
// If the fingerprint does not exist, do not clear out the doc
10641060
// directories. Otherwise this ran into problems where projects
10651061
// like rustbuild were creating the doc directory before running
10661062
// `cargo doc` in a way that deleting it would break it.
1067-
Err(_) => return write_fingerprint(),
1063+
return write_fingerprint();
10681064
};
10691065
match serde_json::from_str::<RustDocFingerprint>(&rustdoc_data) {
10701066
Ok(fingerprint) => {

src/cargo/core/compiler/build_plan.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,10 +86,7 @@ impl Invocation {
8686
);
8787
}
8888
for (var, value) in cmd.get_envs() {
89-
let value = match value {
90-
Some(s) => s,
91-
None => continue,
92-
};
89+
let Some(value) = value else { continue };
9390
self.env.insert(
9491
var.clone(),
9592
value

src/cargo/core/compiler/custom_build.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,7 @@ fn build_work(cx: &mut Context<'_, '_>, unit: &Unit) -> CargoResult<Job> {
443443
))
444444
})?;
445445
let data = &script_output.metadata;
446-
for &(ref key, ref value) in data.iter() {
446+
for (key, value) in data.iter() {
447447
cmd.env(
448448
&format!("DEP_{}_{}", super::envify(&name), super::envify(key)),
449449
value,

src/cargo/core/compiler/fingerprint/mod.rs

Lines changed: 22 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -811,9 +811,8 @@ impl LocalFingerprint {
811811
// rustc.
812812
LocalFingerprint::CheckDepInfo { dep_info } => {
813813
let dep_info = target_root.join(dep_info);
814-
let info = match parse_dep_info(pkg_root, target_root, &dep_info)? {
815-
Some(info) => info,
816-
None => return Ok(Some(StaleItem::MissingFile(dep_info))),
814+
let Some(info) = parse_dep_info(pkg_root, target_root, &dep_info)? else {
815+
return Ok(Some(StaleItem::MissingFile(dep_info)));
817816
};
818817
for (key, previous) in info.env.iter() {
819818
let current = if key == CARGO_ENV {
@@ -1038,16 +1037,16 @@ impl Fingerprint {
10381037
for (a, b) in self.deps.iter().zip(old.deps.iter()) {
10391038
if a.name != b.name {
10401039
return DirtyReason::UnitDependencyNameChanged {
1041-
old: b.name.clone(),
1042-
new: a.name.clone(),
1040+
old: b.name,
1041+
new: a.name,
10431042
};
10441043
}
10451044

10461045
if a.fingerprint.hash_u64() != b.fingerprint.hash_u64() {
10471046
return DirtyReason::UnitDependencyInfoChanged {
1048-
new_name: a.name.clone(),
1047+
new_name: a.name,
10491048
new_fingerprint: a.fingerprint.hash_u64(),
1050-
old_name: b.name.clone(),
1049+
old_name: b.name,
10511050
old_fingerprint: b.fingerprint.hash_u64(),
10521051
};
10531052
}
@@ -1103,16 +1102,12 @@ impl Fingerprint {
11031102
}
11041103

11051104
let opt_max = mtimes.iter().max_by_key(|kv| kv.1);
1106-
let (max_path, max_mtime) = match opt_max {
1107-
Some(mtime) => mtime,
1108-
1105+
let Some((max_path, max_mtime)) = opt_max else {
11091106
// We had no output files. This means we're an overridden build
11101107
// script and we're just always up to date because we aren't
11111108
// watching the filesystem.
1112-
None => {
1113-
self.fs_status = FsStatus::UpToDate { mtimes };
1114-
return Ok(());
1115-
}
1109+
self.fs_status = FsStatus::UpToDate { mtimes };
1110+
return Ok(());
11161111
};
11171112
debug!(
11181113
"max output mtime for {:?} is {:?} {}",
@@ -1127,9 +1122,7 @@ impl Fingerprint {
11271122
| FsStatus::StaleItem(_)
11281123
| FsStatus::StaleDependency { .. }
11291124
| FsStatus::StaleDepFingerprint { .. } => {
1130-
self.fs_status = FsStatus::StaleDepFingerprint {
1131-
name: dep.name.clone(),
1132-
};
1125+
self.fs_status = FsStatus::StaleDepFingerprint { name: dep.name };
11331126
return Ok(());
11341127
}
11351128
};
@@ -1171,7 +1164,7 @@ impl Fingerprint {
11711164
);
11721165

11731166
self.fs_status = FsStatus::StaleDependency {
1174-
name: dep.name.clone(),
1167+
name: dep.name,
11751168
dep_mtime: *dep_mtime,
11761169
max_mtime: *max_mtime,
11771170
};
@@ -1808,16 +1801,12 @@ pub fn parse_dep_info(
18081801
target_root: &Path,
18091802
dep_info: &Path,
18101803
) -> CargoResult<Option<RustcDepInfo>> {
1811-
let data = match paths::read_bytes(dep_info) {
1812-
Ok(data) => data,
1813-
Err(_) => return Ok(None),
1804+
let Ok(data) = paths::read_bytes(dep_info) else {
1805+
return Ok(None);
18141806
};
1815-
let info = match EncodedDepInfo::parse(&data) {
1816-
Some(info) => info,
1817-
None => {
1818-
tracing::warn!("failed to parse cargo's dep-info at {:?}", dep_info);
1819-
return Ok(None);
1820-
}
1807+
let Some(info) = EncodedDepInfo::parse(&data) else {
1808+
tracing::warn!("failed to parse cargo's dep-info at {:?}", dep_info);
1809+
return Ok(None);
18211810
};
18221811
let mut ret = RustcDepInfo::default();
18231812
ret.env = info.env;
@@ -1852,9 +1841,8 @@ where
18521841
I: IntoIterator,
18531842
I::Item: AsRef<Path>,
18541843
{
1855-
let reference_mtime = match paths::mtime(reference) {
1856-
Ok(mtime) => mtime,
1857-
Err(..) => return Some(StaleItem::MissingFile(reference.to_path_buf())),
1844+
let Ok(reference_mtime) = paths::mtime(reference) else {
1845+
return Some(StaleItem::MissingFile(reference.to_path_buf()));
18581846
};
18591847

18601848
let skipable_dirs = if let Ok(cargo_home) = home::cargo_home() {
@@ -1882,9 +1870,8 @@ where
18821870
let path_mtime = match mtime_cache.entry(path.to_path_buf()) {
18831871
Entry::Occupied(o) => *o.get(),
18841872
Entry::Vacant(v) => {
1885-
let mtime = match paths::mtime_recursive(path) {
1886-
Ok(mtime) => mtime,
1887-
Err(..) => return Some(StaleItem::MissingFile(path.to_path_buf())),
1873+
let Ok(mtime) = paths::mtime_recursive(path) else {
1874+
return Some(StaleItem::MissingFile(path.to_path_buf()));
18881875
};
18891876
*v.insert(mtime)
18901877
}
@@ -2156,9 +2143,8 @@ pub fn parse_rustc_dep_info(rustc_dep_info: &Path) -> CargoResult<RustcDepInfo>
21562143
for line in contents.lines() {
21572144
if let Some(rest) = line.strip_prefix("# env-dep:") {
21582145
let mut parts = rest.splitn(2, '=');
2159-
let env_var = match parts.next() {
2160-
Some(s) => s,
2161-
None => continue,
2146+
let Some(env_var) = parts.next() else {
2147+
continue;
21622148
};
21632149
let env_val = match parts.next() {
21642150
Some(s) => Some(unescape_env(s)?),

src/cargo/core/compiler/future_incompat.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -333,13 +333,11 @@ fn get_updates(ws: &Workspace<'_>, package_ids: &BTreeSet<PackageId>) -> Option<
333333
let mut summaries = Vec::new();
334334
while !package_ids.is_empty() {
335335
package_ids.retain(|&pkg_id| {
336-
let source = match sources.get_mut(&pkg_id.source_id()) {
337-
Some(s) => s,
338-
None => return false,
336+
let Some(source) = sources.get_mut(&pkg_id.source_id()) else {
337+
return false;
339338
};
340-
let dep = match Dependency::parse(pkg_id.name(), None, pkg_id.source_id()) {
341-
Ok(dep) => dep,
342-
Err(_) => return false,
339+
let Ok(dep) = Dependency::parse(pkg_id.name(), None, pkg_id.source_id()) else {
340+
return false;
343341
};
344342
match source.query_vec(&dep, QueryKind::Exact) {
345343
Poll::Ready(Ok(sum)) => {

src/cargo/core/compiler/job_queue/mod.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -941,9 +941,8 @@ impl<'cfg> DrainState<'cfg> {
941941
cx: &mut Context<'_, '_>,
942942
) -> CargoResult<()> {
943943
let outputs = cx.build_script_outputs.lock().unwrap();
944-
let metadata = match cx.find_build_script_metadata(unit) {
945-
Some(metadata) => metadata,
946-
None => return Ok(()),
944+
let Some(metadata) = cx.find_build_script_metadata(unit) else {
945+
return Ok(());
947946
};
948947
let bcx = &mut cx.bcx;
949948
if let Some(output) = outputs.get(metadata) {

src/cargo/core/compiler/links.rs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,8 @@ pub fn validate_links(resolve: &Resolve, unit_graph: &UnitGraph) -> CargoResult<
2727
if !validated.insert(unit.pkg.package_id()) {
2828
continue;
2929
}
30-
let lib = match unit.pkg.manifest().links() {
31-
Some(lib) => lib,
32-
None => continue,
30+
let Some(lib) = unit.pkg.manifest().links() else {
31+
continue;
3332
};
3433
if let Some(&prev) = links.get(lib) {
3534
let prev_path = resolve

src/cargo/core/compiler/mod.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -543,12 +543,9 @@ fn link_targets(cx: &mut Context<'_, '_>, unit: &Unit, fresh: bool) -> CargoResu
543543
if !src.exists() {
544544
continue;
545545
}
546-
let dst = match output.hardlink.as_ref() {
547-
Some(dst) => dst,
548-
None => {
549-
destinations.push(src.clone());
550-
continue;
551-
}
546+
let Some(dst) = output.hardlink.as_ref() else {
547+
destinations.push(src.clone());
548+
continue;
552549
};
553550
destinations.push(dst.clone());
554551
paths::link_or_copy(src, dst)?;
@@ -1321,7 +1318,7 @@ fn add_custom_flags(
13211318
cmd.arg("--check-cfg").arg(check_cfg);
13221319
}
13231320
}
1324-
for &(ref name, ref value) in output.env.iter() {
1321+
for (name, value) in output.env.iter() {
13251322
cmd.env(name, value);
13261323
}
13271324
}

src/cargo/core/compiler/timings.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -194,9 +194,8 @@ impl<'cfg> Timings<'cfg> {
194194
// `id` may not always be active. "fresh" units unconditionally
195195
// generate `Message::Finish`, but this active map only tracks dirty
196196
// units.
197-
let unit_time = match self.active.get_mut(&id) {
198-
Some(ut) => ut,
199-
None => return,
197+
let Some(unit_time) = self.active.get_mut(&id) else {
198+
return;
200199
};
201200
let t = self.start.elapsed().as_secs_f64();
202201
unit_time.rmeta_time = Some(t - unit_time.start);
@@ -212,9 +211,8 @@ impl<'cfg> Timings<'cfg> {
212211
return;
213212
}
214213
// See note above in `unit_rmeta_finished`, this may not always be active.
215-
let mut unit_time = match self.active.remove(&id) {
216-
Some(ut) => ut,
217-
None => return,
214+
let Some(mut unit_time) = self.active.remove(&id) else {
215+
return;
218216
};
219217
let t = self.start.elapsed().as_secs_f64();
220218
unit_time.duration = t - unit_time.start;
@@ -265,9 +263,8 @@ impl<'cfg> Timings<'cfg> {
265263
if !self.enabled {
266264
return;
267265
}
268-
let prev = match &mut self.last_cpu_state {
269-
Some(state) => state,
270-
None => return,
266+
let Some(prev) = &mut self.last_cpu_state else {
267+
return;
271268
};
272269
// Don't take samples too frequently, even if requested.
273270
let now = Instant::now();

src/cargo/core/compiler/unit_dependencies.rs

Lines changed: 10 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -273,10 +273,9 @@ fn compute_deps(
273273
let mut ret = Vec::new();
274274
let mut dev_deps = Vec::new();
275275
for (dep_pkg_id, deps) in state.deps(unit, unit_for) {
276-
let dep_lib = match calc_artifact_deps(unit, unit_for, dep_pkg_id, &deps, state, &mut ret)?
277-
{
278-
Some(lib) => lib,
279-
None => continue,
276+
let Some(dep_lib) = calc_artifact_deps(unit, unit_for, dep_pkg_id, &deps, state, &mut ret)?
277+
else {
278+
continue;
280279
};
281280
let dep_pkg = state.get(dep_pkg_id);
282281
let mode = check_or_build_mode(unit.mode, dep_lib);
@@ -412,12 +411,9 @@ fn calc_artifact_deps<'a>(
412411
let mut maybe_non_artifact_lib = false;
413412
let artifact_pkg = state.get(dep_id);
414413
for dep in deps {
415-
let artifact = match dep.artifact() {
416-
Some(a) => a,
417-
None => {
418-
maybe_non_artifact_lib = true;
419-
continue;
420-
}
414+
let Some(artifact) = dep.artifact() else {
415+
maybe_non_artifact_lib = true;
416+
continue;
421417
};
422418
has_artifact_lib |= artifact.is_lib();
423419
// Custom build scripts (build/compile) never get artifact dependencies,
@@ -611,9 +607,8 @@ fn compute_deps_doc(
611607
// the documentation of the library being built.
612608
let mut ret = Vec::new();
613609
for (id, deps) in state.deps(unit, unit_for) {
614-
let dep_lib = match calc_artifact_deps(unit, unit_for, id, &deps, state, &mut ret)? {
615-
Some(lib) => lib,
616-
None => continue,
610+
let Some(dep_lib) = calc_artifact_deps(unit, unit_for, id, &deps, state, &mut ret)? else {
611+
continue;
617612
};
618613
let dep_pkg = state.get(id);
619614
// Rustdoc only needs rmeta files for regular dependencies.
@@ -923,9 +918,8 @@ fn connect_run_custom_build_deps(state: &mut State<'_, '_>) {
923918
{
924919
// This list of dependencies all depend on `unit`, an execution of
925920
// the build script.
926-
let reverse_deps = match reverse_deps_map.get(unit) {
927-
Some(set) => set,
928-
None => continue,
921+
let Some(reverse_deps) = reverse_deps_map.get(unit) else {
922+
continue;
929923
};
930924

931925
let to_add = reverse_deps

0 commit comments

Comments
 (0)