Fix clippy::unnecessary_wraps (pedantic) (#880)

https://rust-lang.github.io/rust-clippy/master/index.html#unnecessary_wraps
This commit is contained in:
Charlie Marsh
2022-11-22 18:25:30 -05:00
committed by GitHub
parent f59799e0c4
commit b922e6ecc8
15 changed files with 398 additions and 438 deletions

View File

@@ -19,7 +19,7 @@ pub fn main(cli: &Cli) -> Result<()> {
let contents = fs::read_to_string(&cli.file)?;
let python_ast = parser::parse_program(&contents, &cli.file.to_string_lossy())?;
let mut generator = SourceGenerator::new();
generator.unparse_suite(&python_ast)?;
generator.unparse_suite(&python_ast);
println!("{}", generator.generate()?);
Ok(())
}

File diff suppressed because it is too large Load Diff

View File

@@ -121,7 +121,7 @@ mod tests {
use crate::directives::extract_noqa_line_for;
#[test]
fn extraction() -> Result<()> {
fn extraction() {
let empty: IntMap<usize, usize> = IntMap::default();
let lxr: Vec<LexResult> = lexer::make_tokenizer(
@@ -200,7 +200,5 @@ z = x + 1",
extract_noqa_line_for(&lxr),
IntMap::from_iter([(2, 5), (3, 5), (4, 5)])
);
Ok(())
}
}

View File

@@ -46,14 +46,13 @@ pub fn assert_false(checker: &mut Checker, stmt: &Stmt, test: &Expr, msg: Option
let mut check = Check::new(CheckKind::DoNotAssertFalse, Range::from_located(test));
if checker.patch(check.kind.code()) {
let mut generator = SourceGenerator::new();
if let Ok(()) = generator.unparse_stmt(&assertion_error(msg)) {
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
stmt.location,
stmt.end_location.unwrap(),
));
}
generator.unparse_stmt(&assertion_error(msg));
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
stmt.location,
stmt.end_location.unwrap(),
));
}
}
checker.add_check(check);

View File

@@ -59,14 +59,13 @@ fn duplicate_handler_exceptions<'a>(
if checker.patch(check.kind.code()) {
// TODO(charlie): If we have a single element, remove the tuple.
let mut generator = SourceGenerator::new();
if let Ok(()) = generator.unparse_expr(&type_pattern(unique_elts), 0) {
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
))
}
generator.unparse_expr(&type_pattern(unique_elts), 0);
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
))
}
}
checker.add_check(check);

View File

@@ -35,14 +35,13 @@ pub fn getattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
Check::new(CheckKind::GetAttrWithConstant, Range::from_located(expr));
if checker.patch(check.kind.code()) {
let mut generator = SourceGenerator::new();
if let Ok(()) = generator.unparse_expr(&attribute(obj, value), 0) {
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
));
}
generator.unparse_expr(&attribute(obj, value), 0);
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
));
}
}
checker.add_check(check);

View File

@@ -64,18 +64,17 @@ pub fn redundant_tuple_in_exception_handler(checker: &mut Checker, handlers: &[E
);
if checker.patch(check.kind.code()) {
let mut generator = SourceGenerator::new();
if let Ok(()) = generator.unparse_expr(elt, 0) {
if let Ok(content) = generator.generate() {
match match_tuple_range(handler, checker.locator) {
Ok(range) => {
check.amend(Fix::replacement(
content,
range.location,
range.end_location,
));
}
Err(e) => error!("Failed to locate parentheses: {}", e),
generator.unparse_expr(elt, 0);
if let Ok(content) = generator.generate() {
match match_tuple_range(handler, checker.locator) {
Ok(range) => {
check.amend(Fix::replacement(
content,
range.location,
range.end_location,
));
}
Err(e) => error!("Failed to locate parentheses: {}", e),
}
}
}

View File

@@ -1,3 +1,5 @@
use anyhow::Result;
use log::error;
use rustpython_ast::{Constant, Expr, ExprContext, ExprKind, Location, Stmt, StmtKind};
use crate::ast::types::Range;
@@ -8,7 +10,7 @@ use crate::code_gen::SourceGenerator;
use crate::python::identifiers::IDENTIFIER_REGEX;
use crate::python::keyword::KWLIST;
fn assignment(obj: &Expr, name: &str, value: &Expr) -> Option<String> {
fn assignment(obj: &Expr, name: &str, value: &Expr) -> Result<String> {
let stmt = Stmt::new(
Location::default(),
Location::default(),
@@ -27,10 +29,8 @@ fn assignment(obj: &Expr, name: &str, value: &Expr) -> Option<String> {
},
);
let mut generator = SourceGenerator::new();
match generator.unparse_stmt(&stmt) {
Ok(()) => generator.generate().ok(),
Err(_) => None,
}
generator.unparse_stmt(&stmt);
generator.generate().map_err(|e| e.into())
}
/// B010
@@ -47,13 +47,14 @@ pub fn setattr_with_constant(checker: &mut Checker, expr: &Expr, func: &Expr, ar
let mut check =
Check::new(CheckKind::SetAttrWithConstant, Range::from_located(expr));
if checker.patch(check.kind.code()) {
if let Some(content) = assignment(obj, name, value) {
check.amend(Fix::replacement(
match assignment(obj, name, value) {
Ok(content) => check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
));
}
)),
Err(e) => error!("Failed to fix invalid comparison: {}", e),
};
}
checker.add_check(check);
}

View File

@@ -259,7 +259,7 @@ pub fn autoformat_path(path: &Path) -> Result<()> {
// Generate the AST.
let python_ast = rustpython_helpers::parse_program_tokens(tokens, "<filename>")?;
let mut generator = SourceGenerator::default();
generator.unparse_suite(&python_ast)?;
generator.unparse_suite(&python_ast);
write(path, generator.generate()?)?;
Ok(())

View File

@@ -79,12 +79,7 @@ fn run_once_stdin(settings: &Settings, filename: &Path, autofix: bool) -> Result
Ok(diagnostics)
}
fn run_once(
files: &[PathBuf],
settings: &Settings,
cache: bool,
autofix: bool,
) -> Result<Diagnostics> {
fn run_once(files: &[PathBuf], settings: &Settings, cache: bool, autofix: bool) -> Diagnostics {
// Collect all the files to check.
let start = Instant::now();
let paths: Vec<Result<DirEntry, walkdir::Error>> = files
@@ -138,10 +133,10 @@ fn run_once(
let duration = start.elapsed();
debug!("Checked files in: {:?}", duration);
Ok(diagnostics)
diagnostics
}
fn add_noqa(files: &[PathBuf], settings: &Settings) -> Result<usize> {
fn add_noqa(files: &[PathBuf], settings: &Settings) -> usize {
// Collect all the files to check.
let start = Instant::now();
let paths: Vec<Result<DirEntry, walkdir::Error>> = files
@@ -166,10 +161,10 @@ fn add_noqa(files: &[PathBuf], settings: &Settings) -> Result<usize> {
let duration = start.elapsed();
debug!("Added noqa to files in: {:?}", duration);
Ok(modifications)
modifications
}
fn autoformat(files: &[PathBuf], settings: &Settings) -> Result<usize> {
fn autoformat(files: &[PathBuf], settings: &Settings) -> usize {
// Collect all the files to format.
let start = Instant::now();
let paths: Vec<DirEntry> = files
@@ -192,7 +187,7 @@ fn autoformat(files: &[PathBuf], settings: &Settings) -> Result<usize> {
let duration = start.elapsed();
debug!("Auto-formatted files in: {:?}", duration);
Ok(modifications)
modifications
}
fn inner_main() -> Result<ExitCode> {
@@ -325,7 +320,7 @@ fn inner_main() -> Result<ExitCode> {
printer.clear_screen()?;
printer.write_to_user("Starting linter in watch mode...\n");
let messages = run_once(&cli.files, &settings, cache_enabled, false)?;
let messages = run_once(&cli.files, &settings, cache_enabled, false);
printer.write_continuously(&messages)?;
// Configure the file watcher.
@@ -343,7 +338,7 @@ fn inner_main() -> Result<ExitCode> {
printer.clear_screen()?;
printer.write_to_user("File change detected...\n");
let messages = run_once(&cli.files, &settings, cache_enabled, false)?;
let messages = run_once(&cli.files, &settings, cache_enabled, false);
printer.write_continuously(&messages)?;
}
}
@@ -352,12 +347,12 @@ fn inner_main() -> Result<ExitCode> {
}
}
} else if cli.add_noqa {
let modifications = add_noqa(&cli.files, &settings)?;
let modifications = add_noqa(&cli.files, &settings);
if modifications > 0 && log_level >= LogLevel::Default {
println!("Added {modifications} noqa directives.");
}
} else if cli.autoformat {
let modifications = autoformat(&cli.files, &settings)?;
let modifications = autoformat(&cli.files, &settings);
if modifications > 0 && log_level >= LogLevel::Default {
println!("Formatted {modifications} files.");
}
@@ -370,7 +365,7 @@ fn inner_main() -> Result<ExitCode> {
let path = Path::new(&filename);
run_once_stdin(&settings, path, fix_enabled)?
} else {
run_once(&cli.files, &settings, cache_enabled, fix_enabled)?
run_once(&cli.files, &settings, cache_enabled, fix_enabled)
};
// Always try to print violations (the printer itself may suppress output),

View File

@@ -57,7 +57,7 @@ pub fn add_noqa(
noqa_line_for: &IntMap<usize, usize>,
path: &Path,
) -> Result<usize> {
let (count, output) = add_noqa_inner(checks, contents, noqa_line_for)?;
let (count, output) = add_noqa_inner(checks, contents, noqa_line_for);
fs::write(path, output)?;
Ok(count)
}
@@ -66,7 +66,7 @@ fn add_noqa_inner(
checks: &[Check],
contents: &str,
noqa_line_for: &IntMap<usize, usize>,
) -> Result<(usize, String)> {
) -> (usize, String) {
let lines: Vec<&str> = contents.lines().collect();
let mut matches_by_line: BTreeMap<usize, BTreeSet<&CheckCode>> = BTreeMap::new();
for lineno in 0..lines.len() {
@@ -115,7 +115,7 @@ fn add_noqa_inner(
}
}
Ok((count, output))
(count, output)
}
#[cfg(test)]
@@ -143,11 +143,11 @@ mod tests {
}
#[test]
fn modification() -> Result<()> {
fn modification() {
let checks = vec![];
let contents = "x = 1";
let noqa_line_for = IntMap::default();
let (count, output) = add_noqa_inner(&checks, contents, &noqa_line_for)?;
let (count, output) = add_noqa_inner(&checks, contents, &noqa_line_for);
assert_eq!(count, 0);
assert_eq!(output.trim(), contents.trim());
@@ -160,7 +160,7 @@ mod tests {
)];
let contents = "x = 1";
let noqa_line_for = IntMap::default();
let (count, output) = add_noqa_inner(&checks, contents, &noqa_line_for)?;
let (count, output) = add_noqa_inner(&checks, contents, &noqa_line_for);
assert_eq!(count, 1);
assert_eq!(output.trim(), "x = 1 # noqa: F841".trim());
@@ -182,7 +182,7 @@ mod tests {
];
let contents = "x = 1 # noqa: E741";
let noqa_line_for = IntMap::default();
let (count, output) = add_noqa_inner(&checks, contents, &noqa_line_for)?;
let (count, output) = add_noqa_inner(&checks, contents, &noqa_line_for);
assert_eq!(count, 1);
assert_eq!(output.trim(), "x = 1 # noqa: E741, F841".trim());
@@ -204,10 +204,8 @@ mod tests {
];
let contents = "x = 1 # noqa";
let noqa_line_for = IntMap::default();
let (count, output) = add_noqa_inner(&checks, contents, &noqa_line_for)?;
let (count, output) = add_noqa_inner(&checks, contents, &noqa_line_for);
assert_eq!(count, 1);
assert_eq!(output.trim(), "x = 1 # noqa: E741, F841".trim());
Ok(())
}
}

View File

@@ -24,10 +24,9 @@ fn compare(left: &Expr, ops: &[Cmpop], comparators: &[Expr]) -> Option<String> {
},
);
let mut generator = SourceGenerator::new();
if let Ok(()) = generator.unparse_expr(&cmp, 0) {
if let Ok(content) = generator.generate() {
return Some(content);
}
generator.unparse_expr(&cmp, 0);
if let Ok(content) = generator.generate() {
return Some(content);
}
None
}
@@ -287,7 +286,7 @@ fn function(name: &str, args: &Arguments, body: &Expr) -> Result<String> {
},
);
let mut generator = SourceGenerator::new();
generator.unparse_stmt(&func)?;
generator.unparse_stmt(&func);
Ok(generator.generate()?)
}

View File

@@ -172,7 +172,7 @@ fn convert_to_class(
base_class: &ExprKind,
) -> Result<Fix> {
let mut generator = SourceGenerator::new();
generator.unparse_stmt(&create_class_def_stmt(typename, body, base_class))?;
generator.unparse_stmt(&create_class_def_stmt(typename, body, base_class));
let content = generator.generate()?;
Ok(Fix::replacement(
content,

View File

@@ -209,7 +209,7 @@ fn convert_to_class(
body,
total_keyword,
base_class,
))?;
));
let content = generator.generate()?;
Ok(Fix::replacement(
content,

View File

@@ -66,14 +66,13 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
let mut check = Check::new(CheckKind::UsePEP604Annotation, Range::from_located(expr));
if checker.patch(check.kind.code()) {
let mut generator = SourceGenerator::new();
if let Ok(()) = generator.unparse_expr(&optional(slice), 0) {
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
))
}
generator.unparse_expr(&optional(slice), 0);
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
))
}
}
checker.add_check(check);
@@ -86,27 +85,25 @@ pub fn use_pep604_annotation(checker: &mut Checker, expr: &Expr, value: &Expr, s
}
ExprKind::Tuple { elts, .. } => {
let mut generator = SourceGenerator::new();
if let Ok(()) = generator.unparse_expr(&union(elts), 0) {
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
))
}
generator.unparse_expr(&union(elts), 0);
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
))
}
}
_ => {
// Single argument.
let mut generator = SourceGenerator::new();
if let Ok(()) = generator.unparse_expr(slice, 0) {
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
));
}
generator.unparse_expr(slice, 0);
if let Ok(content) = generator.generate() {
check.amend(Fix::replacement(
content,
expr.location,
expr.end_location.unwrap(),
));
}
}
}