Skip to content

Commit 530497b

Browse files
committed
[unused_braces] Lint multiline blocks as long as not in arms
Currently the lint faces a severe limitation: since it only catches single-line block, running rustfmt beforehand will remove all occurences of it, because it breaks them into multiline blocks. We do not check match `Arm` for two reasons: - In case it does not use commas to separate arms, removing the block would result in a compilation error Example: ``` match expr { pat => {()} _ => println!("foo") } ``` - Do not lint multiline match arms used for formatting reasons ``` match expr { pat => { somewhat_long_expression } // ... } ``` Delete `unused-braces-lint` test The modified lint correctly provide a span in its suggestion. ```shell error: unnecessary braces around block return value --> /rust/src/test/rustdoc-ui/unused-braces-lint.rs:9:5 | LL | / { LL | | { | |________^ LL | use std; LL | } | __________^ LL | | } | |_____^ | note: the lint level is defined here --> /rust/src/test/rustdoc-ui/unused-braces-lint.rs:6:9 | LL | #![deny(unused_braces)] | ^^^^^^^^^^^^^ help: remove these braces | LL ~ { LL | use std; LL ~ } | ``` It is unclear to which extend rust-lang#70814 is still an issue, as the inital MCVE does not trigger the lint on stable either,[rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b6ff31a449c0b73a08daac8ee43b1fa6) Fix code with expanded `unused_braces` lint Also allow `unused_braces` on tests Mute `unused_braces` on `match_ast!`
1 parent 7919ef0 commit 530497b

File tree

31 files changed

+175
-171
lines changed

31 files changed

+175
-171
lines changed

compiler/rustc_codegen_cranelift/src/base.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,10 @@ pub(crate) fn codegen_fn<'tcx>(
5050
let mir = tcx.instance_mir(instance.def);
5151
let _mir_guard = crate::PrintOnPanic(|| {
5252
let mut buf = Vec::new();
53-
with_no_trimmed_paths!({
53+
with_no_trimmed_paths!(
5454
rustc_middle::mir::pretty::write_mir_fn(tcx, mir, &mut |_, _| Ok(()), &mut buf)
55-
.unwrap();
56-
});
55+
.unwrap()
56+
);
5757
String::from_utf8_lossy(&buf).into_owned()
5858
});
5959

@@ -295,9 +295,9 @@ fn codegen_fn_body(fx: &mut FunctionCx<'_, '_, '_>, start_block: Block) {
295295

296296
if fx.clif_comments.enabled() {
297297
let mut terminator_head = "\n".to_string();
298-
with_no_trimmed_paths!({
299-
bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
300-
});
298+
with_no_trimmed_paths!(
299+
bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap()
300+
);
301301
let inst = fx.bcx.func.layout.last_inst(block).unwrap();
302302
fx.add_comment(inst, terminator_head);
303303
}

compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs

+15-17
Original file line numberDiff line numberDiff line change
@@ -465,27 +465,25 @@ pub fn type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>, t: Ty<'tcx>) -> &'ll D
465465
_ => bug!("debuginfo: unexpected type in type_di_node(): {:?}", t),
466466
};
467467

468-
{
469-
if already_stored_in_typemap {
470-
// Make sure that we really do have a `TypeMap` entry for the unique type ID.
471-
let di_node_for_uid =
472-
match debug_context(cx).type_map.di_node_for_unique_id(unique_type_id) {
473-
Some(di_node) => di_node,
474-
None => {
475-
bug!(
476-
"expected type debuginfo node for unique \
468+
if already_stored_in_typemap {
469+
// Make sure that we really do have a `TypeMap` entry for the unique type ID.
470+
let di_node_for_uid = match debug_context(cx).type_map.di_node_for_unique_id(unique_type_id)
471+
{
472+
Some(di_node) => di_node,
473+
None => {
474+
bug!(
475+
"expected type debuginfo node for unique \
477476
type ID '{:?}' to already be in \
478477
the `debuginfo::TypeMap` but it \
479478
was not.",
480-
unique_type_id,
481-
);
482-
}
483-
};
479+
unique_type_id,
480+
);
481+
}
482+
};
484483

485-
debug_assert_eq!(di_node_for_uid as *const _, di_node as *const _);
486-
} else {
487-
debug_context(cx).type_map.insert(unique_type_id, di_node);
488-
}
484+
debug_assert_eq!(di_node_for_uid as *const _, di_node as *const _);
485+
} else {
486+
debug_context(cx).type_map.insert(unique_type_id, di_node);
489487
}
490488

491489
di_node

compiler/rustc_codegen_ssa/src/mir/block.rs

+11-15
Original file line numberDiff line numberDiff line change
@@ -678,21 +678,17 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
678678
MemUninitializedValid => !bx.tcx().permits_uninit_init(bx.param_env().and(layout)),
679679
};
680680
Some(if do_panic {
681-
let msg_str = with_no_visible_paths!({
682-
with_no_trimmed_paths!({
683-
if layout.abi.is_uninhabited() {
684-
// Use this error even for the other intrinsics as it is more precise.
685-
format!("attempted to instantiate uninhabited type `{}`", ty)
686-
} else if intrinsic == ZeroValid {
687-
format!("attempted to zero-initialize type `{}`, which is invalid", ty)
688-
} else {
689-
format!(
690-
"attempted to leave type `{}` uninitialized, which is invalid",
691-
ty
692-
)
693-
}
694-
})
695-
});
681+
let msg_str = with_no_visible_paths!(with_no_trimmed_paths!(if layout
682+
.abi
683+
.is_uninhabited()
684+
{
685+
// Use this error even for the other intrinsics as it is more precise.
686+
format!("attempted to instantiate uninhabited type `{}`", ty)
687+
} else if intrinsic == ZeroValid {
688+
format!("attempted to zero-initialize type `{}`, which is invalid", ty)
689+
} else {
690+
format!("attempted to leave type `{}` uninitialized, which is invalid", ty)
691+
}));
696692
let msg = bx.const_str(&msg_str);
697693

698694
// Obtain the panic entry point.

compiler/rustc_expand/src/placeholders.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -144,17 +144,17 @@ pub fn placeholder(
144144
span,
145145
is_placeholder: true,
146146
}]),
147-
AstFragmentKind::GenericParams => AstFragment::GenericParams(smallvec![{
148-
ast::GenericParam {
147+
AstFragmentKind::GenericParams => {
148+
AstFragment::GenericParams(smallvec![ast::GenericParam {
149149
attrs: Default::default(),
150150
bounds: Default::default(),
151151
id,
152152
ident,
153153
is_placeholder: true,
154154
kind: ast::GenericParamKind::Lifetime,
155155
colon_span: None,
156-
}
157-
}]),
156+
}])
157+
}
158158
AstFragmentKind::Params => AstFragment::Params(smallvec![ast::Param {
159159
attrs: Default::default(),
160160
id,

compiler/rustc_lint/src/context.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -1199,12 +1199,10 @@ impl<'tcx> LateContext<'tcx> {
11991199
}
12001200

12011201
// This shouldn't ever be needed, but just in case:
1202-
with_no_trimmed_paths!({
1203-
Ok(vec![match trait_ref {
1204-
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1205-
None => Symbol::intern(&format!("<{}>", self_ty)),
1206-
}])
1207-
})
1202+
with_no_trimmed_paths!(Ok(vec![match trait_ref {
1203+
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1204+
None => Symbol::intern(&format!("<{}>", self_ty)),
1205+
}]))
12081206
}
12091207

12101208
fn path_append_impl(

compiler/rustc_lint/src/unused.rs

+18-10
Original file line numberDiff line numberDiff line change
@@ -1116,15 +1116,6 @@ impl UnusedDelimLint for UnusedBraces {
11161116
// - the block is not `unsafe`
11171117
// - the block contains exactly one expression (do not lint `{ expr; }`)
11181118
// - `followed_by_block` is true and the internal expr may contain a `{`
1119-
// - the block is not multiline (do not lint multiline match arms)
1120-
// ```
1121-
// match expr {
1122-
// Pattern => {
1123-
// somewhat_long_expression
1124-
// }
1125-
// // ...
1126-
// }
1127-
// ```
11281119
// - the block has no attribute and was not created inside a macro
11291120
// - if the block is an `anon_const`, the inner expr must be a literal
11301121
// not created by a macro, i.e. do not lint on:
@@ -1133,14 +1124,31 @@ impl UnusedDelimLint for UnusedBraces {
11331124
// let _: A<{ 2 + 3 }>;
11341125
// let _: A<{produces_literal!()}>;
11351126
// ```
1127+
//
1128+
// We do not check expression in `Arm` bodies:
1129+
// - if not using commas to separate arms, removing the block would result in a compilation error
1130+
// ```
1131+
// match expr {
1132+
// pat => {()}
1133+
// _ => println!("foo")
1134+
// }
1135+
// ```
1136+
// - multiline blocks can used for formatting
1137+
// ```
1138+
// match expr {
1139+
// pat => {
1140+
// somewhat_long_expression
1141+
// }
1142+
// // ...
1143+
// }
1144+
// ```
11361145
// FIXME(const_generics): handle paths when #67075 is fixed.
11371146
if let [stmt] = inner.stmts.as_slice() {
11381147
if let ast::StmtKind::Expr(ref expr) = stmt.kind {
11391148
if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
11401149
&& (ctx != UnusedDelimsCtx::AnonConst
11411150
|| (matches!(expr.kind, ast::ExprKind::Lit(_))
11421151
&& !expr.span.from_expansion()))
1143-
&& !cx.sess().source_map().is_multiline(value.span)
11441152
&& value.attrs.is_empty()
11451153
&& !value.span.from_expansion()
11461154
&& !inner.span.from_expansion()

compiler/rustc_middle/src/ty/structural_impls.rs

+5-4
Original file line numberDiff line numberDiff line change
@@ -22,27 +22,27 @@ use std::sync::Arc;
2222
impl fmt::Debug for ty::TraitDef {
2323
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2424
ty::tls::with(|tcx| {
25-
with_no_trimmed_paths!({
25+
with_no_trimmed_paths!(
2626
f.write_str(
2727
&FmtPrinter::new(tcx, Namespace::TypeNS)
2828
.print_def_path(self.def_id, &[])?
2929
.into_buffer(),
3030
)
31-
})
31+
)
3232
})
3333
}
3434
}
3535

3636
impl<'tcx> fmt::Debug for ty::AdtDef<'tcx> {
3737
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3838
ty::tls::with(|tcx| {
39-
with_no_trimmed_paths!({
39+
with_no_trimmed_paths!(
4040
f.write_str(
4141
&FmtPrinter::new(tcx, Namespace::TypeNS)
4242
.print_def_path(self.did(), &[])?
4343
.into_buffer(),
4444
)
45-
})
45+
)
4646
})
4747
}
4848
}
@@ -77,6 +77,7 @@ impl fmt::Debug for ty::BoundRegionKind {
7777
write!(f, "BrNamed({:?}, {})", did, name)
7878
}
7979
}
80+
8081
ty::BrEnv => write!(f, "BrEnv"),
8182
}
8283
}

compiler/rustc_mir_build/src/thir/pattern/check_match.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -488,9 +488,9 @@ fn check_for_bindings_named_same_as_variants(
488488
})
489489
{
490490
let variant_count = edef.variants().len();
491-
let ty_path = with_no_trimmed_paths!({
491+
let ty_path = with_no_trimmed_paths!(
492492
cx.tcx.def_path_str(edef.did())
493-
});
493+
);
494494
cx.tcx.emit_spanned_lint(
495495
BINDINGS_WITH_VARIANT_NAME,
496496
p.hir_id,

compiler/rustc_save_analysis/src/lib.rs

+23-25
Original file line numberDiff line numberDiff line change
@@ -964,35 +964,33 @@ pub fn process_crate<H: SaveHandler>(
964964
config: Option<Config>,
965965
mut handler: H,
966966
) {
967-
with_no_trimmed_paths!({
968-
tcx.dep_graph.with_ignore(|| {
969-
info!("Dumping crate {}", cratename);
970-
971-
// Privacy checking must be done outside of type inference; use a
972-
// fallback in case effective visibilities couldn't have been correctly computed.
973-
let effective_visibilities = match tcx.sess.compile_status() {
974-
Ok(..) => tcx.effective_visibilities(()),
975-
Err(..) => tcx.arena.alloc(EffectiveVisibilities::default()),
976-
};
967+
with_no_trimmed_paths!(tcx.dep_graph.with_ignore(|| {
968+
info!("Dumping crate {}", cratename);
969+
970+
// Privacy checking must be done outside of type inference; use a
971+
// fallback in case effective visibilities couldn't have been correctly computed.
972+
let effective_visibilities = match tcx.sess.compile_status() {
973+
Ok(..) => tcx.effective_visibilities(()),
974+
Err(..) => tcx.arena.alloc(EffectiveVisibilities::default()),
975+
};
977976

978-
let save_ctxt = SaveContext {
979-
tcx,
980-
maybe_typeck_results: None,
981-
effective_visibilities: &effective_visibilities,
982-
span_utils: SpanUtils::new(&tcx.sess),
983-
config: find_config(config),
984-
impl_counter: Cell::new(0),
985-
};
977+
let save_ctxt = SaveContext {
978+
tcx,
979+
maybe_typeck_results: None,
980+
effective_visibilities: &effective_visibilities,
981+
span_utils: SpanUtils::new(&tcx.sess),
982+
config: find_config(config),
983+
impl_counter: Cell::new(0),
984+
};
986985

987-
let mut visitor = DumpVisitor::new(save_ctxt);
986+
let mut visitor = DumpVisitor::new(save_ctxt);
988987

989-
visitor.dump_crate_info(cratename);
990-
visitor.dump_compilation_options(input, cratename);
991-
visitor.process_crate();
988+
visitor.dump_crate_info(cratename);
989+
visitor.dump_compilation_options(input, cratename);
990+
visitor.process_crate();
992991

993-
handler.save(&visitor.save_ctxt, &visitor.analysis())
994-
})
995-
})
992+
handler.save(&visitor.save_ctxt, &visitor.analysis())
993+
}))
996994
}
997995

998996
fn find_config(supplied: Option<Config>) -> Config {

compiler/rustc_span/src/hygiene.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -1332,11 +1332,9 @@ pub fn decode_syntax_context<D: Decoder, F: FnOnce(&mut D, u32) -> SyntaxContext
13321332

13331333
let outer_ctxts = &context.remapped_ctxts;
13341334

1335-
// Ensure that the lock() temporary is dropped early
1336-
{
1337-
if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1338-
return ctxt;
1339-
}
1335+
// the lock() temporary is dropped early
1336+
if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() {
1337+
return ctxt;
13401338
}
13411339

13421340
// Allocate and store SyntaxContext id *before* calling the decoder function,

compiler/rustc_trait_selection/src/traits/select/mod.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -2084,13 +2084,15 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
20842084
ty::Adt(def, substs) => {
20852085
let sized_crit = def.sized_constraint(self.tcx());
20862086
// (*) binder moved here
2087-
Where(obligation.predicate.rebind({
2088-
sized_crit
2089-
.0
2090-
.iter()
2091-
.map(|ty| sized_crit.rebind(*ty).subst(self.tcx(), substs))
2092-
.collect()
2093-
}))
2087+
Where(
2088+
obligation.predicate.rebind(
2089+
sized_crit
2090+
.0
2091+
.iter()
2092+
.map(|ty| sized_crit.rebind(*ty).subst(self.tcx(), substs))
2093+
.collect(),
2094+
),
2095+
)
20942096
}
20952097

20962098
ty::Alias(..) | ty::Param(_) => None,

compiler/rustc_ty_utils/src/layout.rs

+3-4
Original file line numberDiff line numberDiff line change
@@ -596,10 +596,9 @@ fn generator_saved_local_eligibility(
596596
}
597597

598598
// Write down the order of our locals that will be promoted to the prefix.
599-
{
600-
for (idx, local) in ineligible_locals.iter().enumerate() {
601-
assignments[local] = Ineligible(Some(idx as u32));
602-
}
599+
600+
for (idx, local) in ineligible_locals.iter().enumerate() {
601+
assignments[local] = Ineligible(Some(idx as u32));
603602
}
604603
debug!("generator saved local assignments: {:?}", assignments);
605604

library/core/src/iter/adapters/step_by.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -88,10 +88,8 @@ where
8888
// overflow handling
8989
loop {
9090
let mul = n.checked_mul(step);
91-
{
92-
if intrinsics::likely(mul.is_some()) {
93-
return self.iter.nth(mul.unwrap() - 1);
94-
}
91+
if intrinsics::likely(mul.is_some()) {
92+
return self.iter.nth(mul.unwrap() - 1);
9593
}
9694
let div_n = usize::MAX / n;
9795
let div_step = usize::MAX / step;

library/core/src/ptr/const_ptr.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -1349,10 +1349,8 @@ impl<T: ?Sized> *const T {
13491349
panic!("align_offset: align is not a power-of-two");
13501350
}
13511351

1352-
{
1353-
// SAFETY: `align` has been checked to be a power of 2 above
1354-
unsafe { align_offset(self, align) }
1355-
}
1352+
// SAFETY: `align` has been checked to be a power of 2 above
1353+
unsafe { align_offset(self, align) }
13561354
}
13571355

13581356
/// Returns whether the pointer is properly aligned for `T`.

library/core/src/ptr/mut_ptr.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -1617,10 +1617,8 @@ impl<T: ?Sized> *mut T {
16171617
panic!("align_offset: align is not a power-of-two");
16181618
}
16191619

1620-
{
1621-
// SAFETY: `align` has been checked to be a power of 2 above
1622-
unsafe { align_offset(self, align) }
1623-
}
1620+
// SAFETY: `align` has been checked to be a power of 2 above
1621+
unsafe { align_offset(self, align) }
16241622
}
16251623

16261624
/// Returns whether the pointer is properly aligned for `T`.

0 commit comments

Comments
 (0)