Fix even more clippy warnings

This commit is contained in:
Joshua Nelson 2020-10-26 21:02:48 -04:00
parent bfecb18771
commit 57c6ed0c07
53 changed files with 276 additions and 520 deletions

View File

@ -228,7 +228,7 @@ impl<T> TypedArena<T> {
// bytes, then this chunk will be least double the previous
// chunk's size.
new_cap = last_chunk.storage.len().min(HUGE_PAGE / elem_size / 2);
new_cap = new_cap * 2;
new_cap *= 2;
} else {
new_cap = PAGE / elem_size;
}
@ -346,7 +346,7 @@ impl DroplessArena {
// bytes, then this chunk will be least double the previous
// chunk's size.
new_cap = last_chunk.storage.len().min(HUGE_PAGE / 2);
new_cap = new_cap * 2;
new_cap *= 2;
} else {
new_cap = PAGE;
}
@ -562,10 +562,8 @@ impl DropArena {
// 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
for i in 0..len {
destructors.push(DropType {
drop_fn: drop_for_type::<T>,
obj: start_ptr.offset(i as isize) as *mut u8,
});
destructors
.push(DropType { drop_fn: drop_for_type::<T>, obj: start_ptr.add(i) as *mut u8 });
}
slice::from_raw_parts_mut(start_ptr, len)

View File

@ -639,13 +639,11 @@ 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) {
if !self.is_beginning_of_line() {
self.break_offset(n, off)
} else {
if off != 0 && self.last_token().is_hardbreak_tok() {
// We do something pretty sketchy here: tuck the nonzero
// offset-adjustment we were going to deposit along with the
// break into the previous hardbreak.
self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
}
} else if off != 0 && self.last_token().is_hardbreak_tok() {
// We do something pretty sketchy here: tuck the nonzero
// offset-adjustment we were going to deposit along with the
// break into the previous hardbreak.
self.replace_last_token(pp::Printer::hardbreak_tok_offset(off));
}
}

View File

@ -901,38 +901,36 @@ pub fn find_repr_attrs(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
)
.emit();
}
} else {
if let Some(meta_item) = item.meta_item() {
if meta_item.has_name(sym::align) {
if let MetaItemKind::NameValue(ref value) = meta_item.kind {
recognised = true;
let mut err = struct_span_err!(
diagnostic,
item.span(),
E0693,
"incorrect `repr(align)` attribute format"
);
match value.kind {
ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
err.span_suggestion(
item.span(),
"use parentheses instead",
format!("align({})", int),
Applicability::MachineApplicable,
);
}
ast::LitKind::Str(s, _) => {
err.span_suggestion(
item.span(),
"use parentheses instead",
format!("align({})", s),
Applicability::MachineApplicable,
);
}
_ => {}
} else if let Some(meta_item) = item.meta_item() {
if meta_item.has_name(sym::align) {
if let MetaItemKind::NameValue(ref value) = meta_item.kind {
recognised = true;
let mut err = struct_span_err!(
diagnostic,
item.span(),
E0693,
"incorrect `repr(align)` attribute format"
);
match value.kind {
ast::LitKind::Int(int, ast::LitIntType::Unsuffixed) => {
err.span_suggestion(
item.span(),
"use parentheses instead",
format!("align({})", int),
Applicability::MachineApplicable,
);
}
err.emit();
ast::LitKind::Str(s, _) => {
err.span_suggestion(
item.span(),
"use parentheses instead",
format!("align({})", s),
Applicability::MachineApplicable,
);
}
_ => {}
}
err.emit();
}
}
}

View File

@ -93,7 +93,7 @@ pub(crate) unsafe fn codegen(
let args = [usize, usize]; // size, align
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);
// -> ! DIFlagNoReturn
llvm::Attribute::NoReturn.apply_llfn(llvm::AttributePlace::Function, llfn);

View File

@ -302,13 +302,11 @@ impl AsmBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
} else if options.contains(InlineAsmOptions::READONLY) {
llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result);
}
} else if options.contains(InlineAsmOptions::NOMEM) {
llvm::Attribute::InaccessibleMemOnly
.apply_callsite(llvm::AttributePlace::Function, result);
} else {
if options.contains(InlineAsmOptions::NOMEM) {
llvm::Attribute::InaccessibleMemOnly
.apply_callsite(llvm::AttributePlace::Function, result);
} 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

View File

@ -900,7 +900,7 @@ impl ThinLTOKeysMap {
let file = File::open(path)?;
for line in io::BufReader::new(file).lines() {
let line = line?;
let mut split = line.split(" ");
let mut split = line.split(' ');
let module = split.next().unwrap();
let key = split.next().unwrap();
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 float_width = self.cx.float_width(src_ty);
let int_width = self.cx.int_width(dest_ty);
match (int_width, float_width) {
(32, 32) | (32, 64) | (64, 32) | (64, 64) => true,
_ => false,
}
matches!((int_width, float_width), (32, 32) | (32, 64) | (64, 32) | (64, 64))
}
fn fptoui(&mut self, val: &'ll Value, dest_ty: &'ll Type) -> &'ll Value {

View File

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

View File

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

View File

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

View File

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

View File

@ -395,7 +395,7 @@ where
V: Copy,
{
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]
@ -451,7 +451,7 @@ impl<'a, K, V> IntoIterator for &'a SsoHashMap<K, V> {
fn into_iter(self) -> Self::IntoIter {
match self {
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 {
match self {
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 => {
let mut targets =
rustc_target::spec::TARGETS.iter().copied().collect::<Vec<_>>();
targets.sort();
targets.sort_unstable();
println!("{}", targets.join("\n"));
}
Sysroot => println!("{}", sess.sysroot.display()),

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -238,9 +238,9 @@ pub fn is_whitespace(c: char) -> bool {
// 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.
match c {
// Usual ASCII suspects
| '\u{0009}' // \t
matches!(
c,
'\u{0009}' // \t
| '\u{000A}' // \n
| '\u{000B}' // vertical tab
| '\u{000C}' // form feed
@ -257,9 +257,7 @@ pub fn is_whitespace(c: char) -> bool {
// Dedicated whitespace characters from Unicode
| '\u{2028}' // LINE SEPARATOR
| '\u{2029}' // PARAGRAPH SEPARATOR
=> true,
_ => false,
}
)
}
/// True if `c` is valid as a first character of an identifier.

View File

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

View File

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

View File

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

View File

@ -250,15 +250,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
place,
ty,
);
} else if let [success, fail] = *make_target_blocks(self) {
assert_eq!(value.ty, ty);
let expect = self.literal_operand(test.span, value);
let val = Operand::Copy(place);
self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
} else {
if let [success, fail] = *make_target_blocks(self) {
assert_eq!(value.ty, ty);
let expect = self.literal_operand(test.span, value);
let val = Operand::Copy(place);
self.compare(block, success, fail, source_info, BinOp::Eq, expect, val);
} else {
bug!("`TestKind::Eq` should have two target blocks");
}
bug!("`TestKind::Eq` should have two target blocks");
}
}

View File

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

View File

@ -316,16 +316,14 @@ fn make_mirror_unadjusted<'a, 'tcx>(
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
if cx.typeck_results().is_method_call(expr) {
overloaded_operator(cx, expr, vec![arg.to_ref()])
} else {
if let hir::ExprKind::Lit(ref lit) = arg.kind {
ExprKind::Literal {
literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
user_ty: None,
const_id: None,
}
} else {
ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() }
} else if let hir::ExprKind::Lit(ref lit) = arg.kind {
ExprKind::Literal {
literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
user_ty: None,
const_id: None,
}
} else {
ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() }
}
}

View File

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

View File

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

View File

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

View File

@ -376,21 +376,19 @@ impl<'a> Parser<'a> {
format!(" {} ", kw),
Applicability::MachineApplicable,
);
} else if let Ok(snippet) = self.span_to_snippet(ident_sp) {
err.span_suggestion(
full_sp,
"if you meant to call a macro, try",
format!("{}!", snippet),
// this is the `ambiguous` conditional branch
Applicability::MaybeIncorrect,
);
} else {
if let Ok(snippet) = self.span_to_snippet(ident_sp) {
err.span_suggestion(
full_sp,
"if you meant to call a macro, try",
format!("{}!", snippet),
// this is the `ambiguous` conditional branch
Applicability::MaybeIncorrect,
);
} else {
err.help(
"if you meant to call a macro, remove the `pub` \
and add a trailing `!` after the identifier",
);
}
err.help(
"if you meant to call a macro, remove the `pub` \
and add a trailing `!` after the identifier",
);
}
Err(err)
} else if self.look_ahead(1, |t| *t == token::Lt) {
@ -982,10 +980,7 @@ impl<'a> Parser<'a> {
if token.is_keyword(kw::Move) {
return true;
}
match token.kind {
token::BinOp(token::Or) | token::OrOr => true,
_ => false,
}
matches!(token.kind, token::BinOp(token::Or) | token::OrOr)
})
} else {
false

View File

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

View File

@ -149,8 +149,10 @@ impl<'a> Parser<'a> {
/// 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.
fn recover_trailing_vert(&mut self, lo: Option<Span>) -> bool {
let is_end_ahead = self.look_ahead(1, |token| match &token.uninterpolate().kind {
token::FatArrow // e.g. `a | => 0,`.
let is_end_ahead = self.look_ahead(1, |token| {
matches!(
&token.uninterpolate().kind,
token::FatArrow // e.g. `a | => 0,`.
| token::Ident(kw::If, false) // e.g. `a | if expr`.
| token::Eq // e.g. `let a | = 0`.
| token::Semi // e.g. `let a |;`.
@ -158,8 +160,8 @@ impl<'a> Parser<'a> {
| token::Comma // e.g. `let (a |,)`.
| token::CloseDelim(token::Bracket) // e.g. `let [a | ]`.
| token::CloseDelim(token::Paren) // e.g. `let (a | )`.
| token::CloseDelim(token::Brace) => true, // e.g. `let A { f: a | }`.
_ => false,
| token::CloseDelim(token::Brace)
)
});
match (is_end_ahead, &self.token.kind) {
(true, token::BinOp(token::Or) | token::OrOr) => {
@ -766,14 +768,11 @@ impl<'a> Parser<'a> {
&& !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 )`.
&& !self.token.is_keyword(kw::In)
&& self.look_ahead(1, |t| match t.kind { // 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::DotDotDot | token::DotDotEq | token::DotDot // A range pattern.
| token::ModSep // A tuple / struct variant pattern.
| token::Not => false, // A macro expanding to a pattern.
_ => true,
})
| token::Not))
}
/// 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> {
let ident = self.parse_path_segment_ident()?;
let is_args_start = |token: &Token| match token.kind {
token::Lt
| token::BinOp(token::Shl)
| token::OpenDelim(token::Paren)
| token::LArrow => true,
_ => false,
let is_args_start = |token: &Token| {
matches!(
token.kind,
token::Lt
| token::BinOp(token::Shl)
| token::OpenDelim(token::Paren)
| token::LArrow
)
};
let check_args_start = |this: &mut Self| {
this.expected_tokens.extend_from_slice(&[

View File

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

View File

@ -612,10 +612,8 @@ where
prof_timer.finish_with_query_invocation_id(dep_node_index.into());
if unlikely!(!diagnostics.is_empty()) {
if dep_node.kind != DepKind::NULL {
tcx.store_diagnostics(dep_node_index, diagnostics);
}
if unlikely!(!diagnostics.is_empty()) && dep_node.kind != DepKind::NULL {
tcx.store_diagnostics(dep_node_index, diagnostics);
}
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 {
// If any statements are items, we need to create an anonymous module
block.stmts.iter().any(|statement| match statement.kind {
StmtKind::Item(_) | StmtKind::MacCall(_) => true,
_ => false,
})
block
.stmts
.iter()
.any(|statement| matches!(statement.kind, StmtKind::Item(_) | StmtKind::MacCall(_)))
}
// 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);
let import_suggestions = self.lookup_import_candidates(
ident,
Namespace::MacroNS,
parent_scope,
|res| match res {
Res::Def(DefKind::Macro(MacroKind::Bang), _) => true,
_ => false,
},
);
let import_suggestions =
self.lookup_import_candidates(ident, Namespace::MacroNS, parent_scope, |res| {
matches!(res, Res::Def(DefKind::Macro(MacroKind::Bang), _))
});
show_candidates(err, None, &import_suggestions, false, true);
if macro_kind == MacroKind::Derive && (ident.name == sym::Send || ident.name == sym::Sync) {
@ -1010,11 +1005,8 @@ impl<'a> Resolver<'a> {
fn binding_description(&self, b: &NameBinding<'_>, ident: Ident, from_prelude: bool) -> String {
let res = b.res();
if b.span.is_dummy() {
let add_built_in = match b.res() {
// These already contain the "built-in" prefix or look bad with it.
Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod => false,
_ => true,
};
let add_built_in =
!matches!(b.res(), Res::NonMacroAttr(..) | Res::PrimTy(..) | Res::ToolMod);
let (built_in, from) = if from_prelude {
("", " from prelude")
} else if b.is_extern_crate()
@ -1610,10 +1602,7 @@ fn find_span_immediately_after_crate_name(
if *c == ':' {
num_colons += 1;
}
match c {
':' if num_colons == 2 => false,
_ => true,
}
!matches!(c, ':' if num_colons == 2)
});
// Find everything after the second colon.. `foo::{baz, makro};`
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> {
pub fn is_glob(&self) -> bool {
match self.kind {
ImportKind::Glob { .. } => true,
_ => false,
}
matches!(self.kind, ImportKind::Glob { .. })
}
pub fn is_nested(&self) -> bool {
@ -898,12 +895,10 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
let msg = "inconsistent resolution for an import";
self.r.session.span_err(import.span, msg);
}
} else {
if self.r.privacy_errors.is_empty() {
let msg = "cannot determine resolution for the import";
let msg_note = "import resolution is stuck, try simplifying other imports";
self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
}
} else if self.r.privacy_errors.is_empty() {
let msg = "cannot determine resolution for the import";
let msg_note = "import resolution is stuck, try simplifying other imports";
self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
}
module
@ -1044,19 +1039,14 @@ impl<'a, 'b> ImportResolver<'a, 'b> {
if res != initial_res && this.ambiguity_errors.is_empty() {
span_bug!(import.span, "inconsistent resolution for an import");
}
} else {
if res != Res::Err
&& this.ambiguity_errors.is_empty()
&& this.privacy_errors.is_empty()
{
let msg = "cannot determine resolution for the import";
let msg_note =
"import resolution is stuck, try simplifying other imports";
this.session
.struct_span_err(import.span, msg)
.note(msg_note)
.emit();
}
} else if res != Res::Err
&& this.ambiguity_errors.is_empty()
&& this.privacy_errors.is_empty()
{
let msg = "cannot determine resolution for the import";
let msg_note =
"import resolution is stuck, try simplifying other imports";
this.session.struct_span_err(import.span, msg).note(msg_note).emit();
}
}
Err(..) => {

View File

@ -257,16 +257,12 @@ impl<'a> PathSource<'a> {
}
fn is_call(self) -> bool {
match self {
PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })) => true,
_ => false,
}
matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
}
crate fn is_expected(self, res: Res) -> bool {
match self {
PathSource::Type => match res {
Res::Def(
PathSource::Type => matches!(res, Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Enum
@ -280,19 +276,12 @@ impl<'a> PathSource<'a> {
_,
)
| Res::PrimTy(..)
| Res::SelfTy(..) => true,
_ => false,
},
PathSource::Trait(AliasPossibility::No) => match res {
Res::Def(DefKind::Trait, _) => true,
_ => false,
},
PathSource::Trait(AliasPossibility::Maybe) => match res {
Res::Def(DefKind::Trait | DefKind::TraitAlias, _) => true,
_ => false,
},
PathSource::Expr(..) => match res {
Res::Def(
| Res::SelfTy(..)),
PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
PathSource::Trait(AliasPossibility::Maybe) => {
matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
}
PathSource::Expr(..) => matches!(res, Res::Def(
DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
| DefKind::Const
| DefKind::Static
@ -303,23 +292,16 @@ impl<'a> PathSource<'a> {
_,
)
| Res::Local(..)
| Res::SelfCtor(..) => true,
_ => false,
},
PathSource::Pat => match res {
Res::Def(
| Res::SelfCtor(..)),
PathSource::Pat => matches!(res, Res::Def(
DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst,
_,
)
| Res::SelfCtor(..) => true,
_ => false,
},
PathSource::TupleStruct(..) => match res {
Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..) => true,
_ => false,
},
PathSource::Struct => match res {
Res::Def(
| Res::SelfCtor(..)),
PathSource::TupleStruct(..) => {
matches!(res, Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::SelfCtor(..))
}
PathSource::Struct => matches!(res, Res::Def(
DefKind::Struct
| DefKind::Union
| DefKind::Variant
@ -327,9 +309,7 @@ impl<'a> PathSource<'a> {
| DefKind::AssocTy,
_,
)
| Res::SelfTy(..) => true,
_ => false,
},
| Res::SelfTy(..)),
PathSource::TraitItem(ns) => match res {
Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => 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 {
match self.r.partial_res_map.get(&nid).map(|res| res.base_res()) {
Some(Res::Local(..)) => true,
_ => false,
}
matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..)))
}
/// 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,
}
}
let followed_by_brace = match sm.span_to_snippet(sp) {
Ok(ref snippet) if snippet == "{" => true,
_ => false,
};
let followed_by_brace = matches!(sm.span_to_snippet(sp), Ok(ref snippet) if snippet == "{");
// In case this could be a struct literal that needs to be surrounded
// by parentheses, find the appropriate span.
let mut i = 0;
@ -1788,12 +1785,11 @@ impl<'tcx> LifetimeContext<'_, 'tcx> {
}
msg = "consider introducing a named lifetime parameter".to_string();
should_break = true;
if let Some(param) = generics.params.iter().find(|p| match p.kind {
hir::GenericParamKind::Type {
if let Some(param) = generics.params.iter().find(|p| {
!matches!(p.kind, hir::GenericParamKind::Type {
synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
..
} => false,
_ => true,
})
}) {
(param.span.shrink_to_lo(), "'a, ".to_string())
} 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.
/// 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 {
match *node {
hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) => true,
_ => false,
}
matches!(*node, hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..))
}
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".
// This is not true for other kinds of items.x
let track_lifetime_uses = match item.kind {
hir::ItemKind::Impl { .. } => true,
_ => false,
};
let track_lifetime_uses = matches!(item.kind, hir::ItemKind::Impl { .. });
// These kinds of items have only early-bound lifetime parameters.
let mut index = if sub_items_have_self_param(&item.kind) {
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);
if !trait_ref_hack
|| trait_ref.bound_generic_params.iter().any(|param| match param.kind {
GenericParamKind::Lifetime { .. } => true,
_ => false,
})
|| trait_ref
.bound_generic_params
.iter()
.any(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
{
if trait_ref_hack {
struct_span_err!(
@ -1384,18 +1378,16 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
}
if in_band {
Some(param.span)
} else if generics.params.len() == 1 {
// if sole lifetime, remove the entire `<>` brackets
Some(generics.span)
} else {
if generics.params.len() == 1 {
// if sole lifetime, remove the entire `<>` brackets
Some(generics.span)
// if removing within `<>` brackets, we also want to
// delete a leading or trailing comma as appropriate
if i >= generics.params.len() - 1 {
Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
} else {
// if removing within `<>` brackets, we also want to
// delete a leading or trailing comma as appropriate
if i >= generics.params.len() - 1 {
Some(generics.params[i - 1].span.shrink_to_hi().to(param.span))
} else {
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 {
@ -2047,10 +2039,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> {
//
// This is intended to leave room for us to implement the
// correct behavior in the future.
let has_lifetime_parameter = generic_args.args.iter().any(|arg| match arg {
GenericArg::Lifetime(_) => true,
_ => false,
});
let has_lifetime_parameter =
generic_args.args.iter().any(|arg| matches!(arg, GenericArg::Lifetime(_)));
// Resolve lifetimes found in the type `XX` from `Item = XX` bindings.
for b in generic_args.bindings {

View File

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

View File

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

View File

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

View File

@ -326,10 +326,8 @@ impl Printer<'tcx> for SymbolPrinter<'tcx> {
) -> Result<Self::Path, Self::Error> {
self = print_prefix(self)?;
let args = args.iter().cloned().filter(|arg| match arg.unpack() {
GenericArgKind::Lifetime(_) => false,
_ => true,
});
let args =
args.iter().cloned().filter(|arg| !matches!(arg.unpack(), GenericArgKind::Lifetime(_)));
if args.clone().next().is_some() {
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);
}
let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
match tcx.hir().get(hir_id) {
Node::ForeignItem(_) => true,
_ => false,
}
matches!(tcx.hir().get(hir_id), Node::ForeignItem(_))
} else {
tcx.is_foreign_item(def_id)
};
@ -200,15 +197,14 @@ fn compute_symbol_name(
// show up in the `wasm-import-name` custom attribute in LLVM IR.
//
// [1]: https://bugs.llvm.org/show_bug.cgi?id=44316
if is_foreign {
if tcx.sess.target.arch != "wasm32"
|| !tcx.wasm_import_module_map(def_id.krate).contains_key(&def_id)
{
if let Some(name) = attrs.link_name {
return name.to_string();
}
return tcx.item_name(def_id).to_string();
if is_foreign
&& (tcx.sess.target.arch != "wasm32"
|| !tcx.wasm_import_module_map(def_id.krate).contains_key(&def_id))
{
if let Some(name) = attrs.link_name {
return name.to_string();
}
return tcx.item_name(def_id).to_string();
}
if let Some(name) = attrs.export_name {
@ -234,10 +230,7 @@ fn compute_symbol_name(
// codegen units) then this symbol may become an exported (but hidden
// visibility) symbol. This means that multiple crates may do the same
// and we want to be sure to avoid any symbol conflicts here.
match MonoItem::Fn(instance).instantiation_mode(tcx) {
InstantiationMode::GloballyShared { may_conflict: true } => true,
_ => false,
};
matches!(MonoItem::Fn(instance).instantiation_mode(tcx), InstantiationMode::GloballyShared { may_conflict: true });
let instantiating_crate =
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 {
match self.mode {
PassMode::Indirect(..) => true,
_ => false,
}
matches!(self.mode, PassMode::Indirect(..))
}
pub fn is_sized_indirect(&self) -> bool {
match self.mode {
PassMode::Indirect(_, None) => true,
_ => false,
}
matches!(self.mode, PassMode::Indirect(_, None))
}
pub fn is_unsized_indirect(&self) -> bool {
match self.mode {
PassMode::Indirect(_, Some(_)) => true,
_ => false,
}
matches!(self.mode, PassMode::Indirect(_, Some(_)))
}
pub fn is_ignore(&self) -> bool {
match self.mode {
PassMode::Ignore => true,
_ => false,
}
matches!(self.mode, PassMode::Ignore)
}
}

View File

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

View File

@ -24,10 +24,8 @@ where
C: LayoutOf<Ty = Ty, TyAndLayout = TyAndLayout<'a, Ty>> + HasDataLayout,
{
ret.extend_integer_width_to(32);
if ret.layout.is_aggregate() {
if !unwrap_trivial_aggregate(cx, ret) {
ret.make_indirect();
}
if ret.layout.is_aggregate() && !unwrap_trivial_aggregate(cx, ret) {
ret.make_indirect();
}
}
@ -37,10 +35,8 @@ where
C: LayoutOf<Ty = Ty, TyAndLayout = TyAndLayout<'a, Ty>> + HasDataLayout,
{
arg.extend_integer_width_to(32);
if arg.layout.is_aggregate() {
if !unwrap_trivial_aggregate(cx, arg) {
arg.make_indirect_byval();
}
if arg.layout.is_aggregate() && !unwrap_trivial_aggregate(cx, arg) {
arg.make_indirect_byval();
}
}

View File

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

View File

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