From 92000002417fc6db106339941adcd2d3f1767d6c Mon Sep 17 00:00:00 2001 From: Yuri Astrakhan Date: Mon, 16 Oct 2023 01:00:06 -0400 Subject: [PATCH] Inline format-args in CLI This makes the code a bit easier to read and smaller. Some of it was done with this command, and later fixed by hand: ``` cargo clippy --workspace --allow-dirty --fix --benches --tests --bins -- -A clippy::all -W clippy::uninlined_format_args ``` --- regex-cli/args/flags.rs | 8 +++----- regex-cli/args/mod.rs | 4 ++-- regex-cli/args/syntax.rs | 7 ++----- regex-cli/cmd/compile_test.rs | 16 +++++++--------- regex-cli/cmd/debug/dfa.rs | 12 ++++++------ regex-cli/cmd/debug/literal.rs | 10 ++++------ regex-cli/cmd/debug/mod.rs | 6 +++--- regex-cli/cmd/find/capture/mod.rs | 10 +++++----- regex-cli/cmd/find/half/mod.rs | 2 +- regex-cli/cmd/find/match/mod.rs | 2 +- regex-cli/cmd/find/mod.rs | 2 +- regex-cli/cmd/find/which/mod.rs | 2 +- regex-cli/cmd/generate/fowler.rs | 24 ++++++++++-------------- regex-cli/cmd/generate/mod.rs | 2 +- regex-cli/cmd/generate/serialize/dfa.rs | 6 +++--- regex-cli/cmd/generate/serialize/mod.rs | 2 +- regex-cli/cmd/mod.rs | 2 +- regex-cli/main.rs | 6 +++--- regex-cli/util.rs | 2 +- 19 files changed, 56 insertions(+), 69 deletions(-) diff --git a/regex-cli/args/flags.rs b/regex-cli/args/flags.rs index 61732a28e..37b741a71 100644 --- a/regex-cli/args/flags.rs +++ b/regex-cli/args/flags.rs @@ -50,9 +50,7 @@ impl std::str::FromStr for ByteSet { for &byte in Vec::unescape_bytes(s).iter() { anyhow::ensure!( !seen[usize::from(byte)], - "saw duplicate byte 0x{:2X} in '{}'", - byte, - s, + "saw duplicate byte 0x{byte:2X} in '{s}'", ); seen[usize::from(byte)] = true; set.push(byte); @@ -96,7 +94,7 @@ impl std::str::FromStr for StartKind { "both" => regex_automata::dfa::StartKind::Both, "unanchored" => regex_automata::dfa::StartKind::Unanchored, "anchored" => regex_automata::dfa::StartKind::Anchored, - unk => anyhow::bail!("unrecognized start kind '{}'", unk), + unk => anyhow::bail!("unrecognized start kind '{unk}'"), }; Ok(StartKind { kind }) } @@ -147,7 +145,7 @@ impl std::str::FromStr for MatchKind { let kind = match s { "leftmost-first" => regex_automata::MatchKind::LeftmostFirst, "all" => regex_automata::MatchKind::All, - unk => anyhow::bail!("unrecognized match kind '{}'", unk), + unk => anyhow::bail!("unrecognized match kind '{unk}'"), }; Ok(MatchKind { kind }) } diff --git a/regex-cli/args/mod.rs b/regex-cli/args/mod.rs index ba5a032f4..93b274815 100644 --- a/regex-cli/args/mod.rs +++ b/regex-cli/args/mod.rs @@ -143,11 +143,11 @@ pub fn next_as_command(usage: &str, p: &mut Parser) -> anyhow::Result { let usage = usage.trim(); let arg = match p.next()? { Some(arg) => arg, - None => anyhow::bail!("{}", usage), + None => anyhow::bail!("{usage}"), }; let cmd = match arg { Arg::Value(cmd) => cmd.string()?, - Arg::Short('h') | Arg::Long("help") => anyhow::bail!("{}", usage), + Arg::Short('h') | Arg::Long("help") => anyhow::bail!("{usage}"), arg => return Err(arg.unexpected().into()), }; Ok(cmd) diff --git a/regex-cli/args/syntax.rs b/regex-cli/args/syntax.rs index a91ac2dca..e405b5475 100644 --- a/regex-cli/args/syntax.rs +++ b/regex-cli/args/syntax.rs @@ -45,7 +45,7 @@ impl Config { .map(|(i, p)| { let p = p.as_ref(); self.ast(p).with_context(|| { - format!("failed to parse pattern {} to AST: '{}'", i, p,) + format!("failed to parse pattern {i} to AST: '{p}'",) }) }) .collect() @@ -80,10 +80,7 @@ impl Config { .map(|(i, (pat, ast))| { let (pat, ast) = (pat.as_ref(), ast.borrow()); self.hir(pat, ast).with_context(|| { - format!( - "failed to translate pattern {} to HIR: '{}'", - i, pat, - ) + format!("failed to translate pattern {i} to HIR: '{pat}'",) }) }) .collect() diff --git a/regex-cli/cmd/compile_test.rs b/regex-cli/cmd/compile_test.rs index bd28a7dab..2926fd316 100644 --- a/regex-cli/cmd/compile_test.rs +++ b/regex-cli/cmd/compile_test.rs @@ -127,11 +127,11 @@ OPTIONS: } else { write!(wtr, "regex,")?; } - write!(wtr, "{},", revision)?; + write!(wtr, "{revision},")?; write!(wtr, "{},", tdir.test.profile.as_str())?; write!(wtr, "{:?},", m.duration)?; write!(wtr, "{:?},", m.size)?; - write!(wtr, "{:?}", relative_size)?; + write!(wtr, "{relative_size:?}")?; write!(wtr, "\n")?; } Ok(()) @@ -439,7 +439,7 @@ impl Test { let features = self .features .iter() - .map(|f| format!(r#""{}""#, f)) + .map(|f| format!(r#""{f}""#)) .collect::>() .join(", "); format!( @@ -480,7 +480,7 @@ strip = "symbols" let features = self .features .iter() - .map(|f| format!(r#""{}""#, f)) + .map(|f| format!(r#""{f}""#)) .collect::>() .join(", "); format!( @@ -521,7 +521,7 @@ strip = "symbols" let features = self .features .iter() - .map(|f| format!(r#""{}""#, f)) + .map(|f| format!(r#""{f}""#)) .collect::>() .join(", "); format!( @@ -800,8 +800,7 @@ fn baseline_size(parent_dir: &Path, profile: Profile) -> anyhow::Result { .with_context(|| format!("'cargo clean' failed for baseline"))?; anyhow::ensure!( status.success(), - "'cargo clean' got an error exit code of {:?} for baseline", - status, + "'cargo clean' got an error exit code of {status:?} for baseline", ); let status = Command::new("cargo") .arg("build") @@ -814,8 +813,7 @@ fn baseline_size(parent_dir: &Path, profile: Profile) -> anyhow::Result { .with_context(|| format!("'cargo build' failed for baseline"))?; anyhow::ensure!( status.success(), - "'cargo build' got an error exit code of {:?} for baseline", - status, + "'cargo build' got an error exit code of {status:?} for baseline", ); let bin = dir .join("target") diff --git a/regex-cli/cmd/debug/dfa.rs b/regex-cli/cmd/debug/dfa.rs index f16610fbe..a270acd53 100644 --- a/regex-cli/cmd/debug/dfa.rs +++ b/regex-cli/cmd/debug/dfa.rs @@ -29,7 +29,7 @@ COMMANDS: match &*cmd { "dfa" => run_dense_dfa(p), "regex" => run_dense_regex(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } @@ -88,7 +88,7 @@ OPTIONS: if common.table() { writeln!(stdout(), "")?; } - writeln!(stdout(), "{:?}", dfa)?; + writeln!(stdout(), "{dfa:?}")?; } Ok(()) } @@ -161,7 +161,7 @@ OPTIONS: if common.table() { writeln!(stdout(), "")?; } - writeln!(stdout(), "{:?}", re)?; + writeln!(stdout(), "{re:?}")?; } Ok(()) } @@ -188,7 +188,7 @@ COMMANDS: match &*cmd { "dfa" => run_sparse_dfa(p), "regex" => run_sparse_regex(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } @@ -245,7 +245,7 @@ OPTIONS: if common.table() { writeln!(stdout(), "")?; } - writeln!(stdout(), "{:?}", dfa)?; + writeln!(stdout(), "{dfa:?}")?; } Ok(()) } @@ -320,7 +320,7 @@ OPTIONS: if common.table() { writeln!(stdout(), "")?; } - writeln!(stdout(), "{:?}", re)?; + writeln!(stdout(), "{re:?}")?; } Ok(()) } diff --git a/regex-cli/cmd/debug/literal.rs b/regex-cli/cmd/debug/literal.rs index 9c82ec6e0..8d2d281dd 100644 --- a/regex-cli/cmd/debug/literal.rs +++ b/regex-cli/cmd/debug/literal.rs @@ -64,8 +64,7 @@ OPTIONS: ExtractKind::Suffix => seq.optimize_for_suffix_by_preference(), unk => { anyhow::bail!( - "unsupported literal extraction kind: {:?}", - unk + "unsupported literal extraction kind: {unk:?}" ) } } @@ -95,10 +94,10 @@ OPTIONS: writeln!(out, "")?; } match seq.literals() { - None => writeln!(out, "{:?}", seq)?, + None => writeln!(out, "{seq:?}")?, Some(literals) => { for lit in literals.iter() { - writeln!(stdout(), "{:?}", lit)?; + writeln!(stdout(), "{lit:?}")?; } } } @@ -127,8 +126,7 @@ impl Configurable for Literal { "prefix" => ExtractKind::Prefix, "suffix" => ExtractKind::Suffix, unk => anyhow::bail!( - "unknown value for --extract-kind: {}", - unk + "unknown value for --extract-kind: {unk}" ), }; self.kind = kind.clone(); diff --git a/regex-cli/cmd/debug/mod.rs b/regex-cli/cmd/debug/mod.rs index 525c4d138..b25dc4137 100644 --- a/regex-cli/cmd/debug/mod.rs +++ b/regex-cli/cmd/debug/mod.rs @@ -39,7 +39,7 @@ COMMANDS: "onepass" => run_onepass(p), "sparse" => dfa::run_sparse(p), "thompson" => run_thompson(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } @@ -181,7 +181,7 @@ OPTIONS: if common.table() { writeln!(stdout(), "")?; } - writeln!(stdout(), "{:?}", dfa)?; + writeln!(stdout(), "{dfa:?}")?; } Ok(()) } @@ -238,7 +238,7 @@ OPTIONS: if common.table() { writeln!(stdout(), "")?; } - writeln!(stdout(), "{:?}", nfa)?; + writeln!(stdout(), "{nfa:?}")?; } Ok(()) } diff --git a/regex-cli/cmd/find/capture/mod.rs b/regex-cli/cmd/find/capture/mod.rs index 3af46bfcf..38e27059a 100644 --- a/regex-cli/cmd/find/capture/mod.rs +++ b/regex-cli/cmd/find/capture/mod.rs @@ -46,7 +46,7 @@ ENGINES: "onepass" => dfa::run_onepass(p), "pikevm" => nfa::run_pikevm(p), "regex" => run_regex(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } @@ -388,9 +388,9 @@ fn run_counts( } let count = pattern_counts[group_index]; if let Some(name) = maybe_name { - write!(out, "{}/{}: {}", group_index, name, count)?; + write!(out, "{group_index}/{name}: {count}")?; } else { - write!(out, "{}: {}", group_index, count)?; + write!(out, "{group_index}: {count}")?; } } write!(out, " }}\n")?; @@ -440,9 +440,9 @@ fn run_search( write!(out, ", ")?; } if let Some(name) = maybe_name { - write!(out, "{}/{}: ", group_index, name)?; + write!(out, "{group_index}/{name}: ")?; } else { - write!(out, "{}: ", group_index)?; + write!(out, "{group_index}: ")?; } match caps.get_group(group_index) { None => write!(out, "NONE")?, diff --git a/regex-cli/cmd/find/half/mod.rs b/regex-cli/cmd/find/half/mod.rs index 4dd33bd3d..15c8b7362 100644 --- a/regex-cli/cmd/find/half/mod.rs +++ b/regex-cli/cmd/find/half/mod.rs @@ -45,7 +45,7 @@ ENGINES: "meta" => run_meta(p), "regex" => run_regex(p), "sparse" => dfa::run_sparse(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } diff --git a/regex-cli/cmd/find/match/mod.rs b/regex-cli/cmd/find/match/mod.rs index 0bafd8b2b..7cc8fcf42 100644 --- a/regex-cli/cmd/find/match/mod.rs +++ b/regex-cli/cmd/find/match/mod.rs @@ -44,7 +44,7 @@ ENGINES: "pikevm" => nfa::run_pikevm(p), "regex" => run_regex(p), "sparse" => dfa::run_sparse(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } diff --git a/regex-cli/cmd/find/mod.rs b/regex-cli/cmd/find/mod.rs index deb8cd1ed..2965949f7 100644 --- a/regex-cli/cmd/find/mod.rs +++ b/regex-cli/cmd/find/mod.rs @@ -31,7 +31,7 @@ COMMANDS: "half" => half::run(p), "match" => r#match::run(p), "which" => which::run(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } diff --git a/regex-cli/cmd/find/which/mod.rs b/regex-cli/cmd/find/which/mod.rs index 4416a76f8..bbb46f4fe 100644 --- a/regex-cli/cmd/find/which/mod.rs +++ b/regex-cli/cmd/find/which/mod.rs @@ -58,7 +58,7 @@ ENGINES: "pikevm" => nfa::run_pikevm(p), "regex" => run_regex(p), "sparse" => dfa::run_sparse(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } diff --git a/regex-cli/cmd/generate/fowler.rs b/regex-cli/cmd/generate/fowler.rs index 404c47721..3a3af9ed9 100644 --- a/regex-cli/cmd/generate/fowler.rs +++ b/regex-cli/cmd/generate/fowler.rs @@ -50,7 +50,7 @@ USAGE: Some(stem) => stem.to_string_lossy(), None => anyhow::bail!("{}: has no file stem", datfile.display()), }; - let tomlfile = outdir.join(format!("{}.toml", stem)); + let tomlfile = outdir.join(format!("{stem}.toml")); let mut rdr = File::open(datfile) .with_context(|| datfile.display().to_string())?; @@ -112,7 +112,7 @@ fn convert( src: &mut dyn Read, dst: &mut dyn Write, ) -> anyhow::Result<()> { - log::trace!("processing {}", group_name); + log::trace!("processing {group_name}"); let src = std::io::BufReader::new(src); writeln!( @@ -129,7 +129,7 @@ fn convert( for (i, result) in src.lines().enumerate() { // Every usize can fit into a u64... Right? let line_number = u64::try_from(i).unwrap().checked_add(1).unwrap(); - let line = result.with_context(|| format!("line {}", line_number))?; + let line = result.with_context(|| format!("line {line_number}"))?; // The last group of tests in 'repetition' take quite a lot of time // when using them to build and minimize a DFA. So we tag them with // 'expensive' so that we can skip those tests when we need to minimize @@ -146,7 +146,7 @@ fn convert( Some(dat) => dat, }; let toml = TomlTest::from_dat_test(group_name, &dat)?; - writeln!(dst, "{}", toml)?; + writeln!(dst, "{toml}")?; prev = Some(dat); } Ok(()) @@ -220,7 +220,7 @@ impl TomlTest { impl core::fmt::Display for TomlTest { fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { if let Some(ref comment) = self.comment { - writeln!(f, "# {}", comment)?; + writeln!(f, "# {comment}")?; } writeln!(f, "[[test]]")?; writeln!(f, "name = \"{}{}\"", self.group_name, self.line_number)?; @@ -236,7 +236,7 @@ impl core::fmt::Display for TomlTest { } match group { None => write!(f, "[]")?, - Some((start, end)) => write!(f, "[{}, {}]", start, end)?, + Some((start, end)) => write!(f, "[{start}, {end}]")?, } } writeln!(f, "]]")?; @@ -297,7 +297,7 @@ impl DatTest { // First field contains terse one-letter flags. let mut flags: HashSet = fields[0].chars().collect(); if !flags.contains(&'E') { - log::trace!("skipping {}: does not contain 'E' flag", line_number); + log::trace!("skipping {line_number}: does not contain 'E' flag"); return Ok(None); } @@ -307,10 +307,7 @@ impl DatTest { if regex == "SAME" { regex = match prev { Some(test) => test.regex.clone(), - None => anyhow::bail!( - "line {}: wants previous pattern but none is available", - line_number, - ), + None => anyhow::bail!("line {line_number}: wants previous pattern but none is available"), }; } @@ -341,8 +338,7 @@ impl DatTest { // yet, just adding support for them here. if !fields[3].contains(',') { log::trace!( - "skipping {}: malformed capturing group", - line_number + "skipping {line_number}: malformed capturing group" ); return Ok(None); } @@ -390,7 +386,7 @@ impl DatTest { fn count_capturing_groups(pattern: &str) -> anyhow::Result { let ast = regex_syntax::ast::parse::Parser::new() .parse(pattern) - .with_context(|| format!("failed to parse '{}'", pattern))?; + .with_context(|| format!("failed to parse '{pattern}'"))?; // We add 1 to account for the capturing group for the entire // pattern. Ok(1 + count_capturing_groups_ast(&ast)) diff --git a/regex-cli/cmd/generate/mod.rs b/regex-cli/cmd/generate/mod.rs index 3a2faac40..8378a156e 100644 --- a/regex-cli/cmd/generate/mod.rs +++ b/regex-cli/cmd/generate/mod.rs @@ -23,6 +23,6 @@ pub fn run(p: &mut lexopt::Parser) -> anyhow::Result<()> { "fowler" => fowler::run(p), "serialize" => serialize::run(p), "unicode" => unicode::run(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } diff --git a/regex-cli/cmd/generate/serialize/dfa.rs b/regex-cli/cmd/generate/serialize/dfa.rs index 600d12111..583860839 100644 --- a/regex-cli/cmd/generate/serialize/dfa.rs +++ b/regex-cli/cmd/generate/serialize/dfa.rs @@ -42,7 +42,7 @@ ENGINES: match &*args::next_as_command(USAGE, p)? { "dfa" => run_dense_dfa(p), "regex" => run_dense_regex(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } @@ -154,7 +154,7 @@ ENGINES: match &*args::next_as_command(USAGE, p)? { "dfa" => run_sparse_dfa(p), "regex" => run_sparse_regex(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } @@ -389,7 +389,7 @@ impl std::str::FromStr for RustKind { "once-cell" => Ok(RustKind::OnceCell), "lazy-static" => Ok(RustKind::LazyStatic), "none" => Ok(RustKind::None), - unk => anyhow::bail!("unrecognized rust output kind: '{}'", unk), + unk => anyhow::bail!("unrecognized rust output kind: '{unk}'"), } } } diff --git a/regex-cli/cmd/generate/serialize/mod.rs b/regex-cli/cmd/generate/serialize/mod.rs index a0c2f779a..358bafc20 100644 --- a/regex-cli/cmd/generate/serialize/mod.rs +++ b/regex-cli/cmd/generate/serialize/mod.rs @@ -17,6 +17,6 @@ ENGINES: match &*args::next_as_command(USAGE, p)? { "dense" => dfa::run_dense(p), "sparse" => dfa::run_sparse(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } diff --git a/regex-cli/cmd/mod.rs b/regex-cli/cmd/mod.rs index 5e9706a57..8cf79b957 100644 --- a/regex-cli/cmd/mod.rs +++ b/regex-cli/cmd/mod.rs @@ -23,6 +23,6 @@ pub fn run(p: &mut lexopt::Parser) -> anyhow::Result<()> { "find" => find::run(p), "debug" => debug::run(p), "generate" => generate::run(p), - unk => anyhow::bail!("unrecognized command '{}'", unk), + unk => anyhow::bail!("unrecognized command '{unk}'"), } } diff --git a/regex-cli/main.rs b/regex-cli/main.rs index 3ebbac3c0..db22ea166 100644 --- a/regex-cli/main.rs +++ b/regex-cli/main.rs @@ -14,16 +14,16 @@ fn main() -> anyhow::Result<()> { "info" => log::LevelFilter::Info, "debug" => log::LevelFilter::Debug, "trace" => log::LevelFilter::Trace, - unk => anyhow::bail!("unrecognized log level '{}'", unk), + unk => anyhow::bail!("unrecognized log level '{unk}'"), }; logger::Logger::init()?; log::set_max_level(level); if let Err(err) = cmd::run(&mut lexopt::Parser::from_env()) { if std::env::var("RUST_BACKTRACE").map_or(false, |v| v == "1") { - writeln!(&mut std::io::stderr(), "{:?}", err).unwrap(); + writeln!(&mut std::io::stderr(), "{err:?}").unwrap(); } else { - writeln!(&mut std::io::stderr(), "{:#}", err).unwrap(); + writeln!(&mut std::io::stderr(), "{err:#}").unwrap(); } std::process::exit(1); } diff --git a/regex-cli/util.rs b/regex-cli/util.rs index 3ff7d60e7..fbc98d9e1 100644 --- a/regex-cli/util.rs +++ b/regex-cli/util.rs @@ -66,7 +66,7 @@ impl Table { let mut wtr = tabwriter::TabWriter::new(wtr) .alignment(tabwriter::Alignment::Right); for (label, value) in self.pairs.iter() { - writeln!(wtr, "{}:\t{:?}", label, value)?; + writeln!(wtr, "{label}:\t{value:?}")?; } wtr.flush() }