Skip to content

Commit fde1b76

Browse files
Use if-let guards in the codebase
1 parent a992a11 commit fde1b76

File tree

27 files changed

+241
-253
lines changed

27 files changed

+241
-253
lines changed

compiler/rustc_ast/src/attr/mod.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -564,11 +564,11 @@ impl NestedMetaItem {
564564
I: Iterator<Item = TokenTree>,
565565
{
566566
match tokens.peek() {
567-
Some(TokenTree::Token(token)) => {
568-
if let Ok(lit) = Lit::from_token(token) {
569-
tokens.next();
570-
return Some(NestedMetaItem::Literal(lit));
571-
}
567+
Some(TokenTree::Token(token))
568+
if let Ok(lit) = Lit::from_token(token) =>
569+
{
570+
tokens.next();
571+
return Some(NestedMetaItem::Literal(lit));
572572
}
573573
Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => {
574574
let inner_tokens = inner_tokens.clone();

compiler/rustc_ast/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@
1111
#![feature(box_patterns)]
1212
#![cfg_attr(bootstrap, feature(const_fn_transmute))]
1313
#![feature(crate_visibility_modifier)]
14+
#![feature(if_let_guard)]
1415
#![feature(iter_zip)]
1516
#![feature(label_break_value)]
1617
#![feature(nll)]
1718
#![feature(min_specialization)]
19+
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
1820
#![recursion_limit = "256"]
1921

2022
#[macro_use]

compiler/rustc_errors/src/lib.rs

+9-7
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,11 @@
55
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
66
#![feature(crate_visibility_modifier)]
77
#![feature(backtrace)]
8+
#![feature(if_let_guard)]
89
#![feature(format_args_capture)]
910
#![feature(iter_zip)]
1011
#![feature(nll)]
12+
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
1113

1214
#[macro_use]
1315
extern crate rustc_macros;
@@ -1027,15 +1029,15 @@ impl HandlerInner {
10271029
let mut error_codes = self
10281030
.emitted_diagnostic_codes
10291031
.iter()
1030-
.filter_map(|x| match &x {
1031-
DiagnosticId::Error(s) => {
1032-
if let Ok(Some(_explanation)) = registry.try_find_description(s) {
1033-
Some(s.clone())
1034-
} else {
1035-
None
1036-
}
1032+
.filter_map(|x| {
1033+
match &x {
1034+
DiagnosticId::Error(s)
1035+
if let Ok(Some(_explanation)) = registry.try_find_description(s) =>
1036+
{
1037+
Some(s.clone())
10371038
}
10381039
_ => None,
1040+
}
10391041
})
10401042
.collect::<Vec<_>>();
10411043
if !error_codes.is_empty() {

compiler/rustc_expand/src/config.rs

+7-8
Original file line numberDiff line numberDiff line change
@@ -305,15 +305,14 @@ impl<'a> StripUnconfigured<'a> {
305305
Some((AttrAnnotatedTokenTree::Delimited(sp, delim, inner), *spacing))
306306
.into_iter()
307307
}
308+
AttrAnnotatedTokenTree::Token(ref token) if let TokenKind::Interpolated(ref nt) = token.kind => {
309+
panic!(
310+
"Nonterminal should have been flattened at {:?}: {:?}",
311+
token.span, nt
312+
);
313+
}
308314
AttrAnnotatedTokenTree::Token(token) => {
309-
if let TokenKind::Interpolated(nt) = token.kind {
310-
panic!(
311-
"Nonterminal should have been flattened at {:?}: {:?}",
312-
token.span, nt
313-
);
314-
} else {
315-
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
316-
}
315+
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
317316
}
318317
})
319318
.collect();

compiler/rustc_expand/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
#![feature(decl_macro)]
33
#![feature(destructuring_assignment)]
44
#![feature(format_args_capture)]
5+
#![feature(if_let_guard)]
56
#![feature(iter_zip)]
67
#![feature(proc_macro_diagnostic)]
78
#![feature(proc_macro_internals)]
89
#![feature(proc_macro_span)]
910
#![feature(try_blocks)]
11+
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
1012

1113
#[macro_use]
1214
extern crate rustc_macros;

compiler/rustc_expand/src/module.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -86,13 +86,12 @@ crate fn mod_dir_path(
8686
inline: Inline,
8787
) -> (PathBuf, DirOwnership) {
8888
match inline {
89+
Inline::Yes if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) => {
90+
// For inline modules file path from `#[path]` is actually the directory path
91+
// for historical reasons, so we don't pop the last segment here.
92+
(file_path, DirOwnership::Owned { relative: None })
93+
}
8994
Inline::Yes => {
90-
if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) {
91-
// For inline modules file path from `#[path]` is actually the directory path
92-
// for historical reasons, so we don't pop the last segment here.
93-
return (file_path, DirOwnership::Owned { relative: None });
94-
}
95-
9695
// We have to push on the current module name in the case of relative
9796
// paths in order to ensure that any additional module paths from inline
9897
// `mod x { ... }` come after the relative extension.

compiler/rustc_expand/src/proc_macro_server.rs

+12-11
Original file line numberDiff line numberDiff line change
@@ -178,18 +178,19 @@ impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_>)>
178178
tt!(Punct::new('#', false))
179179
}
180180

181+
Interpolated(nt)
182+
if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) =>
183+
{
184+
TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
185+
}
181186
Interpolated(nt) => {
182-
if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) {
183-
TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
184-
} else {
185-
let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
186-
TokenTree::Group(Group {
187-
delimiter: Delimiter::None,
188-
stream,
189-
span: DelimSpan::from_single(span),
190-
flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
191-
})
192-
}
187+
let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
188+
TokenTree::Group(Group {
189+
delimiter: Delimiter::None,
190+
stream,
191+
span: DelimSpan::from_single(span),
192+
flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
193+
})
193194
}
194195

195196
OpenDelim(..) | CloseDelim(..) => unreachable!(),

compiler/rustc_middle/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
#![feature(box_patterns)]
3232
#![feature(core_intrinsics)]
3333
#![feature(discriminant_kind)]
34+
#![feature(if_let_guard)]
3435
#![feature(never_type)]
3536
#![feature(extern_types)]
3637
#![feature(new_uninit)]
@@ -52,6 +53,7 @@
5253
#![feature(try_reserve)]
5354
#![feature(try_reserve_kind)]
5455
#![feature(nonzero_ops)]
56+
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
5557
#![recursion_limit = "512"]
5658

5759
#[macro_use]

compiler/rustc_middle/src/ty/error.rs

+13-17
Original file line numberDiff line numberDiff line change
@@ -279,13 +279,10 @@ impl<'tcx> ty::TyS<'tcx> {
279279
}
280280
ty::FnDef(..) => "fn item".into(),
281281
ty::FnPtr(_) => "fn pointer".into(),
282-
ty::Dynamic(ref inner, ..) => {
283-
if let Some(principal) = inner.principal() {
284-
format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
285-
} else {
286-
"trait object".into()
287-
}
282+
ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
283+
format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
288284
}
285+
ty::Dynamic(..) => "trait object".into(),
289286
ty::Closure(..) => "closure".into(),
290287
ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
291288
ty::GeneratorWitness(..) => "generator witness".into(),
@@ -365,20 +362,19 @@ impl<'tcx> TyCtxt<'tcx> {
365362
// Issue #63167
366363
db.note("distinct uses of `impl Trait` result in different opaque types");
367364
}
368-
(ty::Float(_), ty::Infer(ty::IntVar(_))) => {
365+
(ty::Float(_), ty::Infer(ty::IntVar(_)))
369366
if let Ok(
370367
// Issue #53280
371368
snippet,
372-
) = self.sess.source_map().span_to_snippet(sp)
373-
{
374-
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
375-
db.span_suggestion(
376-
sp,
377-
"use a float literal",
378-
format!("{}.0", snippet),
379-
MachineApplicable,
380-
);
381-
}
369+
) = self.sess.source_map().span_to_snippet(sp) =>
370+
{
371+
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
372+
db.span_suggestion(
373+
sp,
374+
"use a float literal",
375+
format!("{}.0", snippet),
376+
MachineApplicable,
377+
);
382378
}
383379
}
384380
(ty::Param(expected), ty::Param(found)) => {

compiler/rustc_middle/src/ty/util.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -225,14 +225,12 @@ impl<'tcx> TyCtxt<'tcx> {
225225
}
226226
}
227227

228-
ty::Tuple(tys) => {
229-
if let Some((&last_ty, _)) = tys.split_last() {
230-
ty = last_ty.expect_ty();
231-
} else {
232-
break;
233-
}
228+
ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
229+
ty = last_ty.expect_ty();
234230
}
235231

232+
ty::Tuple(_) => break,
233+
236234
ty::Projection(_) | ty::Opaque(..) => {
237235
let normalized = normalize(ty);
238236
if ty == normalized {

compiler/rustc_parse/src/lib.rs

+12-13
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22
33
#![feature(array_windows)]
44
#![feature(crate_visibility_modifier)]
5+
#![feature(if_let_guard)]
56
#![cfg_attr(bootstrap, feature(bindings_after_at))]
67
#![feature(box_patterns)]
8+
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
79
#![recursion_limit = "256"]
810

911
use rustc_ast as ast;
@@ -262,20 +264,17 @@ pub fn nt_to_tokenstream(
262264
let tokens = match *nt {
263265
Nonterminal::NtItem(ref item) => prepend_attrs(&item.attrs, item.tokens.as_ref()),
264266
Nonterminal::NtBlock(ref block) => convert_tokens(block.tokens.as_ref()),
265-
Nonterminal::NtStmt(ref stmt) => {
266-
if let ast::StmtKind::Empty = stmt.kind {
267-
let tokens = AttrAnnotatedTokenStream::new(vec![(
268-
tokenstream::AttrAnnotatedTokenTree::Token(Token::new(
269-
TokenKind::Semi,
270-
stmt.span,
271-
)),
272-
Spacing::Alone,
273-
)]);
274-
prepend_attrs(&stmt.attrs(), Some(&LazyTokenStream::new(tokens)))
275-
} else {
276-
prepend_attrs(&stmt.attrs(), stmt.tokens())
277-
}
267+
Nonterminal::NtStmt(ref stmt) if let ast::StmtKind::Empty = stmt.kind => {
268+
let tokens = AttrAnnotatedTokenStream::new(vec![(
269+
tokenstream::AttrAnnotatedTokenTree::Token(Token::new(
270+
TokenKind::Semi,
271+
stmt.span,
272+
)),
273+
Spacing::Alone,
274+
)]);
275+
prepend_attrs(&stmt.attrs(), Some(&LazyTokenStream::new(tokens)))
278276
}
277+
Nonterminal::NtStmt(ref stmt) => prepend_attrs(&stmt.attrs(), stmt.tokens()),
279278
Nonterminal::NtPat(ref pat) => convert_tokens(pat.tokens.as_ref()),
280279
Nonterminal::NtTy(ref ty) => convert_tokens(ty.tokens.as_ref()),
281280
Nonterminal::NtIdent(ident, is_raw) => {

compiler/rustc_parse/src/parser/nonterminal.rs

+9-8
Original file line numberDiff line numberDiff line change
@@ -143,15 +143,16 @@ impl<'a> Parser<'a> {
143143
token::NtTy(self.collect_tokens_no_attrs(|this| this.parse_ty())?)
144144
}
145145
// this could be handled like a token, since it is one
146+
NonterminalKind::Ident
147+
if let Some((ident, is_raw)) = get_macro_ident(&self.token) =>
148+
{
149+
self.bump();
150+
token::NtIdent(ident, is_raw)
151+
}
146152
NonterminalKind::Ident => {
147-
if let Some((ident, is_raw)) = get_macro_ident(&self.token) {
148-
self.bump();
149-
token::NtIdent(ident, is_raw)
150-
} else {
151-
let token_str = pprust::token_to_string(&self.token);
152-
let msg = &format!("expected ident, found {}", &token_str);
153-
return Err(self.struct_span_err(self.token.span, msg));
154-
}
153+
let token_str = pprust::token_to_string(&self.token);
154+
let msg = &format!("expected ident, found {}", &token_str);
155+
return Err(self.struct_span_err(self.token.span, msg));
155156
}
156157
NonterminalKind::Path => token::NtPath(
157158
self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?,

compiler/rustc_parse/src/parser/stmt.rs

+9-11
Original file line numberDiff line numberDiff line change
@@ -493,21 +493,19 @@ impl<'a> Parser<'a> {
493493
}
494494
}
495495
StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
496-
StmtKind::Local(ref mut local) => {
497-
if let Err(e) = self.expect_semi() {
498-
// We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
499-
match &mut local.init {
500-
Some(ref mut expr) => {
501-
self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
502-
// We found `foo<bar, baz>`, have we fully recovered?
503-
self.expect_semi()?;
504-
}
505-
None => return Err(e),
496+
StmtKind::Local(ref mut local) if let Err(e) = self.expect_semi() => {
497+
// We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
498+
match &mut local.init {
499+
Some(ref mut expr) => {
500+
self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
501+
// We found `foo<bar, baz>`, have we fully recovered?
502+
self.expect_semi()?;
506503
}
504+
None => return Err(e),
507505
}
508506
eat_semi = false;
509507
}
510-
StmtKind::Empty | StmtKind::Item(_) | StmtKind::Semi(_) => eat_semi = false,
508+
StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false,
511509
}
512510

513511
if eat_semi && self.eat(&token::Semi) {

compiler/rustc_parse/src/validate_attr.rs

+8-9
Original file line numberDiff line numberDiff line change
@@ -24,16 +24,15 @@ pub fn check_meta(sess: &ParseSess, attr: &Attribute) {
2424
Some((name, _, template, _)) if name != sym::rustc_dummy => {
2525
check_builtin_attribute(sess, attr, name, template)
2626
}
27-
_ => {
28-
if let MacArgs::Eq(..) = attr.get_normal_item().args {
29-
// All key-value attributes are restricted to meta-item syntax.
30-
parse_meta(sess, attr)
31-
.map_err(|mut err| {
32-
err.emit();
33-
})
34-
.ok();
35-
}
27+
_ if let MacArgs::Eq(..) = attr.get_normal_item().args => {
28+
// All key-value attributes are restricted to meta-item syntax.
29+
parse_meta(sess, attr)
30+
.map_err(|mut err| {
31+
err.emit();
32+
})
33+
.ok();
3634
}
35+
_ => {}
3736
}
3837
}
3938

0 commit comments

Comments
 (0)