Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Use if-let guards in the codebase
  • Loading branch information
LeSeulArtichaut committed Aug 25, 2021
1 parent a992a11 commit fde1b76
Show file tree
Hide file tree
Showing 27 changed files with 241 additions and 253 deletions.
10 changes: 5 additions & 5 deletions compiler/rustc_ast/src/attr/mod.rs
Expand Up @@ -564,11 +564,11 @@ impl NestedMetaItem {
I: Iterator<Item = TokenTree>,
{
match tokens.peek() {
Some(TokenTree::Token(token)) => {
if let Ok(lit) = Lit::from_token(token) {
tokens.next();
return Some(NestedMetaItem::Literal(lit));
}
Some(TokenTree::Token(token))
if let Ok(lit) = Lit::from_token(token) =>
{
tokens.next();
return Some(NestedMetaItem::Literal(lit));
}
Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => {
let inner_tokens = inner_tokens.clone();
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_ast/src/lib.rs
Expand Up @@ -11,10 +11,12 @@
#![feature(box_patterns)]
#![cfg_attr(bootstrap, feature(const_fn_transmute))]
#![feature(crate_visibility_modifier)]
#![feature(if_let_guard)]
#![feature(iter_zip)]
#![feature(label_break_value)]
#![feature(nll)]
#![feature(min_specialization)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
#![recursion_limit = "256"]

#[macro_use]
Expand Down
16 changes: 9 additions & 7 deletions compiler/rustc_errors/src/lib.rs
Expand Up @@ -5,9 +5,11 @@
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![feature(crate_visibility_modifier)]
#![feature(backtrace)]
#![feature(if_let_guard)]
#![feature(format_args_capture)]
#![feature(iter_zip)]
#![feature(nll)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard

#[macro_use]
extern crate rustc_macros;
Expand Down Expand Up @@ -1027,15 +1029,15 @@ impl HandlerInner {
let mut error_codes = self
.emitted_diagnostic_codes
.iter()
.filter_map(|x| match &x {
DiagnosticId::Error(s) => {
if let Ok(Some(_explanation)) = registry.try_find_description(s) {
Some(s.clone())
} else {
None
}
.filter_map(|x| {
match &x {
DiagnosticId::Error(s)
if let Ok(Some(_explanation)) = registry.try_find_description(s) =>
{
Some(s.clone())
}
_ => None,
}
})
.collect::<Vec<_>>();
if !error_codes.is_empty() {
Expand Down
15 changes: 7 additions & 8 deletions compiler/rustc_expand/src/config.rs
Expand Up @@ -305,15 +305,14 @@ impl<'a> StripUnconfigured<'a> {
Some((AttrAnnotatedTokenTree::Delimited(sp, delim, inner), *spacing))
.into_iter()
}
AttrAnnotatedTokenTree::Token(ref token) if let TokenKind::Interpolated(ref nt) = token.kind => {
panic!(
"Nonterminal should have been flattened at {:?}: {:?}",
token.span, nt
);
}
AttrAnnotatedTokenTree::Token(token) => {
if let TokenKind::Interpolated(nt) = token.kind {
panic!(
"Nonterminal should have been flattened at {:?}: {:?}",
token.span, nt
);
} else {
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
}
Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter()
}
})
.collect();
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_expand/src/lib.rs
Expand Up @@ -2,11 +2,13 @@
#![feature(decl_macro)]
#![feature(destructuring_assignment)]
#![feature(format_args_capture)]
#![feature(if_let_guard)]
#![feature(iter_zip)]
#![feature(proc_macro_diagnostic)]
#![feature(proc_macro_internals)]
#![feature(proc_macro_span)]
#![feature(try_blocks)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard

#[macro_use]
extern crate rustc_macros;
Expand Down
11 changes: 5 additions & 6 deletions compiler/rustc_expand/src/module.rs
Expand Up @@ -86,13 +86,12 @@ crate fn mod_dir_path(
inline: Inline,
) -> (PathBuf, DirOwnership) {
match inline {
Inline::Yes if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) => {
// For inline modules file path from `#[path]` is actually the directory path
// for historical reasons, so we don't pop the last segment here.
(file_path, DirOwnership::Owned { relative: None })
}
Inline::Yes => {
if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) {
// For inline modules file path from `#[path]` is actually the directory path
// for historical reasons, so we don't pop the last segment here.
return (file_path, DirOwnership::Owned { relative: None });
}

// We have to push on the current module name in the case of relative
// paths in order to ensure that any additional module paths from inline
// `mod x { ... }` come after the relative extension.
Expand Down
23 changes: 12 additions & 11 deletions compiler/rustc_expand/src/proc_macro_server.rs
Expand Up @@ -178,18 +178,19 @@ impl FromInternal<(TreeAndSpacing, &'_ mut Vec<Self>, &mut Rustc<'_>)>
tt!(Punct::new('#', false))
}

Interpolated(nt)
if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) =>
{
TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
}
Interpolated(nt) => {
if let Some((name, is_raw)) = ident_name_compatibility_hack(&nt, span, rustc) {
TokenTree::Ident(Ident::new(rustc.sess, name.name, is_raw, name.span))
} else {
let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
TokenTree::Group(Group {
delimiter: Delimiter::None,
stream,
span: DelimSpan::from_single(span),
flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
})
}
let stream = nt_to_tokenstream(&nt, rustc.sess, CanSynthesizeMissingTokens::No);
TokenTree::Group(Group {
delimiter: Delimiter::None,
stream,
span: DelimSpan::from_single(span),
flatten: crate::base::pretty_printing_compatibility_hack(&nt, rustc.sess),
})
}

OpenDelim(..) | CloseDelim(..) => unreachable!(),
Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_middle/src/lib.rs
Expand Up @@ -31,6 +31,7 @@
#![feature(box_patterns)]
#![feature(core_intrinsics)]
#![feature(discriminant_kind)]
#![feature(if_let_guard)]
#![feature(never_type)]
#![feature(extern_types)]
#![feature(new_uninit)]
Expand All @@ -52,6 +53,7 @@
#![feature(try_reserve)]
#![feature(try_reserve_kind)]
#![feature(nonzero_ops)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
#![recursion_limit = "512"]

#[macro_use]
Expand Down
30 changes: 13 additions & 17 deletions compiler/rustc_middle/src/ty/error.rs
Expand Up @@ -279,13 +279,10 @@ impl<'tcx> ty::TyS<'tcx> {
}
ty::FnDef(..) => "fn item".into(),
ty::FnPtr(_) => "fn pointer".into(),
ty::Dynamic(ref inner, ..) => {
if let Some(principal) = inner.principal() {
format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
} else {
"trait object".into()
}
ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
}
ty::Dynamic(..) => "trait object".into(),
ty::Closure(..) => "closure".into(),
ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
ty::GeneratorWitness(..) => "generator witness".into(),
Expand Down Expand Up @@ -365,20 +362,19 @@ impl<'tcx> TyCtxt<'tcx> {
// Issue #63167
db.note("distinct uses of `impl Trait` result in different opaque types");
}
(ty::Float(_), ty::Infer(ty::IntVar(_))) => {
(ty::Float(_), ty::Infer(ty::IntVar(_)))
if let Ok(
// Issue #53280
snippet,
) = self.sess.source_map().span_to_snippet(sp)
{
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
db.span_suggestion(
sp,
"use a float literal",
format!("{}.0", snippet),
MachineApplicable,
);
}
) = self.sess.source_map().span_to_snippet(sp) =>
{
if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
db.span_suggestion(
sp,
"use a float literal",
format!("{}.0", snippet),
MachineApplicable,
);
}
}
(ty::Param(expected), ty::Param(found)) => {
Expand Down
10 changes: 4 additions & 6 deletions compiler/rustc_middle/src/ty/util.rs
Expand Up @@ -225,14 +225,12 @@ impl<'tcx> TyCtxt<'tcx> {
}
}

ty::Tuple(tys) => {
if let Some((&last_ty, _)) = tys.split_last() {
ty = last_ty.expect_ty();
} else {
break;
}
ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => {
ty = last_ty.expect_ty();
}

ty::Tuple(_) => break,

ty::Projection(_) | ty::Opaque(..) => {
let normalized = normalize(ty);
if ty == normalized {
Expand Down
25 changes: 12 additions & 13 deletions compiler/rustc_parse/src/lib.rs
Expand Up @@ -2,8 +2,10 @@

#![feature(array_windows)]
#![feature(crate_visibility_modifier)]
#![feature(if_let_guard)]
#![cfg_attr(bootstrap, feature(bindings_after_at))]
#![feature(box_patterns)]
#![cfg_attr(bootstrap, allow(incomplete_features))] // if_let_guard
#![recursion_limit = "256"]

use rustc_ast as ast;
Expand Down Expand Up @@ -262,20 +264,17 @@ pub fn nt_to_tokenstream(
let tokens = match *nt {
Nonterminal::NtItem(ref item) => prepend_attrs(&item.attrs, item.tokens.as_ref()),
Nonterminal::NtBlock(ref block) => convert_tokens(block.tokens.as_ref()),
Nonterminal::NtStmt(ref stmt) => {
if let ast::StmtKind::Empty = stmt.kind {
let tokens = AttrAnnotatedTokenStream::new(vec![(
tokenstream::AttrAnnotatedTokenTree::Token(Token::new(
TokenKind::Semi,
stmt.span,
)),
Spacing::Alone,
)]);
prepend_attrs(&stmt.attrs(), Some(&LazyTokenStream::new(tokens)))
} else {
prepend_attrs(&stmt.attrs(), stmt.tokens())
}
Nonterminal::NtStmt(ref stmt) if let ast::StmtKind::Empty = stmt.kind => {
let tokens = AttrAnnotatedTokenStream::new(vec![(
tokenstream::AttrAnnotatedTokenTree::Token(Token::new(
TokenKind::Semi,
stmt.span,
)),
Spacing::Alone,
)]);
prepend_attrs(&stmt.attrs(), Some(&LazyTokenStream::new(tokens)))
}
Nonterminal::NtStmt(ref stmt) => prepend_attrs(&stmt.attrs(), stmt.tokens()),
Nonterminal::NtPat(ref pat) => convert_tokens(pat.tokens.as_ref()),
Nonterminal::NtTy(ref ty) => convert_tokens(ty.tokens.as_ref()),
Nonterminal::NtIdent(ident, is_raw) => {
Expand Down
17 changes: 9 additions & 8 deletions compiler/rustc_parse/src/parser/nonterminal.rs
Expand Up @@ -143,15 +143,16 @@ impl<'a> Parser<'a> {
token::NtTy(self.collect_tokens_no_attrs(|this| this.parse_ty())?)
}
// this could be handled like a token, since it is one
NonterminalKind::Ident
if let Some((ident, is_raw)) = get_macro_ident(&self.token) =>
{
self.bump();
token::NtIdent(ident, is_raw)
}
NonterminalKind::Ident => {
if let Some((ident, is_raw)) = get_macro_ident(&self.token) {
self.bump();
token::NtIdent(ident, is_raw)
} else {
let token_str = pprust::token_to_string(&self.token);
let msg = &format!("expected ident, found {}", &token_str);
return Err(self.struct_span_err(self.token.span, msg));
}
let token_str = pprust::token_to_string(&self.token);
let msg = &format!("expected ident, found {}", &token_str);
return Err(self.struct_span_err(self.token.span, msg));
}
NonterminalKind::Path => token::NtPath(
self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?,
Expand Down
20 changes: 9 additions & 11 deletions compiler/rustc_parse/src/parser/stmt.rs
Expand Up @@ -493,21 +493,19 @@ impl<'a> Parser<'a> {
}
}
StmtKind::Expr(_) | StmtKind::MacCall(_) => {}
StmtKind::Local(ref mut local) => {
if let Err(e) = self.expect_semi() {
// We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
match &mut local.init {
Some(ref mut expr) => {
self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
// We found `foo<bar, baz>`, have we fully recovered?
self.expect_semi()?;
}
None => return Err(e),
StmtKind::Local(ref mut local) if let Err(e) = self.expect_semi() => {
// We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover.
match &mut local.init {
Some(ref mut expr) => {
self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?;
// We found `foo<bar, baz>`, have we fully recovered?
self.expect_semi()?;
}
None => return Err(e),
}
eat_semi = false;
}
StmtKind::Empty | StmtKind::Item(_) | StmtKind::Semi(_) => eat_semi = false,
StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false,
}

if eat_semi && self.eat(&token::Semi) {
Expand Down
17 changes: 8 additions & 9 deletions compiler/rustc_parse/src/validate_attr.rs
Expand Up @@ -24,16 +24,15 @@ pub fn check_meta(sess: &ParseSess, attr: &Attribute) {
Some((name, _, template, _)) if name != sym::rustc_dummy => {
check_builtin_attribute(sess, attr, name, template)
}
_ => {
if let MacArgs::Eq(..) = attr.get_normal_item().args {
// All key-value attributes are restricted to meta-item syntax.
parse_meta(sess, attr)
.map_err(|mut err| {
err.emit();
})
.ok();
}
_ if let MacArgs::Eq(..) = attr.get_normal_item().args => {
// All key-value attributes are restricted to meta-item syntax.
parse_meta(sess, attr)
.map_err(|mut err| {
err.emit();
})
.ok();
}
_ => {}
}
}

Expand Down

0 comments on commit fde1b76

Please sign in to comment.