Auto merge of #78424 - jyn514:THE-PAPERCLIP-COMETH, r=davidtwco

Fix some more clippy warnings

Found while working on https://github.com/rust-lang/rust/pull/77351. It turns out that `x.py clippy --fix` does work on that branch as long as you pass `CARGOFLAGS=--lib`.
This commit is contained in:
bors 2020-10-30 14:24:02 +00:00
commit ffe52882ed
69 changed files with 349 additions and 616 deletions

View File

@ -228,7 +228,7 @@ impl<T> TypedArena<T> {
// bytes, then this chunk will be least double the previous // bytes, then this chunk will be least double the previous
// chunk's size. // chunk's size.
new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2); new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
new_cap = new_cap * 2; new_cap *= 2;
} else { } else {
new_cap = PAGE / elem_size; new_cap = PAGE / elem_size;
} }
@ -346,7 +346,7 @@ impl DroplessArena {
// bytes, then this chunk will be least double the previous // bytes, then this chunk will be least double the previous
// chunk's size. // chunk's size.
new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2); new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
new_cap = new_cap * 2; new_cap *= 2;
} else { } else {
new_cap = PAGE; new_cap = PAGE;
} }
@ -562,10 +562,8 @@ impl DropArena {
// Record the destructors after doing the allocation as that may panic // Record the destructors after doing the allocation as that may panic
// and would cause `object`'s destructor to run twice if it was recorded before // and would cause `object`'s destructor to run twice if it was recorded before
for i in 0..len { for i in 0..len {
destructors.push(DropType { destructors
drop_fn: drop_for_type::<T>, .push(DropType { drop_fn: drop_for_type::<T>, obj: start_ptr.add(i) as *mut u8 });
obj: start_ptr.offset(i as isize) as *mut u8,
});
} }
slice::from_raw_parts_mut(start_ptr, len) slice::from_raw_parts_mut(start_ptr, len)

View File

@ -490,10 +490,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let count = generics let count = generics
.params .params
.iter() .iter()
.filter(|param| match param.kind { .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
ast::GenericParamKind::Lifetime { .. } => true,
_ => false,
})
.count(); .count();
self.lctx.type_def_lifetime_params.insert(def_id.to_def_id(), count); self.lctx.type_def_lifetime_params.insert(def_id.to_def_id(), count);
} }

View File

@ -262,10 +262,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx) self.lower_angle_bracketed_parameter_data(&Default::default(), param_mode, itctx)
}; };
let has_lifetimes = generic_args.args.iter().any(|arg| match arg { let has_lifetimes =
GenericArg::Lifetime(_) => true, generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
_ => false,
});
let first_generic_span = generic_args let first_generic_span = generic_args
.args .args
.iter() .iter()

View File

@ -639,15 +639,13 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
fn break_offset_if_not_bol(&mut self, n: usize, off: isize) { fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
if !self.is_beginning_of_line() { if !self.is_beginning_of_line() {
self.break_offset(n, off) self.break_offset(n, off)
} else { } else if off != 0 && self.last_token().is_hardbreak_tok() {
if off != 0 && self.last_token().is_hardbreak_tok() {
// We do something pretty sketchy here: tuck the nonzero // We do something pretty sketchy here: tuck the nonzero
// offset-adjustment we were going to deposit along with the // offset-adjustment we were going to deposit along with the
// break into the previous hardbreak. // break into the previous hardbreak.
self.replace_last_token(pp::Printer::hardbreak_tok_offset(off)); self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
} }
} }
}
fn nonterminal_to_string(&self, nt: &Nonterminal) -> String { fn nonterminal_to_string(&self, nt: &Nonterminal) -> String {
match *nt { match *nt {

View File

@ -901,8 +901,7 @@ pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
) )
.emit(); .emit();
} }
} else { } else if let Some(meta_item) = item.meta_item() {
if let Some(meta_item) = item.meta_item() {
if meta_item.has_name(sym::align) { if meta_item.has_name(sym::align) {
if let MetaItemKind::NameValue(ref value) = meta_item.kind { if let MetaItemKind::NameValue(ref value) = meta_item.kind {
recognised = true; recognised = true;
@ -935,7 +934,6 @@ pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
} }
} }
} }
}
if !recognised { if !recognised {
// Not a word we recognize // Not a word we recognize
struct_span_err!( struct_span_err!(

View File

@ -93,7 +93,7 @@ pub(crate) unsafe fn codegen(
let args = [usize, usize]; // size, align let args = [usize, usize]; // size, align
let ty = llvm::LLVMFunctionType(void, args.as_ptr(), args.len() as c_uint, False); let ty = llvm::LLVMFunctionType(void, args.as_ptr(), args.len() as c_uint, False);
let name = format!("__rust_alloc_error_handler"); let name = "__rust_alloc_error_handler".to_string();
let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty); let llfn = llvm::LLVMRustGetOrInsertFunction(llmod, name.as_ptr().cast(), name.len(), ty);
// -> ! DIFlagNoReturn // -> ! DIFlagNoReturn
llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn); llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn);

View File

@ -302,14 +302,12 @@ impl AsmBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
} else if options.contains(InlineAsmOptions::READONLY) { } else if options.contains(InlineAsmOptions::READONLY) {
llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result); llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result);
} }
} else { } else if options.contains(InlineAsmOptions::NOMEM) {
if options.contains(InlineAsmOptions::NOMEM) {
llvm::Attribute::InaccessibleMemOnly llvm::Attribute::InaccessibleMemOnly
.apply_callsite(llvm::AttributePlace::Function, result); .apply_callsite(llvm::AttributePlace::Function, result);
} else { } else {
// LLVM doesn't have an attribute to represent ReadOnly + SideEffect // LLVM doesn't have an attribute to represent ReadOnly + SideEffect
} }
}
// Write results to outputs // Write results to outputs
for (idx, op) in operands.iter().enumerate() { for (idx, op) in operands.iter().enumerate() {

View File

@ -900,7 +900,7 @@ impl ThinLTOKeysMap {
let file = File::open(path)?; let file = File::open(path)?;
for line in io::BufReader::new(file).lines() { for line in io::BufReader::new(file).lines() {
let line = line?; let line = line?;
let mut split = line.split(" "); let mut split = line.split(' ');
let module = split.next().unwrap(); let module = split.next().unwrap();
let key = split.next().unwrap(); let key = split.next().unwrap();
assert_eq!(split.next(), None, "Expected two space-separated values, found {:?}", line); assert_eq!(split.next(), None, "Expected two space-separated values, found {:?}", line);

View File

@ -732,10 +732,7 @@ impl BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> {
let src_ty = self.cx.val_ty(val); let src_ty = self.cx.val_ty(val);
let float_width = self.cx.float_width(src_ty); let float_width = self.cx.float_width(src_ty);
let int_width = self.cx.int_width(dest_ty); let int_width = self.cx.int_width(dest_ty);
match (int_width, float_width) { matches!((int_width, float_width), (32, 32) | (32, 64) | (64, 32) | (64, 64))
(32, 32) | (32, 64) | (64, 32) | (64, 64) => true,
_ => false,
}
} }
fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value { fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {

View File

@ -397,11 +397,9 @@ impl StaticMethods for CodegenCx<'ll, 'tcx> {
// As an optimization, all shared statics which do not have interior // As an optimization, all shared statics which do not have interior
// mutability are placed into read-only memory. // mutability are placed into read-only memory.
if !is_mutable { if !is_mutable && self.type_is_freeze(ty) {
if self.type_is_freeze(ty) {
llvm::LLVMSetGlobalConstant(g, llvm::True); llvm::LLVMSetGlobalConstant(g, llvm::True);
} }
}
debuginfo::create_global_var_metadata(&self, def_id, g); debuginfo::create_global_var_metadata(&self, def_id, g);

View File

@ -122,11 +122,11 @@ pub unsafe fn create_module(
if llvm_util::get_major_version() < 9 { if llvm_util::get_major_version() < 9 {
target_data_layout = strip_function_ptr_alignment(target_data_layout); target_data_layout = strip_function_ptr_alignment(target_data_layout);
} }
if llvm_util::get_major_version() < 10 { if llvm_util::get_major_version() < 10
if sess.target.arch == "x86" || sess.target.arch == "x86_64" { && (sess.target.arch == "x86" || sess.target.arch == "x86_64")
{
target_data_layout = strip_x86_address_spaces(target_data_layout); target_data_layout = strip_x86_address_spaces(target_data_layout);
} }
}
// Ensure the data-layout values hardcoded remain the defaults. // Ensure the data-layout values hardcoded remain the defaults.
if sess.target.options.is_builtin { if sess.target.options.is_builtin {
@ -864,7 +864,7 @@ impl<'b, 'tcx> CodegenCx<'b, 'tcx> {
// user defined names // user defined names
let mut name = String::with_capacity(prefix.len() + 6); let mut name = String::with_capacity(prefix.len() + 6);
name.push_str(prefix); name.push_str(prefix);
name.push_str("."); name.push('.');
base_n::push_str(idx as u128, base_n::ALPHANUMERIC_ONLY, &mut name); base_n::push_str(idx as u128, base_n::ALPHANUMERIC_ONLY, &mut name);
name name
} }

View File

@ -435,7 +435,7 @@ impl DebugInfoMethods<'tcx> for CodegenCx<'ll, 'tcx> {
name_to_append_suffix_to.push('<'); name_to_append_suffix_to.push('<');
for (i, actual_type) in substs.types().enumerate() { for (i, actual_type) in substs.types().enumerate() {
if i != 0 { if i != 0 {
name_to_append_suffix_to.push_str(","); name_to_append_suffix_to.push(',');
} }
let actual_type = let actual_type =

View File

@ -307,10 +307,7 @@ where
fn walk_unvisited_node(&mut self, depth: usize, node: G::Node) -> WalkReturn<S> { fn walk_unvisited_node(&mut self, depth: usize, node: G::Node) -> WalkReturn<S> {
debug!("walk_unvisited_node(depth = {:?}, node = {:?})", depth, node); debug!("walk_unvisited_node(depth = {:?}, node = {:?})", depth, node);
debug_assert!(match self.node_states[node] { debug_assert!(matches!(self.node_states[node], NodeState::NotVisited));
NodeState::NotVisited => true,
_ => false,
});
// Push `node` onto the stack. // Push `node` onto the stack.
self.node_states[node] = NodeState::BeingVisited { depth }; self.node_states[node] = NodeState::BeingVisited { depth };

View File

@ -395,7 +395,7 @@ where
V: Copy, V: Copy,
{ {
fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) { fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: T) {
self.extend(iter.into_iter().map(|(k, v)| (k.clone(), v.clone()))) self.extend(iter.into_iter().map(|(k, v)| (*k, *v)))
} }
#[inline] #[inline]
@ -451,7 +451,7 @@ impl<'a, K, V> IntoIterator for &'a SsoHashMap<K, V> {
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
match self { match self {
SsoHashMap::Array(array) => EitherIter::Left(array.into_iter().map(adapt_array_ref_it)), SsoHashMap::Array(array) => EitherIter::Left(array.into_iter().map(adapt_array_ref_it)),
SsoHashMap::Map(map) => EitherIter::Right(map.into_iter()), SsoHashMap::Map(map) => EitherIter::Right(map.iter()),
} }
} }
} }
@ -469,7 +469,7 @@ impl<'a, K, V> IntoIterator for &'a mut SsoHashMap<K, V> {
fn into_iter(self) -> Self::IntoIter { fn into_iter(self) -> Self::IntoIter {
match self { match self {
SsoHashMap::Array(array) => EitherIter::Left(array.into_iter().map(adapt_array_mut_it)), SsoHashMap::Array(array) => EitherIter::Left(array.into_iter().map(adapt_array_mut_it)),
SsoHashMap::Map(map) => EitherIter::Right(map.into_iter()), SsoHashMap::Map(map) => EitherIter::Right(map.iter_mut()),
} }
} }
} }

View File

@ -716,7 +716,7 @@ impl RustcDefaultCalls {
TargetList => { TargetList => {
let mut targets = let mut targets =
rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>(); rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>();
targets.sort(); targets.sort_unstable();
println!("{}", targets.join("\n")); println!("{}", targets.join("\n"));
} }
Sysroot => println!("{}", sess.sysroot.display()), Sysroot => println!("{}", sess.sysroot.display()),

View File

@ -136,10 +136,7 @@ impl Emitter for JsonEmitter {
} }
fn should_show_explain(&self) -> bool { fn should_show_explain(&self) -> bool {
match self.json_rendered { !matches!(self.json_rendered, HumanReadableErrorType::Short(_))
HumanReadableErrorType::Short(_) => false,
_ => true,
}
} }
} }

View File

@ -91,10 +91,7 @@ pub enum SuggestionStyle {
impl SuggestionStyle { impl SuggestionStyle {
fn hide_inline(&self) -> bool { fn hide_inline(&self) -> bool {
match *self { !matches!(*self, SuggestionStyle::ShowCode)
SuggestionStyle::ShowCode => false,
_ => true,
}
} }
} }
@ -1038,10 +1035,7 @@ impl Level {
} }
pub fn is_failure_note(&self) -> bool { pub fn is_failure_note(&self) -> bool {
match *self { matches!(*self, FailureNote)
FailureNote => true,
_ => false,
}
} }
} }

View File

@ -158,10 +158,7 @@ impl Annotation {
pub fn takes_space(&self) -> bool { pub fn takes_space(&self) -> bool {
// Multiline annotations always have to keep vertical space. // Multiline annotations always have to keep vertical space.
match self.annotation_type { matches!(self.annotation_type, AnnotationType::MultilineStart(_) | AnnotationType::MultilineEnd(_))
AnnotationType::MultilineStart(_) | AnnotationType::MultilineEnd(_) => true,
_ => false,
}
} }
} }

View File

@ -102,10 +102,7 @@ impl TokenTree {
/// Returns `true` if the given token tree is delimited. /// Returns `true` if the given token tree is delimited.
fn is_delimited(&self) -> bool { fn is_delimited(&self) -> bool {
match *self { matches!(*self, TokenTree::Delimited(..))
TokenTree::Delimited(..) => true,
_ => false,
}
} }
/// Returns `true` if the given token tree is a token of the given kind. /// Returns `true` if the given token tree is a token of the given kind.

View File

@ -134,10 +134,7 @@ enum Stack<'a, T> {
impl<'a, T> Stack<'a, T> { impl<'a, T> Stack<'a, T> {
/// Returns whether a stack is empty. /// Returns whether a stack is empty.
fn is_empty(&self) -> bool { fn is_empty(&self) -> bool {
match *self { matches!(*self, Stack::Empty)
Stack::Empty => true,
_ => false,
}
} }
/// Returns a new stack with an element of top. /// Returns a new stack with an element of top.

View File

@ -1036,17 +1036,16 @@ fn token_can_be_followed_by_any(tok: &mbe::TokenTree) -> bool {
/// a fragment specifier (indeed, these fragments can be followed by /// a fragment specifier (indeed, these fragments can be followed by
/// ANYTHING without fear of future compatibility hazards). /// ANYTHING without fear of future compatibility hazards).
fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool { fn frag_can_be_followed_by_any(kind: NonterminalKind) -> bool {
match kind { matches!(
kind,
NonterminalKind::Item // always terminated by `}` or `;` NonterminalKind::Item // always terminated by `}` or `;`
| NonterminalKind::Block // exactly one token tree | NonterminalKind::Block // exactly one token tree
| NonterminalKind::Ident // exactly one token tree | NonterminalKind::Ident // exactly one token tree
| NonterminalKind::Literal // exactly one token tree | NonterminalKind::Literal // exactly one token tree
| NonterminalKind::Meta // exactly one token tree | NonterminalKind::Meta // exactly one token tree
| NonterminalKind::Lifetime // exactly one token tree | NonterminalKind::Lifetime // exactly one token tree
| NonterminalKind::TT => true, // exactly one token tree | NonterminalKind::TT // exactly one token tree
)
_ => false,
}
} }
enum IsInFollow { enum IsInFollow {

View File

@ -345,10 +345,10 @@ impl<'a, 'b> MutVisitor for PlaceholderExpander<'a, 'b> {
fn visit_mod(&mut self, module: &mut ast::Mod) { fn visit_mod(&mut self, module: &mut ast::Mod) {
noop_visit_mod(module, self); noop_visit_mod(module, self);
module.items.retain(|item| match item.kind { // remove macro definitions
ast::ItemKind::MacCall(_) if !self.cx.ecfg.keep_macs => false, // remove macro definitions module.items.retain(
_ => true, |item| !matches!(item.kind, ast::ItemKind::MacCall(_) if !self.cx.ecfg.keep_macs),
}); );
} }
fn visit_mac(&mut self, _mac: &mut ast::MacCall) { fn visit_mac(&mut self, _mac: &mut ast::MacCall) {

View File

@ -83,10 +83,7 @@ impl std::fmt::Debug for AttributeGate {
impl AttributeGate { impl AttributeGate {
fn is_deprecated(&self) -> bool { fn is_deprecated(&self) -> bool {
match *self { matches!(*self, Self::Gated(Stability::Deprecated(_, _), ..))
Self::Gated(Stability::Deprecated(_, _), ..) => true,
_ => false,
}
} }
} }

View File

@ -272,10 +272,7 @@ impl GenericArg<'_> {
} }
pub fn is_const(&self) -> bool { pub fn is_const(&self) -> bool {
match self { matches!(self, GenericArg::Const(_))
GenericArg::Const(_) => true,
_ => false,
}
} }
pub fn descr(&self) -> &'static str { pub fn descr(&self) -> &'static str {
@ -980,17 +977,11 @@ impl BinOpKind {
} }
pub fn is_lazy(self) -> bool { pub fn is_lazy(self) -> bool {
match self { matches!(self, BinOpKind::And | BinOpKind::Or)
BinOpKind::And | BinOpKind::Or => true,
_ => false,
}
} }
pub fn is_shift(self) -> bool { pub fn is_shift(self) -> bool {
match self { matches!(self, BinOpKind::Shl | BinOpKind::Shr)
BinOpKind::Shl | BinOpKind::Shr => true,
_ => false,
}
} }
pub fn is_comparison(self) -> bool { pub fn is_comparison(self) -> bool {
@ -1070,10 +1061,7 @@ impl UnOp {
/// Returns `true` if the unary operator takes its argument by value. /// Returns `true` if the unary operator takes its argument by value.
pub fn is_by_value(self) -> bool { pub fn is_by_value(self) -> bool {
match self { matches!(self, Self::UnNeg | Self::UnNot)
Self::UnNeg | Self::UnNot => true,
_ => false,
}
} }
} }
@ -1409,10 +1397,9 @@ impl Expr<'_> {
/// on the given expression should be considered a place expression. /// on the given expression should be considered a place expression.
pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool { pub fn is_place_expr(&self, mut allow_projections_from: impl FnMut(&Self) -> bool) -> bool {
match self.kind { match self.kind {
ExprKind::Path(QPath::Resolved(_, ref path)) => match path.res { ExprKind::Path(QPath::Resolved(_, ref path)) => {
Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err => true, matches!(path.res, Res::Local(..) | Res::Def(DefKind::Static, _) | Res::Err)
_ => false, }
},
// Type ascription inherits its place expression kind from its // Type ascription inherits its place expression kind from its
// operand. See: // operand. See:
@ -2204,10 +2191,7 @@ pub enum ImplicitSelfKind {
impl ImplicitSelfKind { impl ImplicitSelfKind {
/// Does this represent an implicit self? /// Does this represent an implicit self?
pub fn has_implicit_self(&self) -> bool { pub fn has_implicit_self(&self) -> bool {
match *self { !matches!(*self, ImplicitSelfKind::None)
ImplicitSelfKind::None => false,
_ => true,
}
} }
} }
@ -2237,10 +2221,7 @@ impl Defaultness {
} }
pub fn is_default(&self) -> bool { pub fn is_default(&self) -> bool {
match *self { matches!(*self, Defaultness::Default { .. })
Defaultness::Default { .. } => true,
_ => false,
}
} }
} }
@ -2371,10 +2352,7 @@ pub enum VisibilityKind<'hir> {
impl VisibilityKind<'_> { impl VisibilityKind<'_> {
pub fn is_pub(&self) -> bool { pub fn is_pub(&self) -> bool {
match *self { matches!(*self, VisibilityKind::Public)
VisibilityKind::Public => true,
_ => false,
}
} }
pub fn is_pub_restricted(&self) -> bool { pub fn is_pub_restricted(&self) -> bool {
@ -2502,10 +2480,7 @@ pub struct FnHeader {
impl FnHeader { impl FnHeader {
pub fn is_const(&self) -> bool { pub fn is_const(&self) -> bool {
match &self.constness { matches!(&self.constness, Constness::Const)
Constness::Const => true,
_ => false,
}
} }
} }

View File

@ -92,10 +92,7 @@ impl hir::Pat<'_> {
/// Checks if the pattern contains any patterns that bind something to /// Checks if the pattern contains any patterns that bind something to
/// an ident, e.g., `foo`, or `Foo(foo)` or `foo @ Bar(..)`. /// an ident, e.g., `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
pub fn contains_bindings(&self) -> bool { pub fn contains_bindings(&self) -> bool {
self.satisfies(|p| match p.kind { self.satisfies(|p| matches!(p.kind, PatKind::Binding(..)))
PatKind::Binding(..) => true,
_ => false,
})
} }
/// Checks if the pattern satisfies the given predicate on some sub-pattern. /// Checks if the pattern satisfies the given predicate on some sub-pattern.

View File

@ -299,15 +299,13 @@ impl<'a> State<'a> {
pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) { pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) {
if !self.s.is_beginning_of_line() { if !self.s.is_beginning_of_line() {
self.s.break_offset(n, off) self.s.break_offset(n, off)
} else { } else if off != 0 && self.s.last_token().is_hardbreak_tok() {
if off != 0 && self.s.last_token().is_hardbreak_tok() {
// We do something pretty sketchy here: tuck the nonzero // We do something pretty sketchy here: tuck the nonzero
// offset-adjustment we were going to deposit along with the // offset-adjustment we were going to deposit along with the
// break into the previous hardbreak. // break into the previous hardbreak.
self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off)); self.s.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
} }
} }
}
// Synthesizes a comment that was not textually present in the original source // Synthesizes a comment that was not textually present in the original source
// file. // file.
@ -1921,10 +1919,7 @@ impl<'a> State<'a> {
self.pclose(); self.pclose();
} }
PatKind::Box(ref inner) => { PatKind::Box(ref inner) => {
let is_range_inner = match inner.kind { let is_range_inner = matches!(inner.kind, PatKind::Range(..));
PatKind::Range(..) => true,
_ => false,
};
self.s.word("box "); self.s.word("box ");
if is_range_inner { if is_range_inner {
self.popen(); self.popen();
@ -1935,10 +1930,7 @@ impl<'a> State<'a> {
} }
} }
PatKind::Ref(ref inner, mutbl) => { PatKind::Ref(ref inner, mutbl) => {
let is_range_inner = match inner.kind { let is_range_inner = matches!(inner.kind, PatKind::Range(..));
PatKind::Range(..) => true,
_ => false,
};
self.s.word("&"); self.s.word("&");
self.s.word(mutbl.prefix_str()); self.s.word(mutbl.prefix_str());
if is_range_inner { if is_range_inner {
@ -2435,10 +2427,7 @@ impl<'a> State<'a> {
// //
// Duplicated from `parse::classify`, but adapted for the HIR. // Duplicated from `parse::classify`, but adapted for the HIR.
fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool { fn expr_requires_semi_to_be_stmt(e: &hir::Expr<'_>) -> bool {
match e.kind { !matches!(e.kind, hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..))
hir::ExprKind::Match(..) | hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) => false,
_ => true,
}
} }
/// This statement requires a semicolon after it. /// This statement requires a semicolon after it.

View File

@ -238,9 +238,10 @@ pub fn is_whitespace(c: char) -> bool {
// Note that this set is stable (ie, it doesn't change with different // Note that this set is stable (ie, it doesn't change with different
// Unicode versions), so it's ok to just hard-code the values. // Unicode versions), so it's ok to just hard-code the values.
match c { matches!(
c,
// Usual ASCII suspects // Usual ASCII suspects
| '\u{0009}' // \t '\u{0009}' // \t
| '\u{000A}' // \n | '\u{000A}' // \n
| '\u{000B}' // vertical tab | '\u{000B}' // vertical tab
| '\u{000C}' // form feed | '\u{000C}' // form feed
@ -257,9 +258,7 @@ pub fn is_whitespace(c: char) -> bool {
// Dedicated whitespace characters from Unicode // Dedicated whitespace characters from Unicode
| '\u{2028}' // LINE SEPARATOR | '\u{2028}' // LINE SEPARATOR
| '\u{2029}' // PARAGRAPH SEPARATOR | '\u{2029}' // PARAGRAPH SEPARATOR
=> true, )
_ => false,
}
} }
/// True if `c` is valid as a first character of an identifier. /// True if `c` is valid as a first character of an identifier.

View File

@ -1369,10 +1369,9 @@ impl TypeAliasBounds {
hir::QPath::TypeRelative(ref ty, _) => { hir::QPath::TypeRelative(ref ty, _) => {
// If this is a type variable, we found a `T::Assoc`. // If this is a type variable, we found a `T::Assoc`.
match ty.kind { match ty.kind {
hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => match path.res { hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) => {
Res::Def(DefKind::TyParam, _) => true, matches!(path.res, Res::Def(DefKind::TyParam, _))
_ => false, }
},
_ => false, _ => false,
} }
} }
@ -2381,12 +2380,11 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue {
return Some(InitKind::Zeroed); return Some(InitKind::Zeroed);
} else if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, def_id) { } else if cx.tcx.is_diagnostic_item(sym::mem_uninitialized, def_id) {
return Some(InitKind::Uninit); return Some(InitKind::Uninit);
} else if cx.tcx.is_diagnostic_item(sym::transmute, def_id) { } else if cx.tcx.is_diagnostic_item(sym::transmute, def_id) && is_zero(&args[0])
if is_zero(&args[0]) { {
return Some(InitKind::Zeroed); return Some(InitKind::Zeroed);
} }
} }
}
} else if let hir::ExprKind::MethodCall(_, _, ref args, _) = expr.kind { } else if let hir::ExprKind::MethodCall(_, _, ref args, _) = expr.kind {
// Find problematic calls to `MaybeUninit::assume_init`. // Find problematic calls to `MaybeUninit::assume_init`.
let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?; let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
@ -2880,7 +2878,7 @@ impl<'tcx> LateLintPass<'tcx> for ClashingExternDeclarations {
fn check_foreign_item(&mut self, cx: &LateContext<'tcx>, this_fi: &hir::ForeignItem<'_>) { fn check_foreign_item(&mut self, cx: &LateContext<'tcx>, this_fi: &hir::ForeignItem<'_>) {
trace!("ClashingExternDeclarations: check_foreign_item: {:?}", this_fi); trace!("ClashingExternDeclarations: check_foreign_item: {:?}", this_fi);
if let ForeignItemKind::Fn(..) = this_fi.kind { if let ForeignItemKind::Fn(..) = this_fi.kind {
let tcx = *&cx.tcx; let tcx = cx.tcx;
if let Some(existing_hid) = self.insert(tcx, this_fi) { if let Some(existing_hid) = self.insert(tcx, this_fi) {
let existing_decl_ty = tcx.type_of(tcx.hir().local_def_id(existing_hid)); let existing_decl_ty = tcx.type_of(tcx.hir().local_def_id(existing_hid));
let this_decl_ty = tcx.type_of(tcx.hir().local_def_id(this_fi.hir_id)); let this_decl_ty = tcx.type_of(tcx.hir().local_def_id(this_fi.hir_id));

View File

@ -320,7 +320,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSnakeCase {
.with_hi(lit.span.hi() - BytePos(right as u32)), .with_hi(lit.span.hi() - BytePos(right as u32)),
) )
}) })
.unwrap_or_else(|| lit.span); .unwrap_or(lit.span);
Some(Ident::new(name, sp)) Some(Ident::new(name, sp))
} else { } else {

View File

@ -544,15 +544,15 @@ impl<'tcx> LateLintPass<'tcx> for TypeLimits {
} }
fn is_comparison(binop: hir::BinOp) -> bool { fn is_comparison(binop: hir::BinOp) -> bool {
match binop.node { matches!(
binop.node,
hir::BinOpKind::Eq hir::BinOpKind::Eq
| hir::BinOpKind::Lt | hir::BinOpKind::Lt
| hir::BinOpKind::Le | hir::BinOpKind::Le
| hir::BinOpKind::Ne | hir::BinOpKind::Ne
| hir::BinOpKind::Ge | hir::BinOpKind::Ge
| hir::BinOpKind::Gt => true, | hir::BinOpKind::Gt
_ => false, )
}
} }
} }
} }
@ -1233,15 +1233,10 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> {
} }
fn is_internal_abi(&self, abi: SpecAbi) -> bool { fn is_internal_abi(&self, abi: SpecAbi) -> bool {
if let SpecAbi::Rust matches!(
| SpecAbi::RustCall abi,
| SpecAbi::RustIntrinsic SpecAbi::Rust | SpecAbi::RustCall | SpecAbi::RustIntrinsic | SpecAbi::PlatformIntrinsic
| SpecAbi::PlatformIntrinsic = abi )
{
true
} else {
false
}
} }
} }

View File

@ -752,14 +752,11 @@ impl UnusedDelimLint for UnusedParens {
&& value.attrs.is_empty() && value.attrs.is_empty()
&& !value.span.from_expansion() && !value.span.from_expansion()
&& (ctx != UnusedDelimsCtx::LetScrutineeExpr && (ctx != UnusedDelimsCtx::LetScrutineeExpr
|| match inner.kind { || !matches!(inner.kind, ast::ExprKind::Binary(
ast::ExprKind::Binary(
rustc_span::source_map::Spanned { node, .. }, rustc_span::source_map::Spanned { node, .. },
_, _,
_, _,
) if node.lazy() => false, ) if node.lazy()))
_ => true,
})
{ {
self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos) self.emit_unused_delims_expr(cx, value, ctx, left_pos, right_pos)
} }

View File

@ -752,10 +752,7 @@ impl<'a> CrateLoader<'a> {
// At this point we've determined that we need an allocator. Let's see // At this point we've determined that we need an allocator. Let's see
// if our compilation session actually needs an allocator based on what // if our compilation session actually needs an allocator based on what
// we're emitting. // we're emitting.
let all_rlib = self.sess.crate_types().iter().all(|ct| match *ct { let all_rlib = self.sess.crate_types().iter().all(|ct| matches!(*ct, CrateType::Rlib));
CrateType::Rlib => true,
_ => false,
});
if all_rlib { if all_rlib {
return; return;
} }

View File

@ -633,12 +633,10 @@ impl<'a> CrateLocator<'a> {
} }
} }
if self.exact_paths.is_empty() { if self.exact_paths.is_empty() && self.crate_name != root.name() {
if self.crate_name != root.name() {
info!("Rejecting via crate name"); info!("Rejecting via crate name");
return None; return None;
} }
}
if root.triple() != &self.triple { if root.triple() != &self.triple {
info!("Rejecting via crate triple: expected {} got {}", self.triple, root.triple()); info!("Rejecting via crate triple: expected {} got {}", self.triple, root.triple());

View File

@ -220,10 +220,7 @@ provide! { <'tcx> tcx, def_id, other, cdata,
missing_lang_items => { cdata.get_missing_lang_items(tcx) } missing_lang_items => { cdata.get_missing_lang_items(tcx) }
missing_extern_crate_item => { missing_extern_crate_item => {
let r = match *cdata.extern_crate.borrow() { let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct());
Some(extern_crate) if !extern_crate.is_direct() => true,
_ => false,
};
r r
} }
@ -254,9 +251,11 @@ pub fn provide(providers: &mut Providers) {
} }
_ => false, _ => false,
}, },
is_statically_included_foreign_item: |tcx, id| match tcx.native_library_kind(id) { is_statically_included_foreign_item: |tcx, id| {
Some(NativeLibKind::StaticBundle | NativeLibKind::StaticNoBundle) => true, matches!(
_ => false, tcx.native_library_kind(id),
Some(NativeLibKind::StaticBundle | NativeLibKind::StaticNoBundle)
)
}, },
native_library_kind: |tcx, id| { native_library_kind: |tcx, id| {
tcx.native_libraries(id.krate) tcx.native_libraries(id.krate)

View File

@ -262,10 +262,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
| ExprKind::ThreadLocalRef(_) | ExprKind::ThreadLocalRef(_)
| ExprKind::Call { .. } => { | ExprKind::Call { .. } => {
// these are not places, so we need to make a temporary. // these are not places, so we need to make a temporary.
debug_assert!(match Category::of(&expr.kind) { debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
Some(Category::Place) => false,
_ => true,
});
let temp = let temp =
unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability)); unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
block.and(PlaceBuilder::from(temp)) block.and(PlaceBuilder::from(temp))

View File

@ -260,10 +260,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
| ExprKind::ValueTypeAscription { .. } => { | ExprKind::ValueTypeAscription { .. } => {
// these do not have corresponding `Rvalue` variants, // these do not have corresponding `Rvalue` variants,
// so make an operand and then return that // so make an operand and then return that
debug_assert!(match Category::of(&expr.kind) { debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Rvalue(RvalueFunc::AsRvalue))));
Some(Category::Rvalue(RvalueFunc::AsRvalue)) => false,
_ => true,
});
let operand = unpack!(block = this.as_operand(block, scope, expr)); let operand = unpack!(block = this.as_operand(block, scope, expr));
block.and(Rvalue::Use(operand)) block.and(Rvalue::Use(operand))
} }

View File

@ -58,10 +58,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
} }
ExprKind::NeverToAny { source } => { ExprKind::NeverToAny { source } => {
let source = this.hir.mirror(source); let source = this.hir.mirror(source);
let is_call = match source.kind { let is_call = matches!(source.kind, ExprKind::Call { .. } | ExprKind::InlineAsm { .. });
ExprKind::Call { .. } | ExprKind::InlineAsm { .. } => true,
_ => false,
};
// (#66975) Source could be a const of type `!`, so has to // (#66975) Source could be a const of type `!`, so has to
// exist in the generated MIR. // exist in the generated MIR.

View File

@ -250,8 +250,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
place, place,
ty, ty,
); );
} else { } else if let [success, fail] = *make_target_blocks(self) {
if let [success, fail] = *make_target_blocks(self) {
assert_eq!(value.ty, ty); assert_eq!(value.ty, ty);
let expect = self.literal_operand(test.span, value); let expect = self.literal_operand(test.span, value);
let val = Operand::Copy(place); let val = Operand::Copy(place);
@ -260,7 +259,6 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
bug!("`TestKind::Eq` should have two target blocks"); bug!("`TestKind::Eq` should have two target blocks");
} }
} }
}
TestKind::Range(PatRange { ref lo, ref hi, ref end }) => { TestKind::Range(PatRange { ref lo, ref hi, ref end }) => {
let lower_bound_success = self.cfg.start_new_block(); let lower_bound_success = self.cfg.start_new_block();

View File

@ -331,8 +331,7 @@ impl DropTree {
} }
if let DropKind::Value = drop_data.0.kind { if let DropKind::Value = drop_data.0.kind {
needs_block[drop_data.1] = Block::Own; needs_block[drop_data.1] = Block::Own;
} else { } else if drop_idx != ROOT_NODE {
if drop_idx != ROOT_NODE {
match &mut needs_block[drop_data.1] { match &mut needs_block[drop_data.1] {
pred @ Block::None => *pred = Block::Shares(drop_idx), pred @ Block::None => *pred = Block::Shares(drop_idx),
pred @ Block::Shares(_) => *pred = Block::Own, pred @ Block::Shares(_) => *pred = Block::Own,
@ -340,7 +339,6 @@ impl DropTree {
} }
} }
} }
}
debug!("assign_blocks: blocks = {:#?}", blocks); debug!("assign_blocks: blocks = {:#?}", blocks);
assert!(entry_points.is_empty()); assert!(entry_points.is_empty());
@ -461,9 +459,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let breakable_scope = self.scopes.breakable_scopes.pop().unwrap(); let breakable_scope = self.scopes.breakable_scopes.pop().unwrap();
assert!(breakable_scope.region_scope == region_scope); assert!(breakable_scope.region_scope == region_scope);
let break_block = self.build_exit_tree(breakable_scope.break_drops, None); let break_block = self.build_exit_tree(breakable_scope.break_drops, None);
breakable_scope.continue_drops.map(|drops| { if let Some(drops) = breakable_scope.continue_drops { self.build_exit_tree(drops, loop_block); }
self.build_exit_tree(drops, loop_block);
});
match (normal_exit_block, break_block) { match (normal_exit_block, break_block) {
(Some(block), None) | (None, Some(block)) => block, (Some(block), None) | (None, Some(block)) => block,
(None, None) => self.cfg.start_new_block().unit(), (None, None) => self.cfg.start_new_block().unit(),

View File

@ -316,8 +316,7 @@ fn make_mirror_unadjusted<'a, 'tcx>(
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => { hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
if cx.typeck_results().is_method_call(expr) { if cx.typeck_results().is_method_call(expr) {
overloaded_operator(cx, expr, vec![arg.to_ref()]) overloaded_operator(cx, expr, vec![arg.to_ref()])
} else { } else if let hir::ExprKind::Lit(ref lit) = arg.kind {
if let hir::ExprKind::Lit(ref lit) = arg.kind {
ExprKind::Literal { ExprKind::Literal {
literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true), literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
user_ty: None, user_ty: None,
@ -327,7 +326,6 @@ fn make_mirror_unadjusted<'a, 'tcx>(
ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() } ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() }
} }
} }
}
hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() { hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() {
ty::Adt(adt, substs) => match adt.adt_kind() { ty::Adt(adt, substs) => match adt.adt_kind() {

View File

@ -337,10 +337,7 @@ impl<'tcx> PatternFolder<'tcx> for LiteralExpander {
impl<'tcx> Pat<'tcx> { impl<'tcx> Pat<'tcx> {
pub(super) fn is_wildcard(&self) -> bool { pub(super) fn is_wildcard(&self) -> bool {
match *self.kind { matches!(*self.kind, PatKind::Binding { subpattern: None, .. } | PatKind::Wild)
PatKind::Binding { subpattern: None, .. } | PatKind::Wild => true,
_ => false,
}
} }
} }
@ -1358,10 +1355,7 @@ impl<'tcx> Usefulness<'tcx> {
} }
fn is_useful(&self) -> bool { fn is_useful(&self) -> bool {
match *self { !matches!(*self, NotUseful)
NotUseful => false,
_ => true,
}
} }
fn apply_constructor<'p>( fn apply_constructor<'p>(
@ -1623,10 +1617,7 @@ struct IntRange<'tcx> {
impl<'tcx> IntRange<'tcx> { impl<'tcx> IntRange<'tcx> {
#[inline] #[inline]
fn is_integral(ty: Ty<'_>) -> bool { fn is_integral(ty: Ty<'_>) -> bool {
match ty.kind() { matches!(ty.kind(), ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool)
ty::Char | ty::Int(_) | ty::Uint(_) | ty::Bool => true,
_ => false,
}
} }
fn is_singleton(&self) -> bool { fn is_singleton(&self) -> bool {

View File

@ -223,10 +223,7 @@ impl<'tcx> fmt::Display for Pat<'tcx> {
BindingMode::ByValue => mutability == Mutability::Mut, BindingMode::ByValue => mutability == Mutability::Mut,
BindingMode::ByRef(bk) => { BindingMode::ByRef(bk) => {
write!(f, "ref ")?; write!(f, "ref ")?;
match bk { matches!(bk, BorrowKind::Mut { .. })
BorrowKind::Mut { .. } => true,
_ => false,
}
} }
}; };
if is_mut { if is_mut {

View File

@ -606,7 +606,7 @@ fn prepend_attrs(
) -> Option<tokenstream::TokenStream> { ) -> Option<tokenstream::TokenStream> {
let tokens = tokens?.clone().into_token_stream(); let tokens = tokens?.clone().into_token_stream();
if attrs.is_empty() { if attrs.is_empty() {
return Some(tokens.clone()); return Some(tokens);
} }
let mut builder = tokenstream::TokenStreamBuilder::new(); let mut builder = tokenstream::TokenStreamBuilder::new();
for attr in attrs { for attr in attrs {
@ -622,6 +622,6 @@ fn prepend_attrs(
.into_token_stream(), .into_token_stream(),
); );
} }
builder.push(tokens.clone()); builder.push(tokens);
Some(builder.build()) Some(builder.build())
} }

View File

@ -1359,11 +1359,7 @@ impl<'a> Parser<'a> {
(self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish. (self.token == token::Lt && // `foo:<bar`, likely a typoed turbofish.
self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())) self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()))
|| self.token.is_ident() && || self.token.is_ident() &&
match node { matches!(node, ast::ExprKind::Path(..) | ast::ExprKind::Field(..)) &&
// `foo::` → `foo:` or `foo.bar::` → `foo.bar:`
ast::ExprKind::Path(..) | ast::ExprKind::Field(..) => true,
_ => false,
} &&
!self.token.is_reserved_ident() && // v `foo:bar(baz)` !self.token.is_reserved_ident() && // v `foo:bar(baz)`
self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren))
|| self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {` || self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) // `foo:bar {`

View File

@ -376,8 +376,7 @@ impl<'a> Parser<'a> {
format!(" {} ", kw), format!(" {} ", kw),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} else { } else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
if let Ok(snippet) = self.span_to_snippet(ident_sp) {
err.span_suggestion( err.span_suggestion(
full_sp, full_sp,
"if you meant to call a macro, try", "if you meant to call a macro, try",
@ -391,7 +390,6 @@ impl<'a> Parser<'a> {
and add a trailing `!` after the identifier", and add a trailing `!` after the identifier",
); );
} }
}
Err(err) Err(err)
} else if self.look_ahead(1, |t| *t == token::Lt) { } else if self.look_ahead(1, |t| *t == token::Lt) {
let ident = self.parse_ident().unwrap(); let ident = self.parse_ident().unwrap();
@ -982,10 +980,7 @@ impl<'a> Parser<'a> {
if token.is_keyword(kw::Move) { if token.is_keyword(kw::Move) {
return true; return true;
} }
match token.kind { matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
token::BinOp(token::Or) | token::OrOr => true,
_ => false,
}
}) })
} else { } else {
false false

View File

@ -38,16 +38,13 @@ impl<'a> Parser<'a> {
}, },
NonterminalKind::Block => match token.kind { NonterminalKind::Block => match token.kind {
token::OpenDelim(token::Brace) => true, token::OpenDelim(token::Brace) => true,
token::Interpolated(ref nt) => match **nt { token::Interpolated(ref nt) => !matches!(**nt, token::NtItem(_)
token::NtItem(_)
| token::NtPat(_) | token::NtPat(_)
| token::NtTy(_) | token::NtTy(_)
| token::NtIdent(..) | token::NtIdent(..)
| token::NtMeta(_) | token::NtMeta(_)
| token::NtPath(_) | token::NtPath(_)
| token::NtVis(_) => false, // none of these may start with '{'. | token::NtVis(_)),
_ => true,
},
_ => false, _ => false,
}, },
NonterminalKind::Path | NonterminalKind::Meta => match token.kind { NonterminalKind::Path | NonterminalKind::Meta => match token.kind {
@ -76,17 +73,14 @@ impl<'a> Parser<'a> {
}, },
NonterminalKind::Lifetime => match token.kind { NonterminalKind::Lifetime => match token.kind {
token::Lifetime(_) => true, token::Lifetime(_) => true,
token::Interpolated(ref nt) => match **nt { token::Interpolated(ref nt) => {
token::NtLifetime(_) | token::NtTT(_) => true, matches!(**nt, token::NtLifetime(_) | token::NtTT(_))
}
_ => false, _ => false,
}, },
_ => false, NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => {
}, !matches!(token.kind, token::CloseDelim(_))
NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => match token.kind }
{
token::CloseDelim(_) => false,
_ => true,
},
} }
} }

View File

@ -149,7 +149,9 @@ impl<'a> Parser<'a> {
/// Note that there are more tokens such as `@` for which we know that the `|` /// Note that there are more tokens such as `@` for which we know that the `|`
/// is an illegal parse. However, the user's intent is less clear in that case. /// is an illegal parse. However, the user's intent is less clear in that case.
fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool { fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
let is_end_ahead = self.look_ahead(1, |token| match &token.uninterpolate().kind { let is_end_ahead = self.look_ahead(1, |token| {
matches!(
&token.uninterpolate().kind,
token::FatArrow // e.g. `a | => 0,`. token::FatArrow // e.g. `a | => 0,`.
| token::Ident(kw::If, false) // e.g. `a | if expr`. | token::Ident(kw::If, false) // e.g. `a | if expr`.
| token::Eq // e.g. `let a | = 0`. | token::Eq // e.g. `let a | = 0`.
@ -158,8 +160,8 @@ impl<'a> Parser<'a> {
| token::Comma // e.g. `let (a |,)`. | token::Comma // e.g. `let (a |,)`.
| token::CloseDelim(token::Bracket) // e.g. `let [a | ]`. | token::CloseDelim(token::Bracket) // e.g. `let [a | ]`.
| token::CloseDelim(token::Paren) // e.g. `let (a | )`. | token::CloseDelim(token::Paren) // e.g. `let (a | )`.
| token::CloseDelim(token::Brace) => true, // e.g. `let A { f: a | }`. | token::CloseDelim(token::Brace) // e.g. `let A { f: a | }`.
_ => false, )
}); });
match (is_end_ahead, &self.token.kind) { match (is_end_ahead, &self.token.kind) {
(true, token::BinOp(token::Or) | token::OrOr) => { (true, token::BinOp(token::Or) | token::OrOr) => {
@ -766,14 +768,12 @@ impl<'a> Parser<'a> {
&& !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path. && !self.token.is_path_segment_keyword() // Avoid e.g. `Self` as it is a path.
// Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`. // Avoid `in`. Due to recovery in the list parser this messes with `for ( $pat in $expr )`.
&& !self.token.is_keyword(kw::In) && !self.token.is_keyword(kw::In)
&& self.look_ahead(1, |t| match t.kind { // Try to do something more complex? // Try to do something more complex?
token::OpenDelim(token::Paren) // A tuple struct pattern. && self.look_ahead(1, |t| !matches!(t.kind, token::OpenDelim(token::Paren) // A tuple struct pattern.
| token::OpenDelim(token::Brace) // A struct pattern. | token::OpenDelim(token::Brace) // A struct pattern.
| token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern. | token::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
| token::ModSep // A tuple / struct variant pattern. | token::ModSep // A tuple / struct variant pattern.
| token::Not => false, // A macro expanding to a pattern. | token::Not)) // A macro expanding to a pattern.
_ => true,
})
} }
/// Parses `ident` or `ident @ pat`. /// Parses `ident` or `ident @ pat`.

View File

@ -187,12 +187,14 @@ impl<'a> Parser<'a> {
pub(super) fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> { pub(super) fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
let ident = self.parse_path_segment_ident()?; let ident = self.parse_path_segment_ident()?;
let is_args_start = |token: &Token| match token.kind { let is_args_start = |token: &Token| {
matches!(
token.kind,
token::Lt token::Lt
| token::BinOp(token::Shl) | token::BinOp(token::Shl)
| token::OpenDelim(token::Paren) | token::OpenDelim(token::Paren)
| token::LArrow => true, | token::LArrow
_ => false, )
}; };
let check_args_start = |this: &mut Self| { let check_args_start = |this: &mut Self| {
this.expected_tokens.extend_from_slice(&[ this.expected_tokens.extend_from_slice(&[

View File

@ -1219,9 +1219,11 @@ impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> {
.maybe_typeck_results .maybe_typeck_results
.and_then(|typeck_results| typeck_results.type_dependent_def(id)), .and_then(|typeck_results| typeck_results.type_dependent_def(id)),
}; };
let def = def.filter(|(kind, _)| match kind { let def = def.filter(|(kind, _)| {
DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static => true, matches!(
_ => false, kind,
DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static
)
}); });
if let Some((kind, def_id)) = def { if let Some((kind, def_id)) = def {
let is_local_static = let is_local_static =

View File

@ -292,11 +292,9 @@ impl<K: DepKind> DepGraph<K> {
); );
data.colors.insert(prev_index, color); data.colors.insert(prev_index, color);
} else { } else if print_status {
if print_status {
eprintln!("[task::new] {:?}", key); eprintln!("[task::new] {:?}", key);
} }
}
(result, dep_node_index) (result, dep_node_index)
} else { } else {

View File

@ -612,11 +612,9 @@ where
prof_timer.finish_with_query_invocation_id(dep_node_index.into()); prof_timer.finish_with_query_invocation_id(dep_node_index.into());
if unlikely!(!diagnostics.is_empty()) { if unlikely!(!diagnostics.is_empty()) && dep_node.kind != DepKind::NULL {
if dep_node.kind != DepKind::NULL {
tcx.store_diagnostics(dep_node_index, diagnostics); tcx.store_diagnostics(dep_node_index, diagnostics);
} }
}
let result = job.complete(result, dep_node_index); let result = job.complete(result, dep_node_index);

View File

@ -344,10 +344,10 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> {
fn block_needs_anonymous_module(&mut self, block: &Block) -> bool { fn block_needs_anonymous_module(&mut self, block: &Block) -> bool {
// If any statements are items, we need to create an anonymous module // If any statements are items, we need to create an anonymous module
block.stmts.iter().any(|statement| match statement.kind { block
StmtKind::Item(_) | StmtKind::MacCall(_) => true, .stmts
_ => false, .iter()
}) .any(|statement| matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_)))
} }
// Add an import to the current module. // Add an import to the current module.

View File

@ -922,15 +922,10 @@ impl<'a> Resolver<'a> {
); );
self.add_typo_suggestion(err, suggestion, ident.span); self.add_typo_suggestion(err, suggestion, ident.span);
let import_suggestions = self.lookup_import_candidates( let import_suggestions =
ident, self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, |res| {
Namespace::MacroNS, matches!(res, Res::Def(DefKind::Macro(MacroKind::Bang), _))
parent_scope, });
|res| match res {
Res::Def(DefKind::Macro(MacroKind::Bang), _) => true,
_ => false,
},
);
show_candidates(err, None, &import_suggestions, false, true); show_candidates(err, None, &import_suggestions, false, true);
if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) { if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
@ -1010,11 +1005,9 @@ impl<'a> Resolver<'a> {
fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String { fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
let res = b.res(); let res = b.res();
if b.span.is_dummy() { if b.span.is_dummy() {
let add_built_in = match b.res() {
// These already contain the "built-in" prefix or look bad with it. // These already contain the "built-in" prefix or look bad with it.
Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false, let add_built_in =
_ => true, !matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
};
let (built_in, from) = if from_prelude { let (built_in, from) = if from_prelude {
("", " from prelude") ("", " from prelude")
} else if b.is_extern_crate() } else if b.is_extern_crate()
@ -1610,10 +1603,7 @@ fn find_span_immediately_after_crate_name(
if *c == ':' { if *c == ':' {
num_colons += 1; num_colons += 1;
} }
match c { !matches!(c, ':' if num_colons == 2)
':' if num_colons == 2 => false,
_ => true,
}
}); });
// Find everything after the second colon.. `foo::{baz, makro};` // Find everything after the second colon.. `foo::{baz, makro};`
let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1)); let from_second_colon = use_span.with_lo(until_second_colon.hi() + BytePos(1));

View File

@ -114,10 +114,7 @@ crate struct Import<'a> {
impl<'a> Import<'a> { impl<'a> Import<'a> {
pub fn is_glob(&self) -> bool { pub fn is_glob(&self) -> bool {
match self.kind { matches!(self.kind, ImportKind::Glob { .. })
ImportKind::Glob { .. } => true,
_ => false,
}
} }
pub fn is_nested(&self) -> bool { pub fn is_nested(&self) -> bool {
@ -898,13 +895,11 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
let msg = "inconsistent resolution for an import"; let msg = "inconsistent resolution for an import";
self.r.session.span_err(import.span, msg); self.r.session.span_err(import.span, msg);
} }
} else { } else if self.r.privacy_errors.is_empty() {
if self.r.privacy_errors.is_empty() {
let msg = "cannot determine resolution for the import"; let msg = "cannot determine resolution for the import";
let msg_note = "import resolution is stuck, try simplifying other imports"; let msg_note = "import resolution is stuck, try simplifying other imports";
self.r.session.struct_span_err(import.span, msg).note(msg_note).emit(); self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
} }
}
module module
} }
@ -1044,19 +1039,14 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
if res != initial_res && this.ambiguity_errors.is_empty() { if res != initial_res && this.ambiguity_errors.is_empty() {
span_bug!(import.span, "inconsistent resolution for an import"); span_bug!(import.span, "inconsistent resolution for an import");
} }
} else { } else if res != Res::Err
if res != Res::Err
&& this.ambiguity_errors.is_empty() && this.ambiguity_errors.is_empty()
&& this.privacy_errors.is_empty() && this.privacy_errors.is_empty()
{ {
let msg = "cannot determine resolution for the import"; let msg = "cannot determine resolution for the import";
let msg_note = let msg_note =
"import resolution is stuck, try simplifying other imports"; "import resolution is stuck, try simplifying other imports";
this.session this.session.struct_span_err(import.span, msg).note(msg_note).emit();
.struct_span_err(import.span, msg)
.note(msg_note)
.emit();
}
} }
} }
Err(..) => { Err(..) => {

View File

@ -257,16 +257,12 @@ impl<'a> PathSource<'a> {
} }
fn is_call(self) -> bool { fn is_call(self) -> bool {
match self { matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })) => true,
_ => false,
}
} }
crate fn is_expected(self, res: Res) -> bool { crate fn is_expected(self, res: Res) -> bool {
match self { match self {
PathSource::Type => match res { PathSource::Type => matches!(res, Res::Def(
Res::Def(
DefKind::Struct DefKind::Struct
| DefKind::Union | DefKind::Union
| DefKind::Enum | DefKind::Enum
@ -280,19 +276,12 @@ impl<'a> PathSource<'a> {
_, _,
) )
| Res::PrimTy(..) | Res::PrimTy(..)
| Res::SelfTy(..) => true, | Res::SelfTy(..)),
_ => false, PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
}, PathSource::Trait(AliasPossibility::Maybe) => {
PathSource::Trait(AliasPossibility::No) => match res { matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
Res::Def(DefKind::Trait, _) => true, }
_ => false, PathSource::Expr(..) => matches!(res, Res::Def(
},
PathSource::Trait(AliasPossibility::Maybe) => match res {
Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
_ => false,
},
PathSource::Expr(..) => match res {
Res::Def(
DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn) DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
| DefKind::Const | DefKind::Const
| DefKind::Static | DefKind::Static
@ -303,23 +292,16 @@ impl<'a> PathSource<'a> {
_, _,
) )
| Res::Local(..) | Res::Local(..)
| Res::SelfCtor(..) => true, | Res::SelfCtor(..)),
_ => false, PathSource::Pat => matches!(res, Res::Def(
},
PathSource::Pat => match res {
Res::Def(
DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst, DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst,
_, _,
) )
| Res::SelfCtor(..) => true, | Res::SelfCtor(..)),
_ => false, PathSource::TupleStruct(..) => {
}, matches!(res, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
PathSource::TupleStruct(..) => match res { }
Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true, PathSource::Struct => matches!(res, Res::Def(
_ => false,
},
PathSource::Struct => match res {
Res::Def(
DefKind::Struct DefKind::Struct
| DefKind::Union | DefKind::Union
| DefKind::Variant | DefKind::Variant
@ -327,9 +309,7 @@ impl<'a> PathSource<'a> {
| DefKind::AssocTy, | DefKind::AssocTy,
_, _,
) )
| Res::SelfTy(..) => true, | Res::SelfTy(..)),
_ => false,
},
PathSource::TraitItem(ns) => match res { PathSource::TraitItem(ns) => match res {
Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true, Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true, Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
@ -1450,10 +1430,7 @@ impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
} }
fn is_base_res_local(&self, nid: NodeId) -> bool { fn is_base_res_local(&self, nid: NodeId) -> bool {
match self.r.partial_res_map.get(&nid).map(|res| res.base_res()) { matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..)))
Some(Res::Local(..)) => true,
_ => false,
}
} }
/// Checks that all of the arms in an or-pattern have exactly the /// Checks that all of the arms in an or-pattern have exactly the

View File

@ -702,10 +702,7 @@ impl<'a: 'ast, 'ast> LateResolutionVisitor<'a, '_, 'ast> {
_ => break, _ => break,
} }
} }
let followed_by_brace = match sm.span_to_snippet(sp) { let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
Ok(ref snippet) if snippet == "{" => true,
_ => false,
};
// In case this could be a struct literal that needs to be surrounded // In case this could be a struct literal that needs to be surrounded
// by parentheses, find the appropriate span. // by parentheses, find the appropriate span.
let mut i = 0; let mut i = 0;
@ -1788,12 +1785,11 @@ impl<'tcx> LifetimeContext<'_, 'tcx> {
} }
msg = "consider introducing a named lifetime parameter".to_string(); msg = "consider introducing a named lifetime parameter".to_string();
should_break = true; should_break = true;
if let Some(param) = generics.params.iter().find(|p| match p.kind { if let Some(param) = generics.params.iter().find(|p| {
hir::GenericParamKind::Type { !matches!(p.kind, hir::GenericParamKind::Type {
synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
.. ..
} => false, })
_ => true,
}) { }) {
(param.span.shrink_to_lo(), "'a, ".to_string()) (param.span.shrink_to_lo(), "'a, ".to_string())
} else { } else {

View File

@ -351,10 +351,7 @@ fn krate(tcx: TyCtxt<'_>) -> NamedRegionMap {
/// We have to account for this when computing the index of the other generic parameters. /// We have to account for this when computing the index of the other generic parameters.
/// This function returns whether there is such an implicit parameter defined on the given item. /// This function returns whether there is such an implicit parameter defined on the given item.
fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool { fn sub_items_have_self_param(node: &hir::ItemKind<'_>) -> bool {
match *node { matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => true,
_ => false,
}
} }
impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
@ -417,10 +414,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
// Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name". // Impls permit `'_` to be used and it is equivalent to "some fresh lifetime name".
// This is not true for other kinds of items.x // This is not true for other kinds of items.x
let track_lifetime_uses = match item.kind { let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. });
hir::ItemKind::Impl { .. } => true,
_ => false,
};
// These kinds of items have only early-bound lifetime parameters. // These kinds of items have only early-bound lifetime parameters.
let mut index = if sub_items_have_self_param(&item.kind) { let mut index = if sub_items_have_self_param(&item.kind) {
1 // Self comes before lifetimes 1 // Self comes before lifetimes
@ -970,10 +964,10 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> {
let trait_ref_hack = take(&mut self.trait_ref_hack); let trait_ref_hack = take(&mut self.trait_ref_hack);
if !trait_ref_hack if !trait_ref_hack
|| trait_ref.bound_generic_params.iter().any(|param| match param.kind { || trait_ref
GenericParamKind::Lifetime { .. } => true, .bound_generic_params
_ => false, .iter()
}) .any(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
{ {
if trait_ref_hack { if trait_ref_hack {
struct_span_err!( struct_span_err!(
@ -1384,8 +1378,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
} }
if in_band { if in_band {
Some(param.span) Some(param.span)
} else { } else if generics.params.len() == 1 {
if generics.params.len() == 1 {
// if sole lifetime, remove the entire `<>` brackets // if sole lifetime, remove the entire `<>` brackets
Some(generics.span) Some(generics.span)
} else { } else {
@ -1397,7 +1390,6 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
Some(param.span.to(generics.params[i + 1].span.shrink_to_lo())) Some(param.span.to(generics.params[i + 1].span.shrink_to_lo()))
} }
} }
}
} else { } else {
None None
} }
@ -2047,10 +2039,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
// //
// This is intended to leave room for us to implement the // This is intended to leave room for us to implement the
// correct behavior in the future. // correct behavior in the future.
let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg { let has_lifetime_parameter =
GenericArg::Lifetime(_) => true, generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
_ => false,
});
// Resolve lifetimes found in the type `XX` from `Item = XX` bindings. // Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
for b in generic_args.bindings { for b in generic_args.bindings {

View File

@ -313,8 +313,9 @@ impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
ItemKind::ExternCrate(_) => {} ItemKind::ExternCrate(_) => {}
// but place them before the first other item // but place them before the first other item
_ => { _ => {
if self.span.map_or(true, |span| item.span < span) { if self.span.map_or(true, |span| item.span < span)
if !item.span.from_expansion() { && !item.span.from_expansion()
{
// don't insert between attributes and an item // don't insert between attributes and an item
if item.attrs.is_empty() { if item.attrs.is_empty() {
self.span = Some(item.span.shrink_to_lo()); self.span = Some(item.span.shrink_to_lo());
@ -332,7 +333,6 @@ impl<'tcx> Visitor<'tcx> for UsePlacementFinder {
} }
} }
} }
}
/// An intermediate resolution result. /// An intermediate resolution result.
/// ///
@ -558,17 +558,11 @@ impl<'a> ModuleData<'a> {
// `self` resolves to the first module ancestor that `is_normal`. // `self` resolves to the first module ancestor that `is_normal`.
fn is_normal(&self) -> bool { fn is_normal(&self) -> bool {
match self.kind { matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
ModuleKind::Def(DefKind::Mod, _, _) => true,
_ => false,
}
} }
fn is_trait(&self) -> bool { fn is_trait(&self) -> bool {
match self.kind { matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
ModuleKind::Def(DefKind::Trait, _, _) => true,
_ => false,
}
} }
fn nearest_item_scope(&'a self) -> Module<'a> { fn nearest_item_scope(&'a self) -> Module<'a> {
@ -628,10 +622,7 @@ enum NameBindingKind<'a> {
impl<'a> NameBindingKind<'a> { impl<'a> NameBindingKind<'a> {
/// Is this a name binding of a import? /// Is this a name binding of a import?
fn is_import(&self) -> bool { fn is_import(&self) -> bool {
match *self { matches!(*self, NameBindingKind::Import { .. })
NameBindingKind::Import { .. } => true,
_ => false,
}
} }
} }
@ -750,13 +741,10 @@ impl<'a> NameBinding<'a> {
} }
fn is_variant(&self) -> bool { fn is_variant(&self) -> bool {
match self.kind { matches!(self.kind, NameBindingKind::Res(
NameBindingKind::Res(
Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _), Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), _),
_, _,
) => true, ))
_ => false,
}
} }
fn is_extern_crate(&self) -> bool { fn is_extern_crate(&self) -> bool {
@ -774,10 +762,7 @@ impl<'a> NameBinding<'a> {
} }
fn is_import(&self) -> bool { fn is_import(&self) -> bool {
match self.kind { matches!(self.kind, NameBindingKind::Import { .. })
NameBindingKind::Import { .. } => true,
_ => false,
}
} }
fn is_glob_import(&self) -> bool { fn is_glob_import(&self) -> bool {
@ -788,17 +773,14 @@ impl<'a> NameBinding<'a> {
} }
fn is_importable(&self) -> bool { fn is_importable(&self) -> bool {
match self.res() { !matches!(
Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) => false, self.res(),
_ => true, Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _)
} )
} }
fn is_macro_def(&self) -> bool { fn is_macro_def(&self) -> bool {
match self.kind { matches!(self.kind, NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _))
NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _) => true,
_ => false,
}
} }
fn macro_kind(&self) -> Option<MacroKind> { fn macro_kind(&self) -> Option<MacroKind> {
@ -1380,7 +1362,7 @@ impl<'a> Resolver<'a> {
let maybe_unused_extern_crates = self.maybe_unused_extern_crates; let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
let glob_map = self.glob_map; let glob_map = self.glob_map;
ResolverOutputs { ResolverOutputs {
definitions: definitions, definitions,
cstore: Box::new(self.crate_loader.into_cstore()), cstore: Box::new(self.crate_loader.into_cstore()),
visibilities, visibilities,
extern_crate_map, extern_crate_map,
@ -1992,8 +1974,10 @@ impl<'a> Resolver<'a> {
// The macro is a proc macro derive // The macro is a proc macro derive
if let Some(def_id) = module.expansion.expn_data().macro_def_id { if let Some(def_id) = module.expansion.expn_data().macro_def_id {
if let Some(ext) = self.get_macro_by_def_id(def_id) { if let Some(ext) = self.get_macro_by_def_id(def_id) {
if !ext.is_builtin && ext.macro_kind() == MacroKind::Derive { if !ext.is_builtin
if parent.expansion.outer_expn_is_descendant_of(span.ctxt()) { && ext.macro_kind() == MacroKind::Derive
&& parent.expansion.outer_expn_is_descendant_of(span.ctxt())
{
*poisoned = Some(node_id); *poisoned = Some(node_id);
return module.parent; return module.parent;
} }
@ -2001,7 +1985,6 @@ impl<'a> Resolver<'a> {
} }
} }
} }
}
None None
} }
@ -2390,10 +2373,7 @@ impl<'a> Resolver<'a> {
_ => None, _ => None,
}; };
let (label, suggestion) = if module_res == self.graph_root.res() { let (label, suggestion) = if module_res == self.graph_root.res() {
let is_mod = |res| match res { let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _));
Res::Def(DefKind::Mod, _) => true,
_ => false,
};
// Don't look up import candidates if this is a speculative resolve // Don't look up import candidates if this is a speculative resolve
let mut candidates = if record_used { let mut candidates = if record_used {
self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod) self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod)

View File

@ -2057,10 +2057,7 @@ impl PpMode {
pub fn needs_analysis(&self) -> bool { pub fn needs_analysis(&self) -> bool {
use PpMode::*; use PpMode::*;
match *self { matches!(*self, PpmMir | PpmMirCFG)
PpmMir | PpmMirCFG => true,
_ => false,
}
} }
} }

View File

@ -199,11 +199,9 @@ pub fn invalid_output_for_target(sess: &Session, crate_type: CrateType) -> bool
_ => {} _ => {}
} }
} }
if !sess.target.options.executables { if !sess.target.options.executables && crate_type == CrateType::Executable {
if crate_type == CrateType::Executable {
return true; return true;
} }
}
false false
} }

View File

@ -326,10 +326,8 @@ impl Printer<'tcx> for SymbolPrinter<'tcx> {
) -> Result<Self::Path, Self::Error> { ) -> Result<Self::Path, Self::Error> {
self = print_prefix(self)?; self = print_prefix(self)?;
let args = args.iter().cloned().filter(|arg| match arg.unpack() { let args =
GenericArgKind::Lifetime(_) => false, args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
_ => true,
});
if args.clone().next().is_some() { if args.clone().next().is_some() {
self.generic_delimiters(|cx| cx.comma_sep(args)) self.generic_delimiters(|cx| cx.comma_sep(args))

View File

@ -174,10 +174,7 @@ fn compute_symbol_name(
return tcx.sess.generate_proc_macro_decls_symbol(disambiguator); return tcx.sess.generate_proc_macro_decls_symbol(disambiguator);
} }
let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
match tcx.hir().get(hir_id) { matches!(tcx.hir().get(hir_id), Node::ForeignItem(_))
Node::ForeignItem(_) => true,
_ => false,
}
} else { } else {
tcx.is_foreign_item(def_id) tcx.is_foreign_item(def_id)
}; };
@ -200,16 +197,15 @@ fn compute_symbol_name(
// show up in the `wasm-import-name` custom attribute in LLVM IR. // show up in the `wasm-import-name` custom attribute in LLVM IR.
// //
// [1]: https://bugs.llvm.org/show_bug.cgi?id=44316 // [1]: https://bugs.llvm.org/show_bug.cgi?id=44316
if is_foreign { if is_foreign
if tcx.sess.target.arch != "wasm32" && (tcx.sess.target.arch != "wasm32"
|| !tcx.wasm_import_module_map(def_id.krate).contains_key(&def_id) || !tcx.wasm_import_module_map(def_id.krate).contains_key(&def_id))
{ {
if let Some(name) = attrs.link_name { if let Some(name) = attrs.link_name {
return name.to_string(); return name.to_string();
} }
return tcx.item_name(def_id).to_string(); return tcx.item_name(def_id).to_string();
} }
}
if let Some(name) = attrs.export_name { if let Some(name) = attrs.export_name {
// Use provided name // Use provided name
@ -234,10 +230,7 @@ fn compute_symbol_name(
// codegen units) then this symbol may become an exported (but hidden // codegen units) then this symbol may become an exported (but hidden
// visibility) symbol. This means that multiple crates may do the same // visibility) symbol. This means that multiple crates may do the same
// and we want to be sure to avoid any symbol conflicts here. // and we want to be sure to avoid any symbol conflicts here.
match MonoItem::Fn(instance).instantiation_mode(tcx) { matches!(MonoItem::Fn(instance).instantiation_mode(tcx), InstantiationMode::GloballyShared { may_conflict: true });
InstantiationMode::GloballyShared { may_conflict: true } => true,
_ => false,
};
let instantiating_crate = let instantiating_crate =
if avoid_cross_crate_conflicts { Some(compute_instantiating_crate()) } else { None }; if avoid_cross_crate_conflicts { Some(compute_instantiating_crate()) } else { None };

View File

@ -474,31 +474,19 @@ impl<'a, Ty> ArgAbi<'a, Ty> {
} }
pub fn is_indirect(&self) -> bool { pub fn is_indirect(&self) -> bool {
match self.mode { matches!(self.mode, PassMode::Indirect(..))
PassMode::Indirect(..) => true,
_ => false,
}
} }
pub fn is_sized_indirect(&self) -> bool { pub fn is_sized_indirect(&self) -> bool {
match self.mode { matches!(self.mode, PassMode::Indirect(_, None))
PassMode::Indirect(_, None) => true,
_ => false,
}
} }
pub fn is_unsized_indirect(&self) -> bool { pub fn is_unsized_indirect(&self) -> bool {
match self.mode { matches!(self.mode, PassMode::Indirect(_, Some(_)))
PassMode::Indirect(_, Some(_)) => true,
_ => false,
}
} }
pub fn is_ignore(&self) -> bool { pub fn is_ignore(&self) -> bool {
match self.mode { matches!(self.mode, PassMode::Ignore)
PassMode::Ignore => true,
_ => false,
}
} }
} }

View File

@ -333,11 +333,9 @@ where
let mut avail_gprs = 8; let mut avail_gprs = 8;
let mut avail_fprs = 8; let mut avail_fprs = 8;
if !fn_abi.ret.is_ignore() { if !fn_abi.ret.is_ignore() && classify_ret(cx, &mut fn_abi.ret, xlen, flen) {
if classify_ret(cx, &mut fn_abi.ret, xlen, flen) {
avail_gprs -= 1; avail_gprs -= 1;
} }
}
for (i, arg) in fn_abi.args.iter_mut().enumerate() { for (i, arg) in fn_abi.args.iter_mut().enumerate() {
if arg.is_ignore() { if arg.is_ignore() {

View File

@ -24,12 +24,10 @@ where
C: LayoutOf<Ty = Ty, TyAndLayout = TyAndLayout<'a, Ty>> + HasDataLayout, C: LayoutOf<Ty = Ty, TyAndLayout = TyAndLayout<'a, Ty>> + HasDataLayout,
{ {
ret.extend_integer_width_to(32); ret.extend_integer_width_to(32);
if ret.layout.is_aggregate() { if ret.layout.is_aggregate() && !unwrap_trivial_aggregate(cx, ret) {
if !unwrap_trivial_aggregate(cx, ret) {
ret.make_indirect(); ret.make_indirect();
} }
} }
}
fn classify_arg<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>) fn classify_arg<'a, Ty, C>(cx: &C, arg: &mut ArgAbi<'a, Ty>)
where where
@ -37,12 +35,10 @@ where
C: LayoutOf<Ty = Ty, TyAndLayout = TyAndLayout<'a, Ty>> + HasDataLayout, C: LayoutOf<Ty = Ty, TyAndLayout = TyAndLayout<'a, Ty>> + HasDataLayout,
{ {
arg.extend_integer_width_to(32); arg.extend_integer_width_to(32);
if arg.layout.is_aggregate() { if arg.layout.is_aggregate() && !unwrap_trivial_aggregate(cx, arg) {
if !unwrap_trivial_aggregate(cx, arg) {
arg.make_indirect_byval(); arg.make_indirect_byval();
} }
} }
}
pub fn compute_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>) pub fn compute_abi_info<'a, Ty, C>(cx: &C, fn_abi: &mut FnAbi<'a, Ty>)
where where

View File

@ -557,17 +557,11 @@ impl Primitive {
} }
pub fn is_float(self) -> bool { pub fn is_float(self) -> bool {
match self { matches!(self, F32 | F64)
F32 | F64 => true,
_ => false,
}
} }
pub fn is_int(self) -> bool { pub fn is_int(self) -> bool {
match self { matches!(self, Int(..))
Int(..) => true,
_ => false,
}
} }
} }
@ -794,18 +788,12 @@ impl Abi {
/// Returns `true` if this is an uninhabited type /// Returns `true` if this is an uninhabited type
pub fn is_uninhabited(&self) -> bool { pub fn is_uninhabited(&self) -> bool {
match *self { matches!(*self, Abi::Uninhabited)
Abi::Uninhabited => true,
_ => false,
}
} }
/// Returns `true` is this is a scalar type /// Returns `true` is this is a scalar type
pub fn is_scalar(&self) -> bool { pub fn is_scalar(&self) -> bool {
match *self { matches!(*self, Abi::Scalar(_))
Abi::Scalar(_) => true,
_ => false,
}
} }
} }

View File

@ -478,10 +478,7 @@ pub enum InlineAsmType {
impl InlineAsmType { impl InlineAsmType {
pub fn is_integer(self) -> bool { pub fn is_integer(self) -> bool {
match self { matches!(self, Self::I8 | Self::I16 | Self::I32 | Self::I64 | Self::I128)
Self::I8 | Self::I16 | Self::I32 | Self::I64 | Self::I128 => true,
_ => false,
}
} }
pub fn size(self) -> Size { pub fn size(self) -> Size {

View File

@ -342,29 +342,29 @@ impl<'tcx> chalk_solve::RustIrDatabase<RustInterner<'tcx>> for RustIrDatabase<'t
} }
(ty::Bool, Scalar(Bool)) => true, (ty::Bool, Scalar(Bool)) => true,
(ty::Char, Scalar(Char)) => true, (ty::Char, Scalar(Char)) => true,
(ty::Int(ty1), Scalar(Int(ty2))) => match (ty1, ty2) { (ty::Int(ty1), Scalar(Int(ty2))) => matches!(
(ty1, ty2),
(ast::IntTy::Isize, chalk_ir::IntTy::Isize) (ast::IntTy::Isize, chalk_ir::IntTy::Isize)
| (ast::IntTy::I8, chalk_ir::IntTy::I8) | (ast::IntTy::I8, chalk_ir::IntTy::I8)
| (ast::IntTy::I16, chalk_ir::IntTy::I16) | (ast::IntTy::I16, chalk_ir::IntTy::I16)
| (ast::IntTy::I32, chalk_ir::IntTy::I32) | (ast::IntTy::I32, chalk_ir::IntTy::I32)
| (ast::IntTy::I64, chalk_ir::IntTy::I64) | (ast::IntTy::I64, chalk_ir::IntTy::I64)
| (ast::IntTy::I128, chalk_ir::IntTy::I128) => true, | (ast::IntTy::I128, chalk_ir::IntTy::I128)
_ => false, ),
}, (ty::Uint(ty1), Scalar(Uint(ty2))) => matches!(
(ty::Uint(ty1), Scalar(Uint(ty2))) => match (ty1, ty2) { (ty1, ty2),
(ast::UintTy::Usize, chalk_ir::UintTy::Usize) (ast::UintTy::Usize, chalk_ir::UintTy::Usize)
| (ast::UintTy::U8, chalk_ir::UintTy::U8) | (ast::UintTy::U8, chalk_ir::UintTy::U8)
| (ast::UintTy::U16, chalk_ir::UintTy::U16) | (ast::UintTy::U16, chalk_ir::UintTy::U16)
| (ast::UintTy::U32, chalk_ir::UintTy::U32) | (ast::UintTy::U32, chalk_ir::UintTy::U32)
| (ast::UintTy::U64, chalk_ir::UintTy::U64) | (ast::UintTy::U64, chalk_ir::UintTy::U64)
| (ast::UintTy::U128, chalk_ir::UintTy::U128) => true, | (ast::UintTy::U128, chalk_ir::UintTy::U128)
_ => false, ),
}, (ty::Float(ty1), Scalar(Float(ty2))) => matches!(
(ty::Float(ty1), Scalar(Float(ty2))) => match (ty1, ty2) { (ty1, ty2),
(ast::FloatTy::F32, chalk_ir::FloatTy::F32) (ast::FloatTy::F32, chalk_ir::FloatTy::F32)
| (ast::FloatTy::F64, chalk_ir::FloatTy::F64) => true, | (ast::FloatTy::F64, chalk_ir::FloatTy::F64)
_ => false, ),
},
(&ty::Tuple(..), Tuple(..)) => true, (&ty::Tuple(..), Tuple(..)) => true,
(&ty::Array(..), Array) => true, (&ty::Array(..), Array) => true,
(&ty::Slice(..), Slice) => true, (&ty::Slice(..), Slice) => true,

View File

@ -62,7 +62,7 @@ fn compute_implied_outlives_bounds<'tcx>(
// unresolved inference variables here anyway, but there might be // unresolved inference variables here anyway, but there might be
// during typeck under some circumstances.) // during typeck under some circumstances.)
let obligations = wf::obligations(infcx, param_env, hir::CRATE_HIR_ID, 0, arg, DUMMY_SP) let obligations = wf::obligations(infcx, param_env, hir::CRATE_HIR_ID, 0, arg, DUMMY_SP)
.unwrap_or(vec![]); .unwrap_or_default();
// N.B., all of these predicates *ought* to be easily proven // N.B., all of these predicates *ought* to be easily proven
// true. In fact, their correctness is (mostly) implied by // true. In fact, their correctness is (mostly) implied by