Moar linting: needless_borrow, let_unit_value, ...

* There are a few needless borrows that don't seem to be needed. I even did a quick assembly comparison and posted a q to stackoveflow on it. See [here](https://stackoverflow.com/questions/74910196/advantages-of-pass-by-ref-val-with-impl-intoiteratoritem-impl-asrefstr)
* removed several `let _ = ...` when they don't look necessary (even a few ones that were not suggested by clippy (?))
* there were a few `then(|| ctor{})` that clippy suggested to replace with `then_some(ctor{})` -- seems reasonable?
* some unneeded assignment+return - keep the code a bit leaner
* a few `writeln!` instead of `write!`, or even consolidate write!
* a nice optimization to use `ch.is_ascii_digit` instead of `ch.is_digit(10)`
This commit is contained in:
Yuri Astrakhan 2022-12-24 16:09:08 -05:00
parent 2872e05589
commit d3dbf9c194
15 changed files with 22 additions and 26 deletions

View file

@ -297,11 +297,11 @@ impl FlycheckActor {
let mut cmd = Command::new(toolchain::cargo()); let mut cmd = Command::new(toolchain::cargo());
cmd.arg(command); cmd.arg(command);
cmd.current_dir(&self.root); cmd.current_dir(&self.root);
cmd.args(&["--workspace", "--message-format=json", "--manifest-path"]) cmd.args(["--workspace", "--message-format=json", "--manifest-path"])
.arg(self.root.join("Cargo.toml").as_os_str()); .arg(self.root.join("Cargo.toml").as_os_str());
for target in target_triples { for target in target_triples {
cmd.args(&["--target", target.as_str()]); cmd.args(["--target", target.as_str()]);
} }
if *all_targets { if *all_targets {
cmd.arg("--all-targets"); cmd.arg("--all-targets");

View file

@ -51,7 +51,7 @@ pub(crate) mod entry {
use super::*; use super::*;
pub(crate) fn vis(p: &mut Parser<'_>) { pub(crate) fn vis(p: &mut Parser<'_>) {
let _ = opt_visibility(p, false); opt_visibility(p, false);
} }
pub(crate) fn block(p: &mut Parser<'_>) { pub(crate) fn block(p: &mut Parser<'_>) {
@ -70,10 +70,10 @@ pub(crate) mod entry {
types::type_(p); types::type_(p);
} }
pub(crate) fn expr(p: &mut Parser<'_>) { pub(crate) fn expr(p: &mut Parser<'_>) {
let _ = expressions::expr(p); expressions::expr(p);
} }
pub(crate) fn path(p: &mut Parser<'_>) { pub(crate) fn path(p: &mut Parser<'_>) {
let _ = paths::type_path(p); paths::type_path(p);
} }
pub(crate) fn item(p: &mut Parser<'_>) { pub(crate) fn item(p: &mut Parser<'_>) {
items::item_or_macro(p, true); items::item_or_macro(p, true);

View file

@ -80,8 +80,8 @@ impl<'a> LexedStr<'a> {
State::PendingEnter | State::Normal => unreachable!(), State::PendingEnter | State::Normal => unreachable!(),
} }
let is_eof = builder.pos == builder.lexed.len(); // is_eof?
is_eof builder.pos == builder.lexed.len()
} }
} }

View file

@ -93,14 +93,12 @@ fn parse(entry: TopEntryPoint, text: &str) -> (String, bool) {
crate::StrStep::Token { kind, text } => { crate::StrStep::Token { kind, text } => {
assert!(depth > 0); assert!(depth > 0);
len += text.len(); len += text.len();
write!(buf, "{indent}").unwrap(); writeln!(buf, "{indent}{kind:?} {text:?}").unwrap();
write!(buf, "{kind:?} {text:?}\n").unwrap();
} }
crate::StrStep::Enter { kind } => { crate::StrStep::Enter { kind } => {
assert!(depth > 0 || len == 0); assert!(depth > 0 || len == 0);
depth += 1; depth += 1;
write!(buf, "{indent}").unwrap(); writeln!(buf, "{indent}{kind:?}").unwrap();
write!(buf, "{kind:?}\n").unwrap();
indent.push_str(" "); indent.push_str(" ");
} }
crate::StrStep::Exit => { crate::StrStep::Exit => {

View file

@ -67,7 +67,7 @@ impl Process {
args: impl IntoIterator<Item = impl AsRef<OsStr>>, args: impl IntoIterator<Item = impl AsRef<OsStr>>,
) -> io::Result<Process> { ) -> io::Result<Process> {
let args: Vec<OsString> = args.into_iter().map(|s| s.as_ref().into()).collect(); let args: Vec<OsString> = args.into_iter().map(|s| s.as_ref().into()).collect();
let child = JodChild(mk_child(&path, &args)?); let child = JodChild(mk_child(&path, args)?);
Ok(Process { child }) Ok(Process { child })
} }

View file

@ -63,7 +63,7 @@ fn main() {
}; };
cmd.current_dir(&staging_dir) cmd.current_dir(&staging_dir)
.args(&["build", "-p", "proc-macro-test-impl", "--message-format", "json"]) .args(["build", "-p", "proc-macro-test-impl", "--message-format", "json"])
// Explicit override the target directory to avoid using the same one which the parent // Explicit override the target directory to avoid using the same one which the parent
// cargo is using, or we'll deadlock. // cargo is using, or we'll deadlock.
// This can happen when `CARGO_TARGET_DIR` is set or global config forces all cargo // This can happen when `CARGO_TARGET_DIR` is set or global config forces all cargo

View file

@ -119,7 +119,7 @@ impl Expr {
fn binding_power(&self) -> (u8, u8) { fn binding_power(&self) -> (u8, u8) {
use ast::{ArithOp::*, BinaryOp::*, Expr::*, LogicOp::*}; use ast::{ArithOp::*, BinaryOp::*, Expr::*, LogicOp::*};
let dps = match self { match self {
// (0, 0) -- paren-like/nullary // (0, 0) -- paren-like/nullary
// (0, N) -- prefix // (0, N) -- prefix
// (N, 0) -- postfix // (N, 0) -- postfix
@ -170,9 +170,7 @@ impl Expr {
ArrayExpr(_) | TupleExpr(_) | Literal(_) | PathExpr(_) | ParenExpr(_) | IfExpr(_) ArrayExpr(_) | TupleExpr(_) | Literal(_) | PathExpr(_) | ParenExpr(_) | IfExpr(_)
| WhileExpr(_) | ForExpr(_) | LoopExpr(_) | MatchExpr(_) | BlockExpr(_) | WhileExpr(_) | ForExpr(_) | LoopExpr(_) | MatchExpr(_) | BlockExpr(_)
| RecordExpr(_) | UnderscoreExpr(_) => (0, 0), | RecordExpr(_) | UnderscoreExpr(_) => (0, 0),
}; }
dps
} }
fn is_paren_like(&self) -> bool { fn is_paren_like(&self) -> bool {

View file

@ -82,7 +82,7 @@ impl<N: AstNode> AstPtr<N> {
/// Like `SyntaxNodePtr::cast` but the trait bounds work out. /// Like `SyntaxNodePtr::cast` but the trait bounds work out.
pub fn try_from_raw(raw: SyntaxNodePtr) -> Option<AstPtr<N>> { pub fn try_from_raw(raw: SyntaxNodePtr) -> Option<AstPtr<N>> {
N::can_cast(raw.kind()).then(|| AstPtr { raw, _ty: PhantomData }) N::can_cast(raw.kind()).then_some(AstPtr { raw, _ty: PhantomData })
} }
} }

View file

@ -196,7 +196,7 @@ pub(crate) fn validate_block_structure(root: &SyntaxNode) {
fn validate_numeric_name(name_ref: Option<ast::NameRef>, errors: &mut Vec<SyntaxError>) { fn validate_numeric_name(name_ref: Option<ast::NameRef>, errors: &mut Vec<SyntaxError>) {
if let Some(int_token) = int_token(name_ref) { if let Some(int_token) = int_token(name_ref) {
if int_token.text().chars().any(|c| !c.is_digit(10)) { if int_token.text().chars().any(|c| !c.is_ascii_digit()) {
errors.push(SyntaxError::new( errors.push(SyntaxError::new(
"Tuple (struct) field access is only allowed through \ "Tuple (struct) field access is only allowed through \
decimal integers with no underscores or suffix", decimal integers with no underscores or suffix",

View file

@ -36,10 +36,10 @@ struct S{} {{
pub fn glorious_old_parser() -> String { pub fn glorious_old_parser() -> String {
let path = project_root().join("bench_data/glorious_old_parser"); let path = project_root().join("bench_data/glorious_old_parser");
fs::read_to_string(&path).unwrap() fs::read_to_string(path).unwrap()
} }
pub fn numerous_macro_rules() -> String { pub fn numerous_macro_rules() -> String {
let path = project_root().join("bench_data/numerous_macro_rules"); let path = project_root().join("bench_data/numerous_macro_rules");
fs::read_to_string(&path).unwrap() fs::read_to_string(path).unwrap()
} }

View file

@ -396,7 +396,7 @@ pub fn skip_slow_tests() -> bool {
eprintln!("ignoring slow test"); eprintln!("ignoring slow test");
} else { } else {
let path = project_root().join("./target/.slow_tests_cookie"); let path = project_root().join("./target/.slow_tests_cookie");
fs::write(&path, ".").unwrap(); fs::write(path, ".").unwrap();
} }
should_skip should_skip
} }

View file

@ -35,7 +35,7 @@ fn get_path_for_executable(executable_name: &'static str) -> PathBuf {
// example: for cargo, this tries ~/.cargo/bin/cargo // example: for cargo, this tries ~/.cargo/bin/cargo
// It seems that this is a reasonable place to try for cargo, rustc, and rustup // It seems that this is a reasonable place to try for cargo, rustc, and rustup
let env_var = executable_name.to_ascii_uppercase(); let env_var = executable_name.to_ascii_uppercase();
if let Some(path) = env::var_os(&env_var) { if let Some(path) = env::var_os(env_var) {
return path.into(); return path.into();
} }

View file

@ -62,7 +62,7 @@ fn fix_path_for_mac(sh: &Shell) -> Result<()> {
let mut paths = env::split_paths(&vars).collect::<Vec<_>>(); let mut paths = env::split_paths(&vars).collect::<Vec<_>>();
paths.append(&mut vscode_path); paths.append(&mut vscode_path);
let new_paths = env::join_paths(paths).context("build env PATH")?; let new_paths = env::join_paths(paths).context("build env PATH")?;
sh.set_var("PATH", &new_paths); sh.set_var("PATH", new_paths);
} }
Ok(()) Ok(())

View file

@ -65,7 +65,7 @@ impl flags::Release {
let contents = changelog::get_changelog(sh, changelog_n, &commit, prev_tag, &today)?; let contents = changelog::get_changelog(sh, changelog_n, &commit, prev_tag, &today)?;
let path = changelog_dir.join(format!("{today}-changelog-{changelog_n}.adoc")); let path = changelog_dir.join(format!("{today}-changelog-{changelog_n}.adoc"));
sh.write_file(&path, &contents)?; sh.write_file(path, contents)?;
Ok(()) Ok(())
} }

View file

@ -23,7 +23,7 @@ pub(crate) fn get_changelog(
let mut others = String::new(); let mut others = String::new();
for line in git_log.lines() { for line in git_log.lines() {
let line = line.trim_start(); let line = line.trim_start();
if let Some(pr_num) = parse_pr_number(&line) { if let Some(pr_num) = parse_pr_number(line) {
let accept = "Accept: application/vnd.github.v3+json"; let accept = "Accept: application/vnd.github.v3+json";
let authorization = format!("Authorization: token {token}"); let authorization = format!("Authorization: token {token}");
let pr_url = "https://api.github.com/repos/rust-lang/rust-analyzer/issues"; let pr_url = "https://api.github.com/repos/rust-lang/rust-analyzer/issues";