Skip to content

Commit 9d3e6ba

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
1 parent 0b90256 commit 9d3e6ba

File tree

39 files changed

+250
-273
lines changed

39 files changed

+250
-273
lines changed

compiler/rustc_codegen_cranelift/src/base.rs

Lines changed: 6 additions & 6 deletions
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

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

294294
if fx.clif_comments.enabled() {
295295
let mut terminator_head = "\n".to_string();
296-
with_no_trimmed_paths!({
297-
bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
298-
});
296+
with_no_trimmed_paths!(
297+
bb_data.terminator().kind.fmt_head(&mut terminator_head).unwrap()
298+
);
299299
let inst = fx.bcx.func.layout.last_inst(block).unwrap();
300300
fx.add_comment(inst, terminator_head);
301301
}

compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs

Lines changed: 18 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -649,43 +649,34 @@ fn codegen_regular_intrinsic_call<'tcx>(
649649

650650
let layout = fx.layout_of(substs.type_at(0));
651651
if layout.abi.is_uninhabited() {
652-
with_no_trimmed_paths!({
653-
crate::base::codegen_panic(
654-
fx,
655-
&format!("attempted to instantiate uninhabited type `{}`", layout.ty),
656-
source_info,
657-
)
658-
});
652+
with_no_trimmed_paths!(crate::base::codegen_panic(
653+
fx,
654+
&format!("attempted to instantiate uninhabited type `{}`", layout.ty),
655+
source_info,
656+
));
659657
return;
660658
}
661659

662660
if intrinsic == sym::assert_zero_valid && !fx.tcx.permits_zero_init(layout) {
663-
with_no_trimmed_paths!({
664-
crate::base::codegen_panic(
665-
fx,
666-
&format!(
667-
"attempted to zero-initialize type `{}`, which is invalid",
668-
layout.ty
669-
),
670-
source_info,
671-
);
672-
});
661+
with_no_trimmed_paths!(crate::base::codegen_panic(
662+
fx,
663+
&format!("attempted to zero-initialize type `{}`, which is invalid", layout.ty),
664+
source_info,
665+
));
673666
return;
674667
}
675668

676669
if intrinsic == sym::assert_mem_uninitialized_valid
677670
&& !fx.tcx.permits_uninit_init(layout)
678671
{
679-
with_no_trimmed_paths!({
680-
crate::base::codegen_panic(
681-
fx,
682-
&format!(
683-
"attempted to leave type `{}` uninitialized, which is invalid",
684-
layout.ty
685-
),
686-
source_info,
687-
)
688-
});
672+
with_no_trimmed_paths!(crate::base::codegen_panic(
673+
fx,
674+
&format!(
675+
"attempted to leave type `{}` uninitialized, which is invalid",
676+
layout.ty
677+
),
678+
source_info,
679+
));
689680
return;
690681
}
691682
}

compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs

Lines changed: 15 additions & 17 deletions
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

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -682,21 +682,17 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
682682
MemUninitializedValid => !bx.tcx().permits_uninit_init(layout),
683683
};
684684
Some(if do_panic {
685-
let msg_str = with_no_visible_paths!({
686-
with_no_trimmed_paths!({
687-
if layout.abi.is_uninhabited() {
688-
// Use this error even for the other intrinsics as it is more precise.
689-
format!("attempted to instantiate uninhabited type `{}`", ty)
690-
} else if intrinsic == ZeroValid {
691-
format!("attempted to zero-initialize type `{}`, which is invalid", ty)
692-
} else {
693-
format!(
694-
"attempted to leave type `{}` uninitialized, which is invalid",
695-
ty
696-
)
697-
}
698-
})
699-
});
685+
let msg_str = with_no_visible_paths!(with_no_trimmed_paths!(if layout
686+
.abi
687+
.is_uninhabited()
688+
{
689+
// Use this error even for the other intrinsics as it is more precise.
690+
format!("attempted to instantiate uninhabited type `{}`", ty)
691+
} else if intrinsic == ZeroValid {
692+
format!("attempted to zero-initialize type `{}`, which is invalid", ty)
693+
} else {
694+
format!("attempted to leave type `{}` uninitialized, which is invalid", ty)
695+
}));
700696
let msg = bx.const_str(&msg_str);
701697

702698
// Obtain the panic entry point.

compiler/rustc_expand/src/placeholders.rs

Lines changed: 4 additions & 4 deletions
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

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1194,12 +1194,10 @@ impl<'tcx> LateContext<'tcx> {
11941194
}
11951195

11961196
// This shouldn't ever be needed, but just in case:
1197-
with_no_trimmed_paths!({
1198-
Ok(vec![match trait_ref {
1199-
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1200-
None => Symbol::intern(&format!("<{}>", self_ty)),
1201-
}])
1202-
})
1197+
with_no_trimmed_paths!(Ok(vec![match trait_ref {
1198+
Some(trait_ref) => Symbol::intern(&format!("{:?}", trait_ref)),
1199+
None => Symbol::intern(&format!("<{}>", self_ty)),
1200+
}]))
12031201
}
12041202

12051203
fn path_append_impl(

compiler/rustc_lint/src/unused.rs

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,26 +1084,33 @@ impl UnusedDelimLint for UnusedBraces {
10841084
// - the block is not `unsafe`
10851085
// - the block contains exactly one expression (do not lint `{ expr; }`)
10861086
// - `followed_by_block` is true and the internal expr may contain a `{`
1087-
// - the block is not multiline (do not lint multiline match arms)
1088-
// ```
1089-
// match expr {
1090-
// Pattern => {
1091-
// somewhat_long_expression
1092-
// }
1093-
// // ...
1094-
// }
1095-
// ```
10961087
// - the block has no attribute and was not created inside a macro
10971088
// - if the block is an `anon_const`, the inner expr must be a literal
10981089
// (do not lint `struct A<const N: usize>; let _: A<{ 2 + 3 }>;`)
10991090
//
1091+
// We do not check expression in `Arm` bodies:
1092+
// - if not using commas to separate arms, removing the block would result in a compilation error
1093+
// ```
1094+
// match expr {
1095+
// pat => {()}
1096+
// _ => println!("foo")
1097+
// }
1098+
// ```
1099+
// - multiline blocks can used for formatting
1100+
// ```
1101+
// match expr {
1102+
// pat => {
1103+
// somewhat_long_expression
1104+
// }
1105+
// // ...
1106+
// }
1107+
// ```
11001108
// FIXME(const_generics): handle paths when #67075 is fixed.
11011109
if let [stmt] = inner.stmts.as_slice() {
11021110
if let ast::StmtKind::Expr(ref expr) = stmt.kind {
11031111
if !Self::is_expr_delims_necessary(expr, followed_by_block, false)
11041112
&& (ctx != UnusedDelimsCtx::AnonConst
11051113
|| matches!(expr.kind, ast::ExprKind::Lit(_)))
1106-
&& !cx.sess().source_map().is_multiline(value.span)
11071114
&& value.attrs.is_empty()
11081115
&& !value.span.from_expansion()
11091116
&& !inner.span.from_expansion()

compiler/rustc_middle/src/ty/structural_impls.rs

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

3535
impl<'tcx> fmt::Debug for ty::AdtDef<'tcx> {
3636
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3737
ty::tls::with(|tcx| {
38-
with_no_trimmed_paths!({
38+
with_no_trimmed_paths!(
3939
f.write_str(
4040
&FmtPrinter::new(tcx, Namespace::TypeNS)
4141
.print_def_path(self.did(), &[])?
4242
.into_buffer(),
4343
)
44-
})
44+
)
4545
})
4646
}
4747
}
@@ -76,6 +76,7 @@ impl fmt::Debug for ty::BoundRegionKind {
7676
write!(f, "BrNamed({:?}, {})", did, name)
7777
}
7878
}
79+
7980
ty::BrEnv => write!(f, "BrEnv"),
8081
}
8182
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -476,9 +476,9 @@ fn check_for_bindings_named_same_as_variants(
476476
})
477477
{
478478
let variant_count = edef.variants().len();
479-
let ty_path = with_no_trimmed_paths!({
479+
let ty_path = with_no_trimmed_paths!(
480480
cx.tcx.def_path_str(edef.did())
481-
});
481+
);
482482
cx.tcx.emit_spanned_lint(
483483
BINDINGS_WITH_VARIANT_NAME,
484484
p.hir_id,

compiler/rustc_save_analysis/src/lib.rs

Lines changed: 23 additions & 25 deletions
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

Lines changed: 3 additions & 5 deletions
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

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2055,13 +2055,15 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
20552055
ty::Adt(def, substs) => {
20562056
let sized_crit = def.sized_constraint(self.tcx());
20572057
// (*) binder moved here
2058-
Where(obligation.predicate.rebind({
2059-
sized_crit
2060-
.0
2061-
.iter()
2062-
.map(|ty| sized_crit.rebind(*ty).subst(self.tcx(), substs))
2063-
.collect()
2064-
}))
2058+
Where(
2059+
obligation.predicate.rebind(
2060+
sized_crit
2061+
.0
2062+
.iter()
2063+
.map(|ty| sized_crit.rebind(*ty).subst(self.tcx(), substs))
2064+
.collect(),
2065+
),
2066+
)
20652067
}
20662068

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

0 commit comments

Comments
 (0)