diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 21255fcca9617..f4e8f12b719d3 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -3505,7 +3505,7 @@ pub fn is_case_difference(sm: &SourceMap, suggested: &str, sp: Span) -> bool { // All the chars that differ in capitalization are confusable (above): let confusable = iter::zip(found.chars(), suggested.chars()) .filter(|(f, s)| f != s) - .all(|(f, s)| (ascii_confusables.contains(&f) || ascii_confusables.contains(&s))); + .all(|(f, s)| ascii_confusables.contains(&f) || ascii_confusables.contains(&s)); confusable && found.to_lowercase() == suggested.to_lowercase() // FIXME: We sometimes suggest the same thing we already have, which is a // bug, but be defensive against that here. diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 7b43aac90c741..75d2630f12887 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -2,7 +2,7 @@ use std::iter; use rustc_ast as ast; use rustc_ast::util::{classify, parser}; -use rustc_ast::{ExprKind, StmtKind}; +use rustc_ast::{ExprKind, FnRetTy, StmtKind}; use rustc_errors::{MultiSpan, pluralize}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; @@ -593,6 +593,7 @@ enum UnusedDelimsCtx { AnonConst, MatchArmExpr, IndexExpr, + ClosureBody, } impl From for &'static str { @@ -614,6 +615,7 @@ impl From for &'static str { UnusedDelimsCtx::ArrayLenExpr | UnusedDelimsCtx::AnonConst => "const expression", UnusedDelimsCtx::MatchArmExpr => "match arm expression", UnusedDelimsCtx::IndexExpr => "index expression", + UnusedDelimsCtx::ClosureBody => "closure body", } } } @@ -909,6 +911,14 @@ trait UnusedDelimLint { let (args_to_check, ctx) = match *call_or_other { Call(_, ref args) => (&args[..], UnusedDelimsCtx::FunctionArg), MethodCall(ref call) => (&call.args[..], UnusedDelimsCtx::MethodArg), + Closure(ref closure) + if matches!(closure.fn_decl.output, FnRetTy::Default(_)) + // skip `#[core::contracts::requires(...)]` and `#[core::contracts::ensures(...)]` + // which generate closure expr with span that is same as the inner closure body span + && e.span != closure.body.span => + { + (&[closure.body.clone()][..], UnusedDelimsCtx::ClosureBody) + } // actual catch-all arm _ => { return; diff --git a/compiler/rustc_mir_transform/src/coverage/counters/node_flow.rs b/compiler/rustc_mir_transform/src/coverage/counters/node_flow.rs index 91ed54b8b59f5..f7f22f0465002 100644 --- a/compiler/rustc_mir_transform/src/coverage/counters/node_flow.rs +++ b/compiler/rustc_mir_transform/src/coverage/counters/node_flow.rs @@ -261,7 +261,7 @@ impl<'a, Node: Idx> SpantreeBuilder<'a, Node> { debug_assert!( span_edges .iter_enumerated() - .all(|(node, span_edge)| { span_edge.is_some() <= self.is_supernode(node) }), + .all(|(node, span_edge)| span_edge.is_some() <= self.is_supernode(node)), "only supernodes can have a span edge", ); debug_assert!( diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index 1ccae0fd7fe95..651dcd27b7c00 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -159,7 +159,7 @@ fn create_mappings(extracted_mappings: &ExtractedMappings) -> Vec { condition_info: _, true_index: _, false_index: _, - }| { Mapping { kind: MappingKind::Branch { true_bcb, false_bcb }, span } }, + }| Mapping { kind: MappingKind::Branch { true_bcb, false_bcb }, span }, )); for (decision, branches) in mcdc_mappings { diff --git a/compiler/rustc_mir_transform/src/coverage/tests.rs b/compiler/rustc_mir_transform/src/coverage/tests.rs index 3c0053c610d14..9263cf1c60185 100644 --- a/compiler/rustc_mir_transform/src/coverage/tests.rs +++ b/compiler/rustc_mir_transform/src/coverage/tests.rs @@ -217,7 +217,7 @@ fn print_mir_graphviz(name: &str, mir_body: &Body<'_>) { mir_body .basic_blocks .successors(bb) - .map(|successor| { format!(" {:?} -> {:?};", bb, successor) }) + .map(|successor| format!(" {:?} -> {:?};", bb, successor)) .join("\n") ) }) @@ -241,7 +241,7 @@ fn print_coverage_graphviz(name: &str, mir_body: &Body<'_>, graph: &graph::Cover mir_body[bcb_data.last_bb()].terminator().kind.name(), graph .successors(bcb) - .map(|successor| { format!(" {:?} -> {:?};", bcb, successor) }) + .map(|successor| format!(" {:?} -> {:?};", bcb, successor)) .join("\n") ) }) diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 0b9350c71992a..8add068464045 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -2201,7 +2201,7 @@ impl<'a> Parser<'a> { if self.look_ahead(1, |t| *t == token::Bang) && self.look_ahead(2, |t| t.is_ident()) { return IsMacroRulesItem::Yes { has_bang: true }; - } else if self.look_ahead(1, |t| (t.is_ident())) { + } else if self.look_ahead(1, |t| t.is_ident()) { // macro_rules foo self.dcx().emit_err(errors::MacroRulesMissingBang { span: macro_rules_span, diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 84858cfc1b1e4..da8db8f773f2d 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -326,8 +326,7 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { let module_did = mod_prefix.as_ref().and_then(Res::mod_def_id); let mod_prefix = - mod_prefix.map_or_else(String::new, |res| (format!("{} ", res.descr()))); - + mod_prefix.map_or_else(String::new, |res| format!("{} ", res.descr())); (mod_prefix, format!("`{}`", Segment::names_to_string(mod_path)), module_did, None) }; diff --git a/library/alloc/src/collections/btree/map/entry.rs b/library/alloc/src/collections/btree/map/entry.rs index ea8fa363c3805..8a0660efa3303 100644 --- a/library/alloc/src/collections/btree/map/entry.rs +++ b/library/alloc/src/collections/btree/map/entry.rs @@ -247,12 +247,12 @@ impl<'a, K: Ord, V, A: Allocator + Clone> Entry<'a, K, V, A> { /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); /// /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) + /// .and_modify(|e| *e += 1) /// .or_insert(42); /// assert_eq!(map["poneyland"], 42); /// /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) + /// .and_modify(|e| *e += 1) /// .or_insert(42); /// assert_eq!(map["poneyland"], 43); /// ``` diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index da9a77154f9b5..be36553f8086d 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -3654,7 +3654,7 @@ impl Vec { /// /// ``` /// # use std::cmp::min; - /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 }; + /// # let some_predicate = |x: &mut i32| *x == 2 || *x == 3 || *x == 6; /// # let mut vec = vec![1, 2, 3, 4, 5, 6]; /// # let range = 1..4; /// let mut i = range.start; diff --git a/library/std/src/collections/hash/map.rs b/library/std/src/collections/hash/map.rs index ff4a4b35ce450..91f03f85c5e61 100644 --- a/library/std/src/collections/hash/map.rs +++ b/library/std/src/collections/hash/map.rs @@ -2026,13 +2026,13 @@ impl<'a, K, V, S> RawEntryMut<'a, K, V, S> { /// /// map.raw_entry_mut() /// .from_key("poneyland") - /// .and_modify(|_k, v| { *v += 1 }) + /// .and_modify(|_k, v| *v += 1) /// .or_insert("poneyland", 42); /// assert_eq!(map["poneyland"], 42); /// /// map.raw_entry_mut() /// .from_key("poneyland") - /// .and_modify(|_k, v| { *v += 1 }) + /// .and_modify(|_k, v| *v += 1) /// .or_insert("poneyland", 0); /// assert_eq!(map["poneyland"], 43); /// ``` @@ -2883,12 +2883,12 @@ impl<'a, K, V> Entry<'a, K, V> { /// let mut map: HashMap<&str, u32> = HashMap::new(); /// /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) + /// .and_modify(|e| *e += 1) /// .or_insert(42); /// assert_eq!(map["poneyland"], 42); /// /// map.entry("poneyland") - /// .and_modify(|e| { *e += 1 }) + /// .and_modify(|e| *e += 1) /// .or_insert(42); /// assert_eq!(map["poneyland"], 43); /// ``` diff --git a/library/std/src/sync/poison/condvar.rs b/library/std/src/sync/poison/condvar.rs index 7f0f3f652bcb7..9c9d8d32fd90e 100644 --- a/library/std/src/sync/poison/condvar.rs +++ b/library/std/src/sync/poison/condvar.rs @@ -238,7 +238,7 @@ impl Condvar { /// // Wait for the thread to start up. /// let (lock, cvar) = &*pair; /// // As long as the value inside the `Mutex` is `true`, we wait. - /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| { *pending }).unwrap(); + /// let _guard = cvar.wait_while(lock.lock().unwrap(), |pending| *pending).unwrap(); /// ``` #[stable(feature = "wait_until", since = "1.42.0")] pub fn wait_while<'a, T, F>( diff --git a/library/std/tests/env_modify.rs b/library/std/tests/env_modify.rs index ba84978b35f8f..fc48fb20f8ea2 100644 --- a/library/std/tests/env_modify.rs +++ b/library/std/tests/env_modify.rs @@ -91,9 +91,9 @@ fn test_env_set_var() { unsafe { set_var(&n, "VALUE"); } - assert!(!e.any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); + assert!(!e.any(|(k, v)| &*k == &*n && &*v == "VALUE")); - assert!(vars_os().any(|(k, v)| { &*k == &*n && &*v == "VALUE" })); + assert!(vars_os().any(|(k, v)| &*k == &*n && &*v == "VALUE")); } #[test] diff --git a/src/etc/test-float-parse/src/lib.rs b/src/etc/test-float-parse/src/lib.rs index def66398d9fd1..a0c4eebd90784 100644 --- a/src/etc/test-float-parse/src/lib.rs +++ b/src/etc/test-float-parse/src/lib.rs @@ -333,7 +333,7 @@ fn launch_tests(tests: &mut [TestInfo], cfg: &Config) -> Duration { for test in tests.iter_mut() { test.progress = Some(ui::Progress::new(test, &mut all_progress_bars)); ui::set_panic_hook(&all_progress_bars); - ((test.launch)(test, cfg)); + (test.launch)(test, cfg); } start.elapsed() diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 8b8439a253527..8896bad329d21 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -1307,7 +1307,7 @@ impl clean::FnDecl { fmt::from_fn(move |f| { // First, generate the text form of the declaration, with no line wrapping, and count the bytes. let mut counter = WriteCounter(0); - write!(&mut counter, "{:#}", fmt::from_fn(|f| { self.inner_full_print(None, f, cx) })) + write!(&mut counter, "{:#}", fmt::from_fn(|f| self.inner_full_print(None, f, cx))) .unwrap(); // If the text form was over 80 characters wide, we will line-wrap our output. let line_wrapping_indent = diff --git a/src/tools/clippy/clippy_lints/src/unused_async.rs b/src/tools/clippy/clippy_lints/src/unused_async.rs index 1c1c841e96412..013b9a6e568f2 100644 --- a/src/tools/clippy/clippy_lints/src/unused_async.rs +++ b/src/tools/clippy/clippy_lints/src/unused_async.rs @@ -165,7 +165,7 @@ impl<'tcx> LateLintPass<'tcx> for UnusedAsync { let iter = self .unused_async_fns .iter() - .filter(|UnusedAsyncFn { def_id, .. }| (!self.async_fns_as_value.contains(def_id))); + .filter(|UnusedAsyncFn { def_id, .. }| !self.async_fns_as_value.contains(def_id)); for fun in iter { span_lint_hir_and_then( diff --git a/src/tools/clippy/clippy_utils/src/higher.rs b/src/tools/clippy/clippy_utils/src/higher.rs index c4d00002292c9..5079d622759d9 100644 --- a/src/tools/clippy/clippy_utils/src/higher.rs +++ b/src/tools/clippy/clippy_utils/src/higher.rs @@ -172,7 +172,7 @@ impl<'hir> IfLetOrMatch<'hir> { if_then, if_else, let_span, - }| { Self::IfLet(let_expr, let_pat, if_then, if_else, let_span) }, + }| Self::IfLet(let_expr, let_pat, if_then, if_else, let_span), ), } } diff --git a/src/tools/clippy/clippy_utils/src/ty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/mod.rs index 6fdf4c244f8d8..44c270e22429c 100644 --- a/src/tools/clippy/clippy_utils/src/ty/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ty/mod.rs @@ -947,7 +947,7 @@ impl AdtVariantInfo { .enumerate() .map(|(i, f)| (i, approx_ty_size(cx, f.ty(cx.tcx, subst)))) .collect::>(); - fields_size.sort_by(|(_, a_size), (_, b_size)| (a_size.cmp(b_size))); + fields_size.sort_by(|(_, a_size), (_, b_size)| a_size.cmp(b_size)); Self { ind: i, @@ -956,7 +956,7 @@ impl AdtVariantInfo { } }) .collect::>(); - variants_size.sort_by(|a, b| (b.size.cmp(&a.size))); + variants_size.sort_by(|a, b| b.size.cmp(&a.size)); variants_size } } diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs index 6e250ca12c937..2ab53b35b7e9c 100644 --- a/src/tools/compiletest/src/runtest.rs +++ b/src/tools/compiletest/src/runtest.rs @@ -1715,6 +1715,12 @@ impl<'test> TestCx<'test> { // Allow tests to use internal features. rustc.args(&["-A", "internal_features"]); + // Allow tests to have unused parens and braces. + // Add #![deny(unused_parens, unused_braces)] to the test file if you want to + // test that these lints are working. + rustc.args(&["-A", "unused_parens"]); + rustc.args(&["-A", "unused_braces"]); + if self.props.force_host { self.maybe_add_external_args(&mut rustc, &self.config.host_rustcflags); if !is_rustdoc { diff --git a/src/tools/miri/src/concurrency/thread.rs b/src/tools/miri/src/concurrency/thread.rs index a8a2491304dd1..fa86550a72d3b 100644 --- a/src/tools/miri/src/concurrency/thread.rs +++ b/src/tools/miri/src/concurrency/thread.rs @@ -641,7 +641,7 @@ impl<'tcx> ThreadManager<'tcx> { assert!( self.threads .iter() - .all(|thread| { !thread.state.is_blocked_on(BlockReason::Join(joined_thread_id)) }), + .all(|thread| !thread.state.is_blocked_on(BlockReason::Join(joined_thread_id))), "this thread already has threads waiting for its termination" ); diff --git a/tests/ui/async-await/issues/issue-54752-async-block.rs b/tests/ui/async-await/issues/issue-54752-async-block.rs index 452b6794bee06..164c1885da11c 100644 --- a/tests/ui/async-await/issues/issue-54752-async-block.rs +++ b/tests/ui/async-await/issues/issue-54752-async-block.rs @@ -4,4 +4,3 @@ //@ pp-exact fn main() { let _a = (async { }); } -//~^ WARNING unnecessary parentheses around assigned value diff --git a/tests/ui/async-await/issues/issue-54752-async-block.stderr b/tests/ui/async-await/issues/issue-54752-async-block.stderr deleted file mode 100644 index 8cc849dd98544..0000000000000 --- a/tests/ui/async-await/issues/issue-54752-async-block.stderr +++ /dev/null @@ -1,15 +0,0 @@ -warning: unnecessary parentheses around assigned value - --> $DIR/issue-54752-async-block.rs:6:22 - | -LL | fn main() { let _a = (async { }); } - | ^ ^ - | - = note: `#[warn(unused_parens)]` on by default -help: remove these parentheses - | -LL - fn main() { let _a = (async { }); } -LL + fn main() { let _a = async { }; } - | - -warning: 1 warning emitted - diff --git a/tests/ui/lint/unused/closure-body-issue-136741.fixed b/tests/ui/lint/unused/closure-body-issue-136741.fixed new file mode 100644 index 0000000000000..075ac7ae6c781 --- /dev/null +++ b/tests/ui/lint/unused/closure-body-issue-136741.fixed @@ -0,0 +1,36 @@ +//@ run-rustfix +// ignore-tidy-linelength +#![deny(unused_parens)] +#![deny(unused_braces)] + +fn long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() +{} + +fn func(f: impl FnOnce()) { + f() +} + +pub fn main() { + let _closure = |x: i32, y: i32| x * (x + (y * 2)); //~ ERROR unnecessary braces around closure body + let _ = || 0 == 0; //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| n % 2 == 0); //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| n % 2 == 0); //~ ERROR unnecessary braces around closure body + + // multiple lines of code will not lint with braces + let _ = (0..).find(|n| { + n % 2 == 0 + }); + + // multiple lines of code will lint with parentheses + let _ = (0..).find(|n| n % 2 == 0); + + let _ = || { + _ = 0; + 0 == 0 //~ ERROR unnecessary parentheses around block return value + }; + + // long expressions will not lint with braces + func(|| { + long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() + }) +} diff --git a/tests/ui/lint/unused/closure-body-issue-136741.rs b/tests/ui/lint/unused/closure-body-issue-136741.rs new file mode 100644 index 0000000000000..84945ac7aa768 --- /dev/null +++ b/tests/ui/lint/unused/closure-body-issue-136741.rs @@ -0,0 +1,38 @@ +//@ run-rustfix +// ignore-tidy-linelength +#![deny(unused_parens)] +#![deny(unused_braces)] + +fn long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() +{} + +fn func(f: impl FnOnce()) { + f() +} + +pub fn main() { + let _closure = |x: i32, y: i32| { x * (x + (y * 2)) }; //~ ERROR unnecessary braces around closure body + let _ = || (0 == 0); //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| (n % 2 == 0)); //~ ERROR unnecessary parentheses around closure body + let _ = (0..).find(|n| {n % 2 == 0}); //~ ERROR unnecessary braces around closure body + + // multiple lines of code will not lint with braces + let _ = (0..).find(|n| { + n % 2 == 0 + }); + + // multiple lines of code will lint with parentheses + let _ = (0..).find(|n| ( //~ ERROR unnecessary parentheses around closure body + n % 2 == 0 + )); + + let _ = || { + _ = 0; + (0 == 0) //~ ERROR unnecessary parentheses around block return value + }; + + // long expressions will not lint with braces + func(|| { + long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces_long_expr_that_does_not_require_braces() + }) +} diff --git a/tests/ui/lint/unused/closure-body-issue-136741.stderr b/tests/ui/lint/unused/closure-body-issue-136741.stderr new file mode 100644 index 0000000000000..ac69f1cc27039 --- /dev/null +++ b/tests/ui/lint/unused/closure-body-issue-136741.stderr @@ -0,0 +1,91 @@ +error: unnecessary braces around closure body + --> $DIR/closure-body-issue-136741.rs:14:37 + | +LL | let _closure = |x: i32, y: i32| { x * (x + (y * 2)) }; + | ^^ ^^ + | +note: the lint level is defined here + --> $DIR/closure-body-issue-136741.rs:4:9 + | +LL | #![deny(unused_braces)] + | ^^^^^^^^^^^^^ +help: remove these braces + | +LL - let _closure = |x: i32, y: i32| { x * (x + (y * 2)) }; +LL + let _closure = |x: i32, y: i32| x * (x + (y * 2)); + | + +error: unnecessary parentheses around closure body + --> $DIR/closure-body-issue-136741.rs:15:16 + | +LL | let _ = || (0 == 0); + | ^ ^ + | +note: the lint level is defined here + --> $DIR/closure-body-issue-136741.rs:3:9 + | +LL | #![deny(unused_parens)] + | ^^^^^^^^^^^^^ +help: remove these parentheses + | +LL - let _ = || (0 == 0); +LL + let _ = || 0 == 0; + | + +error: unnecessary parentheses around closure body + --> $DIR/closure-body-issue-136741.rs:16:28 + | +LL | let _ = (0..).find(|n| (n % 2 == 0)); + | ^ ^ + | +help: remove these parentheses + | +LL - let _ = (0..).find(|n| (n % 2 == 0)); +LL + let _ = (0..).find(|n| n % 2 == 0); + | + +error: unnecessary braces around closure body + --> $DIR/closure-body-issue-136741.rs:17:28 + | +LL | let _ = (0..).find(|n| {n % 2 == 0}); + | ^ ^ + | +help: remove these braces + | +LL - let _ = (0..).find(|n| {n % 2 == 0}); +LL + let _ = (0..).find(|n| n % 2 == 0); + | + +error: unnecessary parentheses around closure body + --> $DIR/closure-body-issue-136741.rs:25:28 + | +LL | let _ = (0..).find(|n| ( + | _____________________________^ +LL | | n % 2 == 0 + | | ________^__________^ + | ||________| + | | +LL | | )); + | |_____^ + | +help: remove these parentheses + | +LL - let _ = (0..).find(|n| ( +LL - n % 2 == 0 +LL + let _ = (0..).find(|n| n % 2 == 0); + | + +error: unnecessary parentheses around block return value + --> $DIR/closure-body-issue-136741.rs:31:9 + | +LL | (0 == 0) + | ^ ^ + | +help: remove these parentheses + | +LL - (0 == 0) +LL + 0 == 0 + | + +error: aborting due to 6 previous errors +