Rollup merge of #130235 - compiler-errors:nested-if, r=michaelwoerister

Simplify some nested `if` statements

Applies some but not all instances of `clippy::collapsible_if`. Some ended up looking worse afterwards, though, so I left those out. Also applies instances of `clippy::collapsible_else_if`

Review with whitespace disabled please.
This commit is contained in:
Stuart Cook 2024-09-12 20:37:16 +10:00 committed by GitHub
commit 3ba12756d3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
61 changed files with 563 additions and 671 deletions

View File

@ -45,8 +45,7 @@ pub fn entry_point_type(
EntryPointType::Start EntryPointType::Start
} else if attr::contains_name(attrs, sym::rustc_main) { } else if attr::contains_name(attrs, sym::rustc_main) {
EntryPointType::RustcMainAttr EntryPointType::RustcMainAttr
} else { } else if let Some(name) = name
if let Some(name) = name
&& name == sym::main && name == sym::main
{ {
if at_root { if at_root {
@ -59,4 +58,3 @@ pub fn entry_point_type(
EntryPointType::None EntryPointType::None
} }
} }
}

View File

@ -78,8 +78,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
// Make sure that the DepNode of some node coincides with the HirId // Make sure that the DepNode of some node coincides with the HirId
// owner of that node. // owner of that node.
if cfg!(debug_assertions) { if cfg!(debug_assertions) && hir_id.owner != self.owner {
if hir_id.owner != self.owner {
span_bug!( span_bug!(
span, span,
"inconsistent HirId at `{:?}` for `{:?}`: \ "inconsistent HirId at `{:?}` for `{:?}`: \
@ -98,7 +97,6 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
hir_id.owner, hir_id.owner,
) )
} }
}
self.nodes[hir_id.local_id] = ParentedNode { parent: self.parent_node, node }; self.nodes[hir_id.local_id] = ParentedNode { parent: self.parent_node, node };
} }

View File

@ -628,14 +628,12 @@ impl<'hir> LoweringContext<'_, 'hir> {
.map_or(Const::No, |attr| Const::Yes(attr.span)), .map_or(Const::No, |attr| Const::Yes(attr.span)),
_ => Const::No, _ => Const::No,
} }
} else { } else if self.tcx.is_const_trait(def_id) {
if self.tcx.is_const_trait(def_id) {
// FIXME(effects) span // FIXME(effects) span
Const::Yes(self.tcx.def_ident_span(def_id).unwrap()) Const::Yes(self.tcx.def_ident_span(def_id).unwrap())
} else { } else {
Const::No Const::No
} }
}
} else { } else {
Const::No Const::No
} }

View File

@ -447,15 +447,15 @@ impl<'a> AstValidator<'a> {
fn check_item_safety(&self, span: Span, safety: Safety) { fn check_item_safety(&self, span: Span, safety: Safety) {
match self.extern_mod_safety { match self.extern_mod_safety {
Some(extern_safety) => { Some(extern_safety) => {
if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_)) { if matches!(safety, Safety::Unsafe(_) | Safety::Safe(_))
if extern_safety == Safety::Default { && extern_safety == Safety::Default
{
self.dcx().emit_err(errors::InvalidSafetyOnExtern { self.dcx().emit_err(errors::InvalidSafetyOnExtern {
item_span: span, item_span: span,
block: Some(self.current_extern_span().shrink_to_lo()), block: Some(self.current_extern_span().shrink_to_lo()),
}); });
} }
} }
}
None => { None => {
if matches!(safety, Safety::Safe(_)) { if matches!(safety, Safety::Safe(_)) {
self.dcx().emit_err(errors::InvalidSafetyOnItem { span }); self.dcx().emit_err(errors::InvalidSafetyOnItem { span });

View File

@ -2574,8 +2574,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
} }
impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> { impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) { fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
if e.span.contains(self.capture_span) { if e.span.contains(self.capture_span)
if let hir::ExprKind::Closure(&hir::Closure { && let hir::ExprKind::Closure(&hir::Closure {
kind: hir::ClosureKind::Closure, kind: hir::ClosureKind::Closure,
body, body,
fn_arg_span, fn_arg_span,
@ -2593,15 +2593,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
self.visit_expr(body); self.visit_expr(body);
self.in_closure = false; self.in_closure = false;
} }
} if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e
if let hir::Expr { kind: hir::ExprKind::Path(path), .. } = e { && let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
if let hir::QPath::Resolved(_, hir::Path { segments: [seg], .. }) = path
&& seg.ident.name == kw::SelfLower && seg.ident.name == kw::SelfLower
&& self.in_closure && self.in_closure
{ {
self.closure_change_spans.push(e.span); self.closure_change_spans.push(e.span);
} }
}
hir::intravisit::walk_expr(self, e); hir::intravisit::walk_expr(self, e);
} }
@ -2609,8 +2607,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } = if let hir::Pat { kind: hir::PatKind::Binding(_, hir_id, _ident, _), .. } =
local.pat local.pat
&& let Some(init) = local.init && let Some(init) = local.init
{ && let hir::Expr {
if let hir::Expr {
kind: kind:
hir::ExprKind::Closure(&hir::Closure { hir::ExprKind::Closure(&hir::Closure {
kind: hir::ClosureKind::Closure, kind: hir::ClosureKind::Closure,
@ -2622,7 +2619,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
{ {
self.closure_local_id = Some(*hir_id); self.closure_local_id = Some(*hir_id);
} }
}
hir::intravisit::walk_local(self, local); hir::intravisit::walk_local(self, local);
} }

View File

@ -2069,13 +2069,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> {
// no move out from an earlier location) then this is an attempt at initialization // no move out from an earlier location) then this is an attempt at initialization
// of the union - we should error in that case. // of the union - we should error in that case.
let tcx = this.infcx.tcx; let tcx = this.infcx.tcx;
if base.ty(this.body(), tcx).ty.is_union() { if base.ty(this.body(), tcx).ty.is_union()
if this.move_data.path_map[mpi].iter().any(|moi| { && this.move_data.path_map[mpi].iter().any(|moi| {
this.move_data.moves[*moi].source.is_predecessor_of(location, this.body) this.move_data.moves[*moi].source.is_predecessor_of(location, this.body)
}) { })
{
return; return;
} }
}
this.report_use_of_moved_or_uninitialized( this.report_use_of_moved_or_uninitialized(
location, location,

View File

@ -118,11 +118,9 @@ impl LivenessValues {
debug!("LivenessValues::add_location(region={:?}, location={:?})", region, location); debug!("LivenessValues::add_location(region={:?}, location={:?})", region, location);
if let Some(points) = &mut self.points { if let Some(points) = &mut self.points {
points.insert(region, point); points.insert(region, point);
} else { } else if self.elements.point_in_range(point) {
if self.elements.point_in_range(point) {
self.live_regions.as_mut().unwrap().insert(region); self.live_regions.as_mut().unwrap().insert(region);
} }
}
// When available, record the loans flowing into this region as live at the given point. // When available, record the loans flowing into this region as live at the given point.
if let Some(loans) = self.loans.as_mut() { if let Some(loans) = self.loans.as_mut() {
@ -137,11 +135,9 @@ impl LivenessValues {
debug!("LivenessValues::add_points(region={:?}, points={:?})", region, points); debug!("LivenessValues::add_points(region={:?}, points={:?})", region, points);
if let Some(this) = &mut self.points { if let Some(this) = &mut self.points {
this.union_row(region, points); this.union_row(region, points);
} else { } else if points.iter().any(|point| self.elements.point_in_range(point)) {
if points.iter().any(|point| self.elements.point_in_range(point)) {
self.live_regions.as_mut().unwrap().insert(region); self.live_regions.as_mut().unwrap().insert(region);
} }
}
// When available, record the loans flowing into this region as live at the given points. // When available, record the loans flowing into this region as live at the given points.
if let Some(loans) = self.loans.as_mut() { if let Some(loans) = self.loans.as_mut() {

View File

@ -353,13 +353,13 @@ impl<'a, 'typeck, 'b, 'tcx> LivenessResults<'a, 'typeck, 'b, 'tcx> {
let location = self.cx.elements.to_location(drop_point); let location = self.cx.elements.to_location(drop_point);
debug_assert_eq!(self.cx.body.terminator_loc(location.block), location,); debug_assert_eq!(self.cx.body.terminator_loc(location.block), location,);
if self.cx.initialized_at_terminator(location.block, mpi) { if self.cx.initialized_at_terminator(location.block, mpi)
if self.drop_live_at.insert(drop_point) { && self.drop_live_at.insert(drop_point)
{
self.drop_locations.push(location); self.drop_locations.push(location);
self.stack.push(drop_point); self.stack.push(drop_point);
} }
} }
}
debug!("compute_drop_live_points_for: drop_locations={:?}", self.drop_locations); debug!("compute_drop_live_points_for: drop_locations={:?}", self.drop_locations);

View File

@ -235,15 +235,13 @@ pub fn parse_asm_args<'a>(
continue; continue;
} }
args.named_args.insert(name, slot); args.named_args.insert(name, slot);
} else { } else if !args.named_args.is_empty() || !args.reg_args.is_empty() {
if !args.named_args.is_empty() || !args.reg_args.is_empty() {
let named = args.named_args.values().map(|p| args.operands[*p].1).collect(); let named = args.named_args.values().map(|p| args.operands[*p].1).collect();
let explicit = args.reg_args.iter().map(|p| args.operands[p].1).collect(); let explicit = args.reg_args.iter().map(|p| args.operands[p].1).collect();
dcx.emit_err(errors::AsmPositionalAfter { span, named, explicit }); dcx.emit_err(errors::AsmPositionalAfter { span, named, explicit });
} }
} }
}
if args.options.contains(ast::InlineAsmOptions::NOMEM) if args.options.contains(ast::InlineAsmOptions::NOMEM)
&& args.options.contains(ast::InlineAsmOptions::READONLY) && args.options.contains(ast::InlineAsmOptions::READONLY)

View File

@ -92,13 +92,11 @@ fn prepare_lto(
dcx.emit_err(LtoDylib); dcx.emit_err(LtoDylib);
return Err(FatalError); return Err(FatalError);
} }
} else if *crate_type == CrateType::ProcMacro { } else if *crate_type == CrateType::ProcMacro && !cgcx.opts.unstable_opts.dylib_lto {
if !cgcx.opts.unstable_opts.dylib_lto {
dcx.emit_err(LtoProcMacro); dcx.emit_err(LtoProcMacro);
return Err(FatalError); return Err(FatalError);
} }
} }
}
if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto { if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto {
dcx.emit_err(DynamicLinkingWithLTO); dcx.emit_err(DynamicLinkingWithLTO);

View File

@ -281,14 +281,12 @@ pub fn each_linked_rlib(
let used_crate_source = &info.used_crate_source[&cnum]; let used_crate_source = &info.used_crate_source[&cnum];
if let Some((path, _)) = &used_crate_source.rlib { if let Some((path, _)) = &used_crate_source.rlib {
f(cnum, path); f(cnum, path);
} else { } else if used_crate_source.rmeta.is_some() {
if used_crate_source.rmeta.is_some() {
return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name }); return Err(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else { } else {
return Err(errors::LinkRlibError::NotFound { crate_name }); return Err(errors::LinkRlibError::NotFound { crate_name });
} }
} }
}
Ok(()) Ok(())
} }
@ -628,14 +626,12 @@ fn link_staticlib(
let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum]; let used_crate_source = &codegen_results.crate_info.used_crate_source[&cnum];
if let Some((path, _)) = &used_crate_source.dylib { if let Some((path, _)) = &used_crate_source.dylib {
all_rust_dylibs.push(&**path); all_rust_dylibs.push(&**path);
} else { } else if used_crate_source.rmeta.is_some() {
if used_crate_source.rmeta.is_some() {
sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name }); sess.dcx().emit_fatal(errors::LinkRlibError::OnlyRmetaFound { crate_name });
} else { } else {
sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name }); sess.dcx().emit_fatal(errors::LinkRlibError::NotFound { crate_name });
} }
} }
}
all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries); all_native_libs.extend_from_slice(&codegen_results.crate_info.used_libraries);
@ -1972,11 +1968,9 @@ fn add_late_link_args(
if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) { if let Some(args) = sess.target.late_link_args_dynamic.get(&flavor) {
cmd.verbatim_args(args.iter().map(Deref::deref)); cmd.verbatim_args(args.iter().map(Deref::deref));
} }
} else { } else if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
if let Some(args) = sess.target.late_link_args_static.get(&flavor) {
cmd.verbatim_args(args.iter().map(Deref::deref)); cmd.verbatim_args(args.iter().map(Deref::deref));
} }
}
if let Some(args) = sess.target.late_link_args.get(&flavor) { if let Some(args) = sess.target.late_link_args.get(&flavor) {
cmd.verbatim_args(args.iter().map(Deref::deref)); cmd.verbatim_args(args.iter().map(Deref::deref));
} }
@ -2635,12 +2629,10 @@ fn add_native_libs_from_crate(
if link_static { if link_static {
cmd.link_staticlib_by_name(name, verbatim, false); cmd.link_staticlib_by_name(name, verbatim, false);
} }
} else { } else if link_dynamic {
if link_dynamic {
cmd.link_dylib_by_name(name, verbatim, true); cmd.link_dylib_by_name(name, verbatim, true);
} }
} }
}
NativeLibKind::Framework { as_needed } => { NativeLibKind::Framework { as_needed } => {
if link_dynamic { if link_dynamic {
cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true)) cmd.link_framework_by_name(name, verbatim, as_needed.unwrap_or(true))

View File

@ -791,8 +791,7 @@ impl<'a> Linker for GccLinker<'a> {
self.link_arg("-exported_symbols_list").link_arg(path); self.link_arg("-exported_symbols_list").link_arg(path);
} else if self.sess.target.is_like_solaris { } else if self.sess.target.is_like_solaris {
self.link_arg("-M").link_arg(path); self.link_arg("-M").link_arg(path);
} else { } else if is_windows {
if is_windows {
self.link_arg(path); self.link_arg(path);
} else { } else {
let mut arg = OsString::from("--version-script="); let mut arg = OsString::from("--version-script=");
@ -800,7 +799,6 @@ impl<'a> Linker for GccLinker<'a> {
self.link_arg(arg).link_arg("--no-undefined-version"); self.link_arg(arg).link_arg("--no-undefined-version");
} }
} }
}
fn subsystem(&mut self, subsystem: &str) { fn subsystem(&mut self, subsystem: &str) {
self.link_args(&["--subsystem", subsystem]); self.link_args(&["--subsystem", subsystem]);

View File

@ -617,8 +617,8 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
// purpose functions as they wouldn't have the right target features // purpose functions as they wouldn't have the right target features
// enabled. For that reason we also forbid #[inline(always)] as it can't be // enabled. For that reason we also forbid #[inline(always)] as it can't be
// respected. // respected.
if !codegen_fn_attrs.target_features.is_empty() { if !codegen_fn_attrs.target_features.is_empty() && codegen_fn_attrs.inline == InlineAttr::Always
if codegen_fn_attrs.inline == InlineAttr::Always { {
if let Some(span) = inline_span { if let Some(span) = inline_span {
tcx.dcx().span_err( tcx.dcx().span_err(
span, span,
@ -627,10 +627,8 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
); );
} }
} }
}
if !codegen_fn_attrs.no_sanitize.is_empty() { if !codegen_fn_attrs.no_sanitize.is_empty() && codegen_fn_attrs.inline == InlineAttr::Always {
if codegen_fn_attrs.inline == InlineAttr::Always {
if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) { if let (Some(no_sanitize_span), Some(inline_span)) = (no_sanitize_span, inline_span) {
let hir_id = tcx.local_def_id_to_hir_id(did); let hir_id = tcx.local_def_id_to_hir_id(did);
tcx.node_span_lint( tcx.node_span_lint(
@ -644,7 +642,6 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
) )
} }
} }
}
if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) { if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
codegen_fn_attrs.inline = InlineAttr::Never; codegen_fn_attrs.inline = InlineAttr::Never;

View File

@ -236,15 +236,13 @@ fn push_debuginfo_type_name<'tcx>(
let has_enclosing_parens = if cpp_like_debuginfo { let has_enclosing_parens = if cpp_like_debuginfo {
output.push_str("dyn$<"); output.push_str("dyn$<");
false false
} else { } else if trait_data.len() > 1 && auto_traits.len() != 0 {
if trait_data.len() > 1 && auto_traits.len() != 0 {
// We need enclosing parens because there is more than one trait // We need enclosing parens because there is more than one trait
output.push_str("(dyn "); output.push_str("(dyn ");
true true
} else { } else {
output.push_str("dyn "); output.push_str("dyn ");
false false
}
}; };
if let Some(principal) = trait_data.principal() { if let Some(principal) = trait_data.principal() {

View File

@ -16,7 +16,7 @@ use rustc_span::Span;
use rustc_target::abi::call::FnAbi; use rustc_target::abi::call::FnAbi;
use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout}; use rustc_target::abi::{Align, HasDataLayout, Size, TargetDataLayout};
use rustc_trait_selection::traits::ObligationCtxt; use rustc_trait_selection::traits::ObligationCtxt;
use tracing::{debug, trace}; use tracing::{debug, instrument, trace};
use super::{ use super::{
err_inval, throw_inval, throw_ub, throw_ub_custom, Frame, FrameInfo, GlobalId, InterpErrorInfo, err_inval, throw_inval, throw_ub, throw_ub_custom, Frame, FrameInfo, GlobalId, InterpErrorInfo,
@ -315,6 +315,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
/// Check if the two things are equal in the current param_env, using an infctx to get proper /// Check if the two things are equal in the current param_env, using an infctx to get proper
/// equality checks. /// equality checks.
#[instrument(level = "trace", skip(self), ret)]
pub(super) fn eq_in_param_env<T>(&self, a: T, b: T) -> bool pub(super) fn eq_in_param_env<T>(&self, a: T, b: T) -> bool
where where
T: PartialEq + TypeFoldable<TyCtxt<'tcx>> + ToTrace<'tcx>, T: PartialEq + TypeFoldable<TyCtxt<'tcx>> + ToTrace<'tcx>,
@ -330,15 +331,22 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> {
// equate the two trait refs after normalization // equate the two trait refs after normalization
let a = ocx.normalize(&cause, self.param_env, a); let a = ocx.normalize(&cause, self.param_env, a);
let b = ocx.normalize(&cause, self.param_env, b); let b = ocx.normalize(&cause, self.param_env, b);
if ocx.eq(&cause, self.param_env, a, b).is_ok() {
if ocx.select_all_or_error().is_empty() { if let Err(terr) = ocx.eq(&cause, self.param_env, a, b) {
// All good. trace!(?terr);
return true;
}
}
return false; return false;
} }
let errors = ocx.select_all_or_error();
if !errors.is_empty() {
trace!(?errors);
return false;
}
// All good.
true
}
/// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a /// Walks up the callstack from the intrinsic's callsite, searching for the first callsite in a
/// frame which is not `#[track_caller]`. This matches the `caller_location` intrinsic, /// frame which is not `#[track_caller]`. This matches the `caller_location` intrinsic,
/// and is primarily intended for the panic machinery. /// and is primarily intended for the panic machinery.

View File

@ -222,11 +222,9 @@ impl<'tcx> PrintExtra<'tcx> {
} }
pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) { pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
if ppm.needs_analysis() { if ppm.needs_analysis() && ex.tcx().analysis(()).is_err() {
if ex.tcx().analysis(()).is_err() {
FatalError.raise(); FatalError.raise();
} }
}
let (src, src_name) = get_source(sess); let (src, src_name) = get_source(sess);

View File

@ -1151,8 +1151,7 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
"type has conflicting packed and align representation hints" "type has conflicting packed and align representation hints"
) )
.emit(); .emit();
} else { } else if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
if let Some(def_spans) = check_packed_inner(tcx, def.did(), &mut vec![]) {
let mut err = struct_span_code_err!( let mut err = struct_span_code_err!(
tcx.dcx(), tcx.dcx(),
sp, sp,
@ -1189,7 +1188,6 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) {
} }
} }
} }
}
pub(super) fn check_packed_inner( pub(super) fn check_packed_inner(
tcx: TyCtxt<'_>, tcx: TyCtxt<'_>,

View File

@ -186,8 +186,7 @@ fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: LocalDefId) {
if let Ok(alloc) = tcx.eval_static_initializer(id.to_def_id()) if let Ok(alloc) = tcx.eval_static_initializer(id.to_def_id())
&& alloc.inner().provenance().ptrs().len() != 0 && alloc.inner().provenance().ptrs().len() != 0
{ && attrs
if attrs
.link_section .link_section
.map(|link_section| !link_section.as_str().starts_with(".init_array")) .map(|link_section| !link_section.as_str().starts_with(".init_array"))
.unwrap() .unwrap()
@ -198,7 +197,6 @@ fn maybe_check_static_with_link_section(tcx: TyCtxt<'_>, id: LocalDefId) {
tcx.dcx().span_err(tcx.def_span(id), msg); tcx.dcx().span_err(tcx.def_span(id), msg);
} }
} }
}
fn report_forbidden_specialization(tcx: TyCtxt<'_>, impl_item: DefId, parent_impl: DefId) { fn report_forbidden_specialization(tcx: TyCtxt<'_>, impl_item: DefId, parent_impl: DefId) {
let span = tcx.def_span(impl_item); let span = tcx.def_span(impl_item);

View File

@ -53,8 +53,7 @@ fn enforce_trait_manually_implementable(
) -> Result<(), ErrorGuaranteed> { ) -> Result<(), ErrorGuaranteed> {
let impl_header_span = tcx.def_span(impl_def_id); let impl_header_span = tcx.def_span(impl_def_id);
if tcx.is_lang_item(trait_def_id, LangItem::Freeze) { if tcx.is_lang_item(trait_def_id, LangItem::Freeze) && !tcx.features().freeze_impls {
if !tcx.features().freeze_impls {
feature_err( feature_err(
&tcx.sess, &tcx.sess,
sym::freeze_impls, sym::freeze_impls,
@ -64,7 +63,6 @@ fn enforce_trait_manually_implementable(
.with_span_label(impl_header_span, format!("impl of `Freeze` not allowed")) .with_span_label(impl_header_span, format!("impl of `Freeze` not allowed"))
.emit(); .emit();
} }
}
// Disallow *all* explicit impls of traits marked `#[rustc_deny_explicit_impl]` // Disallow *all* explicit impls of traits marked `#[rustc_deny_explicit_impl]`
if trait_def.deny_explicit_impl { if trait_def.deny_explicit_impl {

View File

@ -381,8 +381,7 @@ pub(super) fn find_opaque_ty_constraints_for_rpit<'tcx>(
} }
mir_opaque_ty.ty mir_opaque_ty.ty
} else { } else if let Some(guar) = tables.tainted_by_errors {
if let Some(guar) = tables.tainted_by_errors {
// Some error in the owner fn prevented us from populating // Some error in the owner fn prevented us from populating
// the `concrete_opaque_types` table. // the `concrete_opaque_types` table.
Ty::new_error(tcx, guar) Ty::new_error(tcx, guar)
@ -401,7 +400,6 @@ pub(super) fn find_opaque_ty_constraints_for_rpit<'tcx>(
} }
} }
} }
}
struct RpitConstraintChecker<'tcx> { struct RpitConstraintChecker<'tcx> {
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,

View File

@ -827,8 +827,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
if num_generic_args_supplied_to_trait + num_assoc_fn_excess_args if num_generic_args_supplied_to_trait + num_assoc_fn_excess_args
== num_trait_generics_except_self == num_trait_generics_except_self
{ && let Some(span) = self.gen_args.span_ext()
if let Some(span) = self.gen_args.span_ext()
&& let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
{ {
let sugg = vec![ let sugg = vec![
@ -843,7 +842,6 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
} }
} }
} }
}
fn suggest_moving_args_from_assoc_fn_to_trait_for_method_call( fn suggest_moving_args_from_assoc_fn_to_trait_for_method_call(
&self, &self,

View File

@ -562,8 +562,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
tcx.const_param_default(param.def_id) tcx.const_param_default(param.def_id)
.instantiate(tcx, preceding_args) .instantiate(tcx, preceding_args)
.into() .into()
} else { } else if infer_args {
if infer_args {
self.lowerer.ct_infer(Some(param), self.span).into() self.lowerer.ct_infer(Some(param), self.span).into()
} else { } else {
// We've already errored above about the mismatch. // We've already errored above about the mismatch.
@ -573,7 +572,6 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
} }
} }
} }
}
if let ty::BoundConstness::Const | ty::BoundConstness::ConstIfConst = constness if let ty::BoundConstness::Const | ty::BoundConstness::ConstIfConst = constness
&& generics.has_self && generics.has_self
&& !tcx.is_const_trait(def_id) && !tcx.is_const_trait(def_id)

View File

@ -732,13 +732,12 @@ impl<'a, 'tcx> CastCheck<'tcx> {
} }
_ => return Err(CastError::NonScalar), _ => return Err(CastError::NonScalar),
}; };
if let ty::Adt(adt_def, _) = *self.expr_ty.kind() { if let ty::Adt(adt_def, _) = *self.expr_ty.kind()
if adt_def.did().krate != LOCAL_CRATE { && adt_def.did().krate != LOCAL_CRATE
if adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive) { && adt_def.variants().iter().any(VariantDef::is_field_list_non_exhaustive)
{
return Err(CastError::ForeignNonExhaustiveAdt); return Err(CastError::ForeignNonExhaustiveAdt);
} }
}
}
match (t_from, t_cast) { match (t_from, t_cast) {
// These types have invariants! can't cast into them. // These types have invariants! can't cast into them.
(_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar), (_, Int(CEnum) | FnPtr) => Err(CastError::NonScalar),

View File

@ -1780,8 +1780,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
} }
// Make sure the programmer specified correct number of fields. // Make sure the programmer specified correct number of fields.
if adt_kind == AdtKind::Union { if adt_kind == AdtKind::Union && hir_fields.len() != 1 {
if hir_fields.len() != 1 {
struct_span_code_err!( struct_span_code_err!(
self.dcx(), self.dcx(),
span, span,
@ -1790,7 +1789,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
) )
.emit(); .emit();
} }
}
// If check_expr_struct_fields hit an error, do not attempt to populate // If check_expr_struct_fields hit an error, do not attempt to populate
// the fields with the base_expr. This could cause us to hit errors later // the fields with the base_expr. This could cause us to hit errors later
@ -2904,8 +2902,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
candidate_fields.iter().map(|path| format!("{unwrap}{path}")), candidate_fields.iter().map(|path| format!("{unwrap}{path}")),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} else { } else if let Some(field_name) =
if let Some(field_name) = find_best_match_for_name(&field_names, field.name, None) { find_best_match_for_name(&field_names, field.name, None)
{
err.span_suggestion_verbose( err.span_suggestion_verbose(
field.span, field.span,
"a field with a similar name exists", "a field with a similar name exists",
@ -2914,11 +2913,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
); );
} else if !field_names.is_empty() { } else if !field_names.is_empty() {
let is = if field_names.len() == 1 { " is" } else { "s are" }; let is = if field_names.len() == 1 { " is" } else { "s are" };
err.note(format!( err.note(
"available field{is}: {}", format!("available field{is}: {}", self.name_series_display(field_names),),
self.name_series_display(field_names), );
));
}
} }
} }
err err

View File

@ -158,15 +158,13 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> {
), ),
); );
} }
} else { } else if !self.fcx.tcx.features().unsized_locals {
if !self.fcx.tcx.features().unsized_locals {
self.fcx.require_type_is_sized( self.fcx.require_type_is_sized(
var_ty, var_ty,
p.span, p.span,
ObligationCauseCode::VariableType(p.hir_id), ObligationCauseCode::VariableType(p.hir_id),
); );
} }
}
debug!( debug!(
"pattern binding {} is assigned to {} with type {:?}", "pattern binding {} is assigned to {} with type {:?}",

View File

@ -1252,12 +1252,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&& suggested_bounds.contains(parent) && suggested_bounds.contains(parent)
{ {
// We don't suggest `PartialEq` when we already suggest `Eq`. // We don't suggest `PartialEq` when we already suggest `Eq`.
} else if !suggested_bounds.contains(pred) { } else if !suggested_bounds.contains(pred)
if collect_type_param_suggestions(self_ty, *pred, &p) { && collect_type_param_suggestions(self_ty, *pred, &p)
{
suggested = true; suggested = true;
suggested_bounds.insert(pred); suggested_bounds.insert(pred);
} }
}
( (
match parent_pred { match parent_pred {
None => format!("`{p}`"), None => format!("`{p}`"),
@ -1267,15 +1267,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if !suggested if !suggested
&& !suggested_bounds.contains(pred) && !suggested_bounds.contains(pred)
&& !suggested_bounds.contains(parent_pred) && !suggested_bounds.contains(parent_pred)
{ && collect_type_param_suggestions(
if collect_type_param_suggestions(
self_ty, self_ty,
*parent_pred, *parent_pred,
&p, &p,
) { )
{
suggested_bounds.insert(pred); suggested_bounds.insert(pred);
} }
}
format!("`{p}`\nwhich is required by `{parent_p}`") format!("`{p}`\nwhich is required by `{parent_p}`")
} }
}, },

View File

@ -417,14 +417,12 @@ fn check_config(tcx: TyCtxt<'_>, attr: &Attribute) -> bool {
fn expect_associated_value(tcx: TyCtxt<'_>, item: &NestedMetaItem) -> Symbol { fn expect_associated_value(tcx: TyCtxt<'_>, item: &NestedMetaItem) -> Symbol {
if let Some(value) = item.value_str() { if let Some(value) = item.value_str() {
value value
} else { } else if let Some(ident) = item.ident() {
if let Some(ident) = item.ident() {
tcx.dcx().emit_fatal(errors::AssociatedValueExpectedFor { span: item.span(), ident }); tcx.dcx().emit_fatal(errors::AssociatedValueExpectedFor { span: item.span(), ident });
} else { } else {
tcx.dcx().emit_fatal(errors::AssociatedValueExpected { span: item.span() }); tcx.dcx().emit_fatal(errors::AssociatedValueExpected { span: item.span() });
} }
} }
}
/// A visitor that collects all `#[rustc_clean]` attributes from /// A visitor that collects all `#[rustc_clean]` attributes from
/// the HIR. It is used to verify that we really ran checks for all annotated /// the HIR. It is used to verify that we really ran checks for all annotated

View File

@ -429,11 +429,9 @@ impl MissingDoc {
// Only check publicly-visible items, using the result from the privacy pass. // Only check publicly-visible items, using the result from the privacy pass.
// It's an option so the crate root can also use this function (it doesn't // It's an option so the crate root can also use this function (it doesn't
// have a `NodeId`). // have a `NodeId`).
if def_id != CRATE_DEF_ID { if def_id != CRATE_DEF_ID && !cx.effective_visibilities.is_exported(def_id) {
if !cx.effective_visibilities.is_exported(def_id) {
return; return;
} }
}
let attrs = cx.tcx.hir().attrs(cx.tcx.local_def_id_to_hir_id(def_id)); let attrs = cx.tcx.hir().attrs(cx.tcx.local_def_id_to_hir_id(def_id));
let has_doc = attrs.iter().any(has_doc); let has_doc = attrs.iter().any(has_doc);

View File

@ -444,11 +444,12 @@ impl<'tcx> TyCtxt<'tcx> {
// the `-Z force-unstable-if-unmarked` flag present (we're // the `-Z force-unstable-if-unmarked` flag present (we're
// compiling a compiler crate), then let this missing feature // compiling a compiler crate), then let this missing feature
// annotation slide. // annotation slide.
if feature == sym::rustc_private && issue == NonZero::new(27812) { if feature == sym::rustc_private
if self.sess.opts.unstable_opts.force_unstable_if_unmarked { && issue == NonZero::new(27812)
&& self.sess.opts.unstable_opts.force_unstable_if_unmarked
{
return EvalResult::Allow; return EvalResult::Allow;
} }
}
if matches!(allow_unstable, AllowUnstable::Yes) { if matches!(allow_unstable, AllowUnstable::Yes) {
return EvalResult::Allow; return EvalResult::Allow;

View File

@ -448,8 +448,7 @@ impl<Prov: Provenance, Extra, Bytes: AllocBytes> Allocation<Prov, Extra, Bytes>
bad: uninit_range, bad: uninit_range,
})) }))
})?; })?;
if !Prov::OFFSET_IS_ADDR { if !Prov::OFFSET_IS_ADDR && !self.provenance.range_empty(range, cx) {
if !self.provenance.range_empty(range, cx) {
// Find the provenance. // Find the provenance.
let (offset, _prov) = self let (offset, _prov) = self
.provenance .provenance
@ -464,7 +463,6 @@ impl<Prov: Provenance, Extra, Bytes: AllocBytes> Allocation<Prov, Extra, Bytes>
bad: AllocRange::from(start..end), bad: AllocRange::from(start..end),
}))); })));
} }
}
Ok(self.get_bytes_unchecked(range)) Ok(self.get_bytes_unchecked(range))
} }

View File

@ -208,12 +208,10 @@ fn dump_path<'tcx>(
let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number { let pass_num = if tcx.sess.opts.unstable_opts.dump_mir_exclude_pass_number {
String::new() String::new()
} else { } else if pass_num {
if pass_num {
format!(".{:03}-{:03}", body.phase.phase_index(), body.pass_count) format!(".{:03}-{:03}", body.phase.phase_index(), body.pass_count)
} else { } else {
".-------".to_string() ".-------".to_string()
}
}; };
let crate_name = tcx.crate_name(source.def_id().krate); let crate_name = tcx.crate_name(source.def_id().krate);

View File

@ -2606,8 +2606,7 @@ impl<'tcx> TyCtxt<'tcx> {
/// With `cfg(debug_assertions)`, assert that args are compatible with their generics, /// With `cfg(debug_assertions)`, assert that args are compatible with their generics,
/// and print out the args if not. /// and print out the args if not.
pub fn debug_assert_args_compatible(self, def_id: DefId, args: &'tcx [ty::GenericArg<'tcx>]) { pub fn debug_assert_args_compatible(self, def_id: DefId, args: &'tcx [ty::GenericArg<'tcx>]) {
if cfg!(debug_assertions) { if cfg!(debug_assertions) && !self.check_args_compatible(def_id, args) {
if !self.check_args_compatible(def_id, args) {
if let DefKind::AssocTy = self.def_kind(def_id) if let DefKind::AssocTy = self.def_kind(def_id)
&& let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id)) && let DefKind::Impl { of_trait: false } = self.def_kind(self.parent(def_id))
{ {
@ -2635,7 +2634,6 @@ impl<'tcx> TyCtxt<'tcx> {
} }
} }
} }
}
#[inline(always)] #[inline(always)]
pub(crate) fn check_and_mk_args( pub(crate) fn check_and_mk_args(

View File

@ -1183,12 +1183,12 @@ pub fn fn_can_unwind(tcx: TyCtxt<'_>, fn_def_id: Option<DefId>, abi: SpecAbi) ->
// //
// This is not part of `codegen_fn_attrs` as it can differ between crates // This is not part of `codegen_fn_attrs` as it can differ between crates
// and therefore cannot be computed in core. // and therefore cannot be computed in core.
if tcx.sess.opts.unstable_opts.panic_in_drop == PanicStrategy::Abort { if tcx.sess.opts.unstable_opts.panic_in_drop == PanicStrategy::Abort
if tcx.is_lang_item(did, LangItem::DropInPlace) { && tcx.is_lang_item(did, LangItem::DropInPlace)
{
return false; return false;
} }
} }
}
// Otherwise if this isn't special then unwinding is generally determined by // Otherwise if this isn't special then unwinding is generally determined by
// the ABI of the itself. ABIs like `C` have variants which also // the ABI of the itself. ABIs like `C` have variants which also

View File

@ -3361,12 +3361,10 @@ pub fn trimmed_def_paths(tcx: TyCtxt<'_>, (): ()) -> DefIdMap<Symbol> {
// name. // name.
// //
// Any stable ordering would be fine here though. // Any stable ordering would be fine here though.
if *v.get() != symbol { if *v.get() != symbol && v.get().as_str() > symbol.as_str() {
if v.get().as_str() > symbol.as_str() {
v.insert(symbol); v.insert(symbol);
} }
} }
}
Vacant(v) => { Vacant(v) => {
v.insert(symbol); v.insert(symbol);
} }

View File

@ -268,10 +268,9 @@ impl Builder<'_, '_> {
pub(crate) fn mcdc_decrement_depth_if_enabled(&mut self) { pub(crate) fn mcdc_decrement_depth_if_enabled(&mut self) {
if let Some(coverage_info) = self.coverage_info.as_mut() if let Some(coverage_info) = self.coverage_info.as_mut()
&& let Some(mcdc_info) = coverage_info.mcdc_info.as_mut() && let Some(mcdc_info) = coverage_info.mcdc_info.as_mut()
&& mcdc_info.state.decision_ctx_stack.pop().is_none()
{ {
if mcdc_info.state.decision_ctx_stack.pop().is_none() {
bug!("Unexpected empty decision stack"); bug!("Unexpected empty decision stack");
}
}; };
} }
} }

View File

@ -95,8 +95,8 @@ impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> {
// Check for assignment to fields of a constant // Check for assignment to fields of a constant
// Assigning directly to a constant (e.g. `FOO = true;`) is a hard error, // Assigning directly to a constant (e.g. `FOO = true;`) is a hard error,
// so emitting a lint would be redundant. // so emitting a lint would be redundant.
if !lhs.projection.is_empty() { if !lhs.projection.is_empty()
if let Some(def_id) = self.is_const_item_without_destructor(lhs.local) && let Some(def_id) = self.is_const_item_without_destructor(lhs.local)
&& let Some((lint_root, span, item)) = && let Some((lint_root, span, item)) =
self.should_lint_const_item_usage(lhs, def_id, loc) self.should_lint_const_item_usage(lhs, def_id, loc)
{ {
@ -107,7 +107,7 @@ impl<'tcx> Visitor<'tcx> for ConstMutationChecker<'_, 'tcx> {
errors::ConstMutate::Modify { konst: item }, errors::ConstMutate::Modify { konst: item },
); );
} }
}
// We are looking for MIR of the form: // We are looking for MIR of the form:
// //
// ``` // ```

View File

@ -168,8 +168,8 @@ pub(super) fn deduced_param_attrs<'tcx>(
// Codegen won't use this information for anything if all the function parameters are passed // Codegen won't use this information for anything if all the function parameters are passed
// directly. Detect that and bail, for compilation speed. // directly. Detect that and bail, for compilation speed.
let fn_ty = tcx.type_of(def_id).instantiate_identity(); let fn_ty = tcx.type_of(def_id).instantiate_identity();
if matches!(fn_ty.kind(), ty::FnDef(..)) { if matches!(fn_ty.kind(), ty::FnDef(..))
if fn_ty && fn_ty
.fn_sig(tcx) .fn_sig(tcx)
.inputs() .inputs()
.skip_binder() .skip_binder()
@ -179,7 +179,6 @@ pub(super) fn deduced_param_attrs<'tcx>(
{ {
return &[]; return &[];
} }
}
// Don't deduce any attributes for functions that have no MIR. // Don't deduce any attributes for functions that have no MIR.
if !tcx.is_mir_available(def_id) { if !tcx.is_mir_available(def_id) {

View File

@ -378,11 +378,11 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
if let (Some(l), Some(r)) = (l, r) if let (Some(l), Some(r)) = (l, r)
&& l.layout.ty.is_integral() && l.layout.ty.is_integral()
&& op.is_overflowing() && op.is_overflowing()
{ && self.use_ecx(|this| {
if self.use_ecx(|this| {
let (_res, overflow) = this.ecx.binary_op(op, &l, &r)?.to_scalar_pair(); let (_res, overflow) = this.ecx.binary_op(op, &l, &r)?.to_scalar_pair();
overflow.to_bool() overflow.to_bool()
})? { })?
{
self.report_assert_as_lint( self.report_assert_as_lint(
location, location,
AssertLintKind::ArithmeticOverflow, AssertLintKind::ArithmeticOverflow,
@ -390,7 +390,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
); );
return None; return None;
} }
}
Some(()) Some(())
} }

View File

@ -504,12 +504,10 @@ fn compute_inlined_overlap<'tcx>(cgu1: &CodegenUnit<'tcx>, cgu2: &CodegenUnit<'t
let mut overlap = 0; let mut overlap = 0;
for (item, data) in src_cgu.items().iter() { for (item, data) in src_cgu.items().iter() {
if data.inlined { if data.inlined && dst_cgu.items().contains_key(item) {
if dst_cgu.items().contains_key(item) {
overlap += data.size_estimate; overlap += data.size_estimate;
} }
} }
}
overlap overlap
} }

View File

@ -185,14 +185,12 @@ impl<'a, D: SolverDelegate<Interner = I>, I: Interner> Canonicalizer<'a, D, I> {
for var in var_infos.iter_mut() { for var in var_infos.iter_mut() {
// We simply put all regions from the input into the highest // We simply put all regions from the input into the highest
// compressed universe, so we only deal with them at the end. // compressed universe, so we only deal with them at the end.
if !var.is_region() { if !var.is_region() && is_existential == var.is_existential() {
if is_existential == var.is_existential() {
update_uv(var, orig_uv, is_existential) update_uv(var, orig_uv, is_existential)
} }
} }
} }
} }
}
// We uniquify regions and always put them into their own universe // We uniquify regions and always put them into their own universe
let mut first_region = true; let mut first_region = true;

View File

@ -2554,8 +2554,7 @@ impl<'a> Parser<'a> {
let maybe_fatarrow = self.token.clone(); let maybe_fatarrow = self.token.clone();
let block = if self.check(&token::OpenDelim(Delimiter::Brace)) { let block = if self.check(&token::OpenDelim(Delimiter::Brace)) {
self.parse_block()? self.parse_block()?
} else { } else if let Some(block) = recover_block_from_condition(self) {
if let Some(block) = recover_block_from_condition(self) {
block block
} else { } else {
self.error_on_extra_if(&cond)?; self.error_on_extra_if(&cond)?;
@ -2592,7 +2591,6 @@ impl<'a> Parser<'a> {
} }
err err
})? })?
}
}; };
self.error_on_if_block_attrs(lo, false, block.span, attrs); self.error_on_if_block_attrs(lo, false, block.span, attrs);
block block

View File

@ -1359,13 +1359,11 @@ impl<'a> Parser<'a> {
fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> { fn parse_attr_args(&mut self) -> PResult<'a, AttrArgs> {
Ok(if let Some(args) = self.parse_delim_args_inner() { Ok(if let Some(args) = self.parse_delim_args_inner() {
AttrArgs::Delimited(args) AttrArgs::Delimited(args)
} else { } else if self.eat(&token::Eq) {
if self.eat(&token::Eq) {
let eq_span = self.prev_token.span; let eq_span = self.prev_token.span;
AttrArgs::Eq(eq_span, AttrArgsEq::Ast(self.parse_expr_force_collect()?)) AttrArgs::Eq(eq_span, AttrArgsEq::Ast(self.parse_expr_force_collect()?))
} else { } else {
AttrArgs::Empty AttrArgs::Empty
}
}) })
} }

View File

@ -1336,8 +1336,7 @@ impl<'a> Parser<'a> {
vec![(first_etc_span, String::new())], vec![(first_etc_span, String::new())],
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
} else { } else if let Some(last_non_comma_dotdot_span) = last_non_comma_dotdot_span {
if let Some(last_non_comma_dotdot_span) = last_non_comma_dotdot_span {
// We have `.., x`. // We have `.., x`.
err.multipart_suggestion( err.multipart_suggestion(
"move the `..` to the end of the field list", "move the `..` to the end of the field list",
@ -1352,7 +1351,6 @@ impl<'a> Parser<'a> {
); );
} }
} }
}
err.emit(); err.emit();
} }
Ok((fields, etc)) Ok((fields, etc))

View File

@ -671,13 +671,13 @@ impl<'a> Parser<'a> {
err.emit(); err.emit();
continue; continue;
} }
if !self.token.kind.should_end_const_arg() { if !self.token.kind.should_end_const_arg()
if self.handle_ambiguous_unbraced_const_arg(&mut args)? { && self.handle_ambiguous_unbraced_const_arg(&mut args)?
{
// We've managed to (partially) recover, so continue trying to parse // We've managed to (partially) recover, so continue trying to parse
// arguments. // arguments.
continue; continue;
} }
}
break; break;
} }
} }

View File

@ -192,15 +192,13 @@ pub fn check_attribute_safety(psess: &ParseSess, safety: AttributeSafety, attr:
); );
} }
} }
} else { } else if let Safety::Unsafe(unsafe_span) = attr_item.unsafety {
if let Safety::Unsafe(unsafe_span) = attr_item.unsafety {
psess.dcx().emit_err(errors::InvalidAttrUnsafe { psess.dcx().emit_err(errors::InvalidAttrUnsafe {
span: unsafe_span, span: unsafe_span,
name: attr_item.path.clone(), name: attr_item.path.clone(),
}); });
} }
} }
}
// Called by `check_builtin_meta_item` and code that manually denies // Called by `check_builtin_meta_item` and code that manually denies
// `unsafe(...)` in `cfg` // `unsafe(...)` in `cfg`

View File

@ -2169,18 +2169,14 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
attr.span, attr.span,
errors::MacroExport::TooManyItems, errors::MacroExport::TooManyItems,
); );
} else { } else if meta_item_list[0].name_or_empty() != sym::local_inner_macros {
if meta_item_list[0].name_or_empty() != sym::local_inner_macros {
self.tcx.emit_node_span_lint( self.tcx.emit_node_span_lint(
INVALID_MACRO_EXPORT_ARGUMENTS, INVALID_MACRO_EXPORT_ARGUMENTS,
hir_id, hir_id,
meta_item_list[0].span(), meta_item_list[0].span(),
errors::MacroExport::UnknownItem { errors::MacroExport::UnknownItem { name: meta_item_list[0].name_or_empty() },
name: meta_item_list[0].name_or_empty(),
},
); );
} }
}
} else { } else {
// special case when `#[macro_export]` is applied to a macro 2.0 // special case when `#[macro_export]` is applied to a macro 2.0
let (macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro(); let (macro_definition, _) = self.tcx.hir_node(hir_id).expect_item().expect_macro();

View File

@ -1500,8 +1500,7 @@ impl<'tcx> Liveness<'_, 'tcx> {
); );
} }
} }
} else { } else if let Some(name) = self.should_warn(var) {
if let Some(name) = self.should_warn(var) {
self.ir.tcx.emit_node_span_lint( self.ir.tcx.emit_node_span_lint(
lint::builtin::UNUSED_VARIABLES, lint::builtin::UNUSED_VARIABLES,
var_hir_id, var_hir_id,
@ -1512,7 +1511,6 @@ impl<'tcx> Liveness<'_, 'tcx> {
} }
} }
} }
}
fn warn_about_unused_args(&self, body: &hir::Body<'_>, entry_ln: LiveNode) { fn warn_about_unused_args(&self, body: &hir::Body<'_>, entry_ln: LiveNode) {
for p in body.params { for p in body.params {

View File

@ -174,17 +174,15 @@ impl<'a, 'tcx> Annotator<'a, 'tcx> {
// If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI, // If the current node is a function, has const stability attributes and if it doesn not have an intrinsic ABI,
// check if the function/method is const or the parent impl block is const // check if the function/method is const or the parent impl block is const
if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig) { if let (Some(const_span), Some(fn_sig)) = (const_span, fn_sig)
if fn_sig.header.abi != Abi::RustIntrinsic && !fn_sig.header.is_const() { && fn_sig.header.abi != Abi::RustIntrinsic
if !self.in_trait_impl && !fn_sig.header.is_const()
|| (self.in_trait_impl && !self.tcx.is_const_fn_raw(def_id.to_def_id())) && (!self.in_trait_impl || !self.tcx.is_const_fn_raw(def_id.to_def_id()))
{ {
self.tcx self.tcx
.dcx() .dcx()
.emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span, const_span }); .emit_err(errors::MissingConstErr { fn_sig_span: fn_sig.span, const_span });
} }
}
}
// `impl const Trait for Type` items forward their const stability to their // `impl const Trait for Type` items forward their const stability to their
// immediate children. // immediate children.

View File

@ -1233,8 +1233,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
&& ns == namespace && ns == namespace
&& in_module != parent_scope.module && in_module != parent_scope.module
&& !ident.span.normalize_to_macros_2_0().from_expansion() && !ident.span.normalize_to_macros_2_0().from_expansion()
&& filter_fn(res)
{ {
if filter_fn(res) {
// create the path // create the path
let mut segms = if lookup_ident.span.at_least_rust_2018() { let mut segms = if lookup_ident.span.at_least_rust_2018() {
// crate-local absolute paths start with `crate::` in edition 2018 // crate-local absolute paths start with `crate::` in edition 2018
@ -1292,7 +1292,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
}); });
} }
} }
}
// collect submodules to explore // collect submodules to explore
if let Some(module) = name_binding.module() { if let Some(module) = name_binding.module() {

View File

@ -958,13 +958,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
}); });
} }
if !restricted_shadowing && binding.expansion != LocalExpnId::ROOT { if !restricted_shadowing
if let NameBindingKind::Import { import, .. } = binding.kind && binding.expansion != LocalExpnId::ROOT
&& let NameBindingKind::Import { import, .. } = binding.kind
&& matches!(import.kind, ImportKind::MacroExport) && matches!(import.kind, ImportKind::MacroExport)
{ {
self.macro_expanded_macro_export_errors.insert((path_span, binding.span)); self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
} }
}
self.record_use(ident, binding, used); self.record_use(ident, binding, used);
return Ok(binding); return Ok(binding);

View File

@ -1256,16 +1256,12 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
extern_crate_span: self.tcx.source_span(self.local_def_id(extern_crate_id)), extern_crate_span: self.tcx.source_span(self.local_def_id(extern_crate_id)),
}, },
); );
} else { } else if ns == TypeNS {
if ns == TypeNS {
let err = if crate_private_reexport { let err = if crate_private_reexport {
self.dcx().create_err(CannotBeReexportedCratePublicNS {
span: import.span,
ident,
})
} else {
self.dcx() self.dcx()
.create_err(CannotBeReexportedPrivateNS { span: import.span, ident }) .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
} else {
self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
}; };
err.emit(); err.emit();
} else { } else {
@ -1273,8 +1269,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
self.dcx() self.dcx()
.create_err(CannotBeReexportedCratePublic { span: import.span, ident }) .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
} else { } else {
self.dcx() self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
.create_err(CannotBeReexportedPrivate { span: import.span, ident })
}; };
match binding.kind { match binding.kind {
@ -1296,7 +1291,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
err.emit(); err.emit();
} }
} }
}
if import.module_path.len() <= 1 { if import.module_path.len() <= 1 {
// HACK(eddyb) `lint_if_path_starts_with_module` needs at least // HACK(eddyb) `lint_if_path_starts_with_module` needs at least

View File

@ -4781,8 +4781,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
if let Some(res) = res if let Some(res) = res
&& let Some(def_id) = res.opt_def_id() && let Some(def_id) = res.opt_def_id()
&& !def_id.is_local() && !def_id.is_local()
{ && self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
if self.r.tcx.crate_types().contains(&CrateType::ProcMacro)
&& matches!( && matches!(
self.r.tcx.sess.opts.resolve_doc_links, self.r.tcx.sess.opts.resolve_doc_links,
ResolveDocLinks::ExportedMetadata ResolveDocLinks::ExportedMetadata
@ -4791,7 +4790,6 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> {
// Encoding foreign def ids in proc macro crate metadata will ICE. // Encoding foreign def ids in proc macro crate metadata will ICE.
return None; return None;
} }
}
res res
}); });
self.r.doc_link_resolutions = doc_link_resolutions; self.r.doc_link_resolutions = doc_link_resolutions;

View File

@ -2255,8 +2255,8 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
fn let_binding_suggestion(&mut self, err: &mut Diag<'_>, ident_span: Span) -> bool { fn let_binding_suggestion(&mut self, err: &mut Diag<'_>, ident_span: Span) -> bool {
if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment if let Some(Expr { kind: ExprKind::Assign(lhs, ..), .. }) = self.diag_metadata.in_assignment
&& let ast::ExprKind::Path(None, ref path) = lhs.kind && let ast::ExprKind::Path(None, ref path) = lhs.kind
&& !ident_span.from_expansion()
{ {
if !ident_span.from_expansion() {
let (span, text) = match path.segments.first() { let (span, text) = match path.segments.first() {
Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => { Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => {
// a special case for #117894 // a special case for #117894
@ -2274,7 +2274,6 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> {
); );
return true; return true;
} }
}
false false
} }

View File

@ -270,14 +270,12 @@ fn strip_generics_from_path_segment(segment: Vec<char>) -> Result<String, Malfor
// Give a helpful error message instead of completely ignoring the angle brackets. // Give a helpful error message instead of completely ignoring the angle brackets.
return Err(MalformedGenerics::HasFullyQualifiedSyntax); return Err(MalformedGenerics::HasFullyQualifiedSyntax);
} }
} else { } else if param_depth == 0 {
if param_depth == 0 {
stripped_segment.push(c); stripped_segment.push(c);
} else { } else {
latest_generics_chunk.push(c); latest_generics_chunk.push(c);
} }
} }
}
if param_depth == 0 { if param_depth == 0 {
Ok(stripped_segment) Ok(stripped_segment)

View File

@ -207,15 +207,13 @@ fn encode_fnsig<'tcx>(
if fn_sig.c_variadic { if fn_sig.c_variadic {
s.push('z'); s.push('z');
} }
} else { } else if fn_sig.c_variadic {
if fn_sig.c_variadic {
s.push('z'); s.push('z');
} else { } else {
// Empty parameter lists, whether declared as () or conventionally as (void), are // Empty parameter lists, whether declared as () or conventionally as (void), are
// encoded with a void parameter specifier "v". // encoded with a void parameter specifier "v".
s.push('v') s.push('v')
} }
}
// Close the "F..E" pair // Close the "F..E" pair
s.push('E'); s.push('E');

View File

@ -69,8 +69,7 @@ where
if must_use_stack { if must_use_stack {
arg.make_indirect_byval(None); arg.make_indirect_byval(None);
} else { } else if is_xtensa_aggregate(arg) {
if is_xtensa_aggregate(arg) {
// Aggregates which are <= max_size will be passed in // Aggregates which are <= max_size will be passed in
// registers if possible, so coerce to integers. // registers if possible, so coerce to integers.
@ -94,7 +93,6 @@ where
} }
} }
} }
}
pub(crate) fn compute_abi_info<'a, Ty, C>(_cx: &C, fn_abi: &mut FnAbi<'a, Ty>) pub(crate) fn compute_abi_info<'a, Ty, C>(_cx: &C, fn_abi: &mut FnAbi<'a, Ty>)
where where

View File

@ -1323,8 +1323,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
label_or_note(span, terr.to_string(self.tcx)); label_or_note(span, terr.to_string(self.tcx));
label_or_note(sp, msg); label_or_note(sp, msg);
} }
} else { } else if let Some(values) = values
if let Some(values) = values
&& let Some((e, f)) = values.ty() && let Some((e, f)) = values.ty()
&& let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) = terr && let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) = terr
{ {
@ -1340,7 +1339,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
} else { } else {
label_or_note(span, terr.to_string(self.tcx)); label_or_note(span, terr.to_string(self.tcx));
} }
}
if let Some((expected, found, path)) = expected_found { if let Some((expected, found, path)) = expected_found {
let (expected_label, found_label, exp_found) = match exp_found { let (expected_label, found_label, exp_found) = match exp_found {

View File

@ -3237,16 +3237,13 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
// then the tuple must be the one containing capture types. // then the tuple must be the one containing capture types.
let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) { let is_upvar_tys_infer_tuple = if !matches!(ty.kind(), ty::Tuple(..)) {
false false
} else { } else if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code {
if let ObligationCauseCode::BuiltinDerived(data) = &*data.parent_code { let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
let parent_trait_ref =
self.resolve_vars_if_possible(data.parent_trait_pred);
let nested_ty = parent_trait_ref.skip_binder().self_ty(); let nested_ty = parent_trait_ref.skip_binder().self_ty();
matches!(nested_ty.kind(), ty::Coroutine(..)) matches!(nested_ty.kind(), ty::Coroutine(..))
|| matches!(nested_ty.kind(), ty::Closure(..)) || matches!(nested_ty.kind(), ty::Closure(..))
} else { } else {
false false
}
}; };
if !is_upvar_tys_infer_tuple { if !is_upvar_tys_infer_tuple {

View File

@ -426,15 +426,13 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
} else if kind == ty::ClosureKind::FnOnce { } else if kind == ty::ClosureKind::FnOnce {
candidates.vec.push(ClosureCandidate { is_const }); candidates.vec.push(ClosureCandidate { is_const });
} }
} else { } else if kind == ty::ClosureKind::FnOnce {
if kind == ty::ClosureKind::FnOnce {
candidates.vec.push(ClosureCandidate { is_const }); candidates.vec.push(ClosureCandidate { is_const });
} else { } else {
// This stays ambiguous until kind+upvars are determined. // This stays ambiguous until kind+upvars are determined.
candidates.ambiguous = true; candidates.ambiguous = true;
} }
} }
}
ty::Infer(ty::TyVar(_)) => { ty::Infer(ty::TyVar(_)) => {
debug!("assemble_unboxed_closure_candidates: ambiguous self-type"); debug!("assemble_unboxed_closure_candidates: ambiguous self-type");
candidates.ambiguous = true; candidates.ambiguous = true;
@ -513,12 +511,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
// then there's nothing else to check. // then there's nothing else to check.
if let Some(closure_kind) = self_ty.to_opt_closure_kind() if let Some(closure_kind) = self_ty.to_opt_closure_kind()
&& let Some(goal_kind) = target_kind_ty.to_opt_closure_kind() && let Some(goal_kind) = target_kind_ty.to_opt_closure_kind()
&& closure_kind.extends(goal_kind)
{ {
if closure_kind.extends(goal_kind) {
candidates.vec.push(AsyncFnKindHelperCandidate); candidates.vec.push(AsyncFnKindHelperCandidate);
} }
} }
}
/// Implements one of the `Fn()` family for a fn pointer. /// Implements one of the `Fn()` family for a fn pointer.
fn assemble_fn_pointer_candidates( fn assemble_fn_pointer_candidates(

View File

@ -1334,8 +1334,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
return; return;
} }
if self.can_use_global_caches(param_env) { if self.can_use_global_caches(param_env) && !trait_pred.has_infer() {
if !trait_pred.has_infer() {
debug!(?trait_pred, ?result, "insert_evaluation_cache global"); debug!(?trait_pred, ?result, "insert_evaluation_cache global");
// This may overwrite the cache with the same value // This may overwrite the cache with the same value
// FIXME: Due to #50507 this overwrites the different values // FIXME: Due to #50507 this overwrites the different values
@ -1344,7 +1343,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
self.tcx().evaluation_cache.insert((param_env, trait_pred), dep_node, result); self.tcx().evaluation_cache.insert((param_env, trait_pred), dep_node, result);
return; return;
} }
}
debug!(?trait_pred, ?result, "insert_evaluation_cache"); debug!(?trait_pred, ?result, "insert_evaluation_cache");
self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result); self.infcx.evaluation_cache.insert((param_env, trait_pred), dep_node, result);
@ -1584,15 +1582,13 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> {
if self.can_use_global_caches(param_env) { if self.can_use_global_caches(param_env) {
if let Err(Overflow(OverflowError::Canonical)) = candidate { if let Err(Overflow(OverflowError::Canonical)) = candidate {
// Don't cache overflow globally; we only produce this in certain modes. // Don't cache overflow globally; we only produce this in certain modes.
} else if !pred.has_infer() { } else if !pred.has_infer() && !candidate.has_infer() {
if !candidate.has_infer() {
debug!(?pred, ?candidate, "insert_candidate_cache global"); debug!(?pred, ?candidate, "insert_candidate_cache global");
// This may overwrite the cache with the same value. // This may overwrite the cache with the same value.
tcx.selection_cache.insert((param_env, pred), dep_node, candidate); tcx.selection_cache.insert((param_env, pred), dep_node, candidate);
return; return;
} }
} }
}
debug!(?pred, ?candidate, "insert_candidate_cache local"); debug!(?pred, ?candidate, "insert_candidate_cache local");
self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate); self.infcx.selection_cache.insert((param_env, pred), dep_node, candidate);
@ -1980,11 +1976,11 @@ impl<'tcx> SelectionContext<'_, 'tcx> {
// impls have to be always applicable, meaning that the only allowed // impls have to be always applicable, meaning that the only allowed
// region constraints may be constraints also present on the default impl. // region constraints may be constraints also present on the default impl.
let tcx = self.tcx(); let tcx = self.tcx();
if other.evaluation.must_apply_modulo_regions() { if other.evaluation.must_apply_modulo_regions()
if tcx.specializes((other_def, victim_def)) { && tcx.specializes((other_def, victim_def))
{
return DropVictim::Yes; return DropVictim::Yes;
} }
}
match tcx.impls_are_allowed_to_overlap(other_def, victim_def) { match tcx.impls_are_allowed_to_overlap(other_def, victim_def) {
// For #33140 the impl headers must be exactly equal, the trait must not have // For #33140 the impl headers must be exactly equal, the trait must not have

View File

@ -143,13 +143,11 @@ impl<'tcx> OpaqueTypeCollector<'tcx> {
match origin { match origin {
rustc_hir::OpaqueTyOrigin::FnReturn(_) | rustc_hir::OpaqueTyOrigin::AsyncFn(_) => {} rustc_hir::OpaqueTyOrigin::FnReturn(_) | rustc_hir::OpaqueTyOrigin::AsyncFn(_) => {}
rustc_hir::OpaqueTyOrigin::TyAlias { in_assoc_ty, .. } => { rustc_hir::OpaqueTyOrigin::TyAlias { in_assoc_ty, .. } => {
if !in_assoc_ty { if !in_assoc_ty && !self.check_tait_defining_scope(alias_ty.def_id.expect_local()) {
if !self.check_tait_defining_scope(alias_ty.def_id.expect_local()) {
return; return;
} }
} }
} }
}
self.opaques.push(alias_ty.def_id.expect_local()); self.opaques.push(alias_ty.def_id.expect_local());