From 05785550c84b378cc1c0e85ed24d67ef02b803b7 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Wed, 23 Mar 2022 21:26:38 -0700 Subject: [PATCH] Format the world (considering let-chains) --- compiler/rustc_ast/src/attr/mod.rs | 4 +- .../rustc_ast_passes/src/ast_validation.rs | 23 +++-- .../src/diagnostics/conflict_errors.rs | 4 +- .../src/diagnostics/explain_borrow.rs | 3 +- compiler/rustc_expand/src/config.rs | 13 +-- compiler/rustc_expand/src/mbe/metavar_expr.rs | 3 +- compiler/rustc_expand/src/module.rs | 4 +- .../src/infer/error_reporting/mod.rs | 6 +- .../infer/error_reporting/need_type_info.rs | 21 ++--- .../nice_region_error/static_impl_trait.rs | 3 +- .../trait_impl_difference.rs | 20 ++-- compiler/rustc_lint/src/internal.rs | 2 +- compiler/rustc_lint/src/types.rs | 61 +++++++------ compiler/rustc_middle/src/ty/print/pretty.rs | 19 ++-- .../rustc_mir_build/src/build/expr/stmt.rs | 4 +- .../rustc_mir_build/src/build/matches/mod.rs | 5 +- .../rustc_mir_build/src/check_unsafety.rs | 4 +- .../src/thir/pattern/check_match.rs | 55 +++++------ .../rustc_mir_build/src/thir/pattern/mod.rs | 9 +- .../rustc_mir_transform/src/coverage/debug.rs | 6 +- .../rustc_mir_transform/src/coverage/spans.rs | 12 ++- compiler/rustc_parse/src/lib.rs | 5 +- .../rustc_parse/src/parser/diagnostics.rs | 3 +- compiler/rustc_parse/src/parser/expr.rs | 9 +- .../rustc_parse/src/parser/nonterminal.rs | 19 ++-- compiler/rustc_parse/src/parser/stmt.rs | 4 +- compiler/rustc_passes/src/check_attr.rs | 16 +--- compiler/rustc_passes/src/check_const.rs | 91 +++++++++---------- compiler/rustc_passes/src/entry.rs | 10 +- compiler/rustc_passes/src/intrinsicck.rs | 8 +- compiler/rustc_span/src/source_map.rs | 8 +- .../src/traits/on_unimplemented.rs | 28 +++--- .../src/traits/select/mod.rs | 3 +- compiler/rustc_typeck/src/check/check.rs | 28 +++--- compiler/rustc_typeck/src/check/coercion.rs | 2 +- compiler/rustc_typeck/src/check/demand.rs | 35 ++++--- .../rustc_typeck/src/check/fn_ctxt/_impl.rs | 4 +- .../rustc_typeck/src/check/fn_ctxt/checks.rs | 22 +++-- .../rustc_typeck/src/check/method/probe.rs | 3 +- .../rustc_typeck/src/check/method/suggest.rs | 16 ++-- compiler/rustc_typeck/src/check/pat.rs | 37 ++++---- compiler/rustc_typeck/src/check/writeback.rs | 3 +- compiler/rustc_typeck/src/collect.rs | 11 +-- compiler/rustc_typeck/src/collect/type_of.rs | 84 ++++++++--------- 44 files changed, 368 insertions(+), 362 deletions(-) diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 550c66e3d3b20..fb1bdbcd5176e 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -595,9 +595,7 @@ impl NestedMetaItem { I: Iterator, { match tokens.peek() { - Some(TokenTree::Token(token)) - if let Ok(lit) = Lit::from_token(token) => - { + Some(TokenTree::Token(token)) if let Ok(lit) = Lit::from_token(token) => { tokens.next(); return Some(NestedMetaItem::Literal(lit)); } diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 8ba6a914c4a4b..980fcbaf98015 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -1003,8 +1003,10 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } fn visit_expr(&mut self, expr: &'a Expr) { - self.with_let_management(Some(ForbiddenLetReason::GenericForbidden), |this, forbidden_let_reason| { - match &expr.kind { + self.with_let_management( + Some(ForbiddenLetReason::GenericForbidden), + |this, forbidden_let_reason| { + match &expr.kind { ExprKind::Binary(Spanned { node: BinOpKind::Or, span }, lhs, rhs) => { let forbidden_let_reason = Some(ForbiddenLetReason::ForbiddenWithOr(*span)); this.with_let_management(forbidden_let_reason, |this, _| this.visit_expr(lhs)); @@ -1018,23 +1020,25 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } ExprKind::Let(..) if let Some(elem) = forbidden_let_reason => { this.ban_let_expr(expr, elem); - }, + } ExprKind::Match(scrutinee, arms) => { this.visit_expr(scrutinee); for arm in arms { this.visit_expr(&arm.body); this.visit_pat(&arm.pat); walk_list!(this, visit_attribute, &arm.attrs); - if let Some(guard) = &arm.guard && let ExprKind::Let(_, guard_expr, _) = &guard.kind { - this.with_let_management(None, |this, _| { - this.visit_expr(guard_expr) - }); + if let Some(guard) = &arm.guard + && let ExprKind::Let(_, guard_expr, _) = &guard.kind + { + this.with_let_management(None, |this, _| this.visit_expr(guard_expr)); return; } } } ExprKind::Paren(_) | ExprKind::Binary(Spanned { node: BinOpKind::And, .. }, ..) => { - this.with_let_management(forbidden_let_reason, |this, _| visit::walk_expr(this, expr)); + this.with_let_management(forbidden_let_reason, |this, _| { + visit::walk_expr(this, expr) + }); return; } ExprKind::While(cond, then, opt_label) => { @@ -1045,7 +1049,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> { } _ => visit::walk_expr(this, expr), } - }); + }, + ); } fn visit_ty(&mut self, ty: &'a Ty) { diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 66a23eb4125d5..cffddb283aab3 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -1840,9 +1840,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { err.span_label(assigned_span, format!("first assignment to {}", place_description)); } } - if let Some(decl) = local_decl - && let Some(name) = local_name - && decl.can_be_made_mutable() + if let Some(decl) = local_decl && let Some(name) = local_name && decl.can_be_made_mutable() { err.span_suggestion( decl.source_info.span, diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index ffea15bdc33eb..abfabcf47dc65 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -378,7 +378,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if self.local_names[local].is_some() && let Some((WriteKind::StorageDeadOrDrop, place)) = kind_place && let Some(borrowed_local) = place.as_local() - && self.local_names[borrowed_local].is_some() && local != borrowed_local + && self.local_names[borrowed_local].is_some() + && local != borrowed_local { should_note_order = true; } diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 762198887cf8c..83ae16c189ef9 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -290,7 +290,8 @@ impl<'a> StripUnconfigured<'a> { let trees: Vec<_> = stream .0 .iter() - .flat_map(|(tree, spacing)| match tree.clone() { + .flat_map(|(tree, spacing)| { + match tree.clone() { AttrAnnotatedTokenTree::Attributes(mut data) => { let mut attrs: Vec<_> = std::mem::take(&mut data.attrs).into(); attrs.flat_map_in_place(|attr| self.process_cfg_attr(attr)); @@ -310,15 +311,15 @@ impl<'a> StripUnconfigured<'a> { Some((AttrAnnotatedTokenTree::Delimited(sp, delim, inner), *spacing)) .into_iter() } - AttrAnnotatedTokenTree::Token(ref token) if let TokenKind::Interpolated(ref nt) = token.kind => { - panic!( - "Nonterminal should have been flattened at {:?}: {:?}", - token.span, nt - ); + AttrAnnotatedTokenTree::Token(ref token) + if let TokenKind::Interpolated(ref nt) = token.kind => + { + panic!("Nonterminal should have been flattened at {:?}: {:?}", token.span, nt); } AttrAnnotatedTokenTree::Token(token) => { Some((AttrAnnotatedTokenTree::Token(token), *spacing)).into_iter() } + } }) .collect(); AttrAnnotatedTokenStream::new(trees) diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs index 2949ca716b230..2fefc71dee47a 100644 --- a/compiler/rustc_expand/src/mbe/metavar_expr.rs +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -115,8 +115,7 @@ fn parse_depth<'sess>( && let Ok(n_usize) = usize::try_from(n_u128) { Ok(n_usize) - } - else { + } else { let msg = "only unsuffixes integer literals are supported in meta-variable expressions"; Err(sess.span_diagnostic.struct_span_err(span, msg)) } diff --git a/compiler/rustc_expand/src/module.rs b/compiler/rustc_expand/src/module.rs index 2a059f3519d1e..feb3c17d0ff6b 100644 --- a/compiler/rustc_expand/src/module.rs +++ b/compiler/rustc_expand/src/module.rs @@ -87,7 +87,9 @@ crate fn mod_dir_path( inline: Inline, ) -> (PathBuf, DirOwnership) { match inline { - Inline::Yes if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) => { + Inline::Yes + if let Some(file_path) = mod_file_path_from_attr(sess, attrs, &module.dir_path) => + { // For inline modules file path from `#[path]` is actually the directory path // for historical reasons, so we don't pop the last segment here. (file_path, DirOwnership::Owned { relative: None }) diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index abc25d51776f3..40c81c6c17d7f 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -607,7 +607,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { err.span_label(span, format!("this expression has type `{}`", ty)); } if let Some(ty::error::ExpectedFound { found, .. }) = exp_found - && ty.is_box() && ty.boxed_ty() == found + && ty.is_box() + && ty.boxed_ty() == found && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { err.span_suggestion( @@ -2047,7 +2048,8 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { // specify a character literal (issue #92479) (ty::Char, ty::Ref(_, r, _)) if r.is_str() => { if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) - && let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"')) + && let Some(code) = + code.strip_prefix('"').and_then(|s| s.strip_suffix('"')) && code.chars().count() == 1 { err.span_suggestion( diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index a9a92fdbd6448..5704948322c44 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -124,12 +124,13 @@ impl<'a, 'tcx> Visitor<'tcx> for FindHirNodeVisitor<'a, 'tcx> { } if let ExprKind::MethodCall(segment, exprs, _) = expr.kind && segment.ident.span == self.target_span - && Some(self.target) == self.infcx.in_progress_typeck_results.and_then(|typeck_results| { - typeck_results - .borrow() - .node_type_opt(exprs.first().unwrap().hir_id) - .map(Into::into) - }) + && Some(self.target) + == self.infcx.in_progress_typeck_results.and_then(|typeck_results| { + typeck_results + .borrow() + .node_type_opt(exprs.first().unwrap().hir_id) + .map(Into::into) + }) { self.found_exact_method_call = Some(&expr); return; @@ -731,17 +732,15 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { // | help: specify type like: `>::into(foo_impl)` // | // = note: cannot satisfy `Impl: Into<_>` - if !impl_candidates.is_empty() && e.span.contains(span) + if !impl_candidates.is_empty() + && e.span.contains(span) && let Some(expr) = exprs.first() && let ExprKind::Path(hir::QPath::Resolved(_, path)) = expr.kind && let [path_segment] = path.segments { let candidate_len = impl_candidates.len(); let suggestions = impl_candidates.iter().map(|candidate| { - format!( - "{}::{}({})", - candidate, segment.ident, path_segment.ident - ) + format!("{}::{}({})", candidate, segment.ident, path_segment.ident) }); err.span_suggestions( e.span, diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index 4fcdcb6366683..3f4835589a071 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -237,7 +237,8 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { ObligationCauseCode::MatchImpl(parent, ..) => parent.code(), _ => cause.code(), } - && let (ObligationCauseCode::ItemObligation(item_def_id), None) = (code, override_error_code) + && let (ObligationCauseCode::ItemObligation(item_def_id), None) = + (code, override_error_code) { // Same case of `impl Foo for dyn Bar { fn qux(&self) {} }` introducing a `'static` // lifetime as above, but called using a fully-qualified path to the method: diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs index b1a42ee66c920..7d8da7e323231 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs @@ -23,8 +23,14 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { let error = self.error.as_ref()?; debug!("try_report_impl_not_conforming_to_trait {:?}", error); if let RegionResolutionError::SubSupConflict( - _, var_origin, sub_origin, _sub, sup_origin, _sup, _, - ) = error.clone() + _, + var_origin, + sub_origin, + _sub, + sup_origin, + _sup, + _, + ) = error.clone() && let (&Subtype(ref sup_trace), &Subtype(ref sub_trace)) = (&sup_origin, &sub_origin) && let ( sub_expected_found @ Some((sub_expected, sub_found)), @@ -33,16 +39,12 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { ) = (sub_trace.values.ty(), sup_trace.values.ty(), sub_trace.cause.code()) && sup_expected_found == sub_expected_found { - let guar = self.emit_err( - var_origin.span(), - sub_expected, - sub_found, - *trait_item_def_id, - ); + let guar = + self.emit_err(var_origin.span(), sub_expected, sub_found, *trait_item_def_id); return Some(guar); } if let RegionResolutionError::ConcreteFailure(origin, _, _) - | RegionResolutionError::GenericBoundFailure(origin, _, _) = error.clone() + | RegionResolutionError::GenericBoundFailure(origin, _, _) = error.clone() && let SubregionOrigin::CompareImplTypeObligation { span, impl_item_def_id, diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 27d44da6dfc38..610837721dd9d 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -77,7 +77,7 @@ impl LateLintPass<'_> for QueryStability { if let Some(def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id) => { (segment.ident.span, def_id, cx.typeck_results().node_substs(expr.hir_id)) - }, + } _ => { let &ty::FnDef(def_id, substs) = cx.typeck_results() diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index c95905b9b1851..82f64ee652d64 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -1500,7 +1500,8 @@ impl InvalidAtomicOrdering { fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) { use rustc_hir::def::{DefKind, Res}; use rustc_hir::QPath; - if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store]) + if let Some((method, args)) = + Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store]) && let Some((ordering_arg, invalid_ordering)) = match method { sym::load => Some((&args[1], sym::Release)), sym::store => Some((&args[2], sym::Acquire)), @@ -1536,56 +1537,58 @@ impl InvalidAtomicOrdering { { cx.struct_span_lint(INVALID_ATOMIC_ORDERING, args[0].span, |diag| { diag.build("memory fences cannot have `Relaxed` ordering") - .help("consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`") + .help( + "consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`", + ) .emit(); }); } } fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { - if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak]) - && let Some((success_order_arg, failure_order_arg)) = match method { - sym::fetch_update => Some((&args[1], &args[2])), - sym::compare_exchange | sym::compare_exchange_weak => Some((&args[3], &args[4])), - _ => None, - } - && let Some(fail_ordering_def_id) = Self::opt_ordering_defid(cx, failure_order_arg) + if let Some((method, args)) = Self::inherent_atomic_method_call( + cx, + expr, + &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak], + ) && let Some((success_order_arg, failure_order_arg)) = match method { + sym::fetch_update => Some((&args[1], &args[2])), + sym::compare_exchange | sym::compare_exchange_weak => Some((&args[3], &args[4])), + _ => None, + } && let Some(fail_ordering_def_id) = Self::opt_ordering_defid(cx, failure_order_arg) { // Helper type holding on to some checking and error reporting data. Has // - (success ordering, // - list of failure orderings forbidden by the success order, // - suggestion message) type OrdLintInfo = (Symbol, &'static [Symbol], &'static str); - const RELAXED: OrdLintInfo = (sym::Relaxed, &[sym::SeqCst, sym::Acquire], "ordering mode `Relaxed`"); - const ACQUIRE: OrdLintInfo = (sym::Acquire, &[sym::SeqCst], "ordering modes `Acquire` or `Relaxed`"); - const SEQ_CST: OrdLintInfo = (sym::SeqCst, &[], "ordering modes `Acquire`, `SeqCst` or `Relaxed`"); + const RELAXED: OrdLintInfo = + (sym::Relaxed, &[sym::SeqCst, sym::Acquire], "ordering mode `Relaxed`"); + const ACQUIRE: OrdLintInfo = + (sym::Acquire, &[sym::SeqCst], "ordering modes `Acquire` or `Relaxed`"); + const SEQ_CST: OrdLintInfo = + (sym::SeqCst, &[], "ordering modes `Acquire`, `SeqCst` or `Relaxed`"); const RELEASE: OrdLintInfo = (sym::Release, RELAXED.1, RELAXED.2); const ACQREL: OrdLintInfo = (sym::AcqRel, ACQUIRE.1, ACQUIRE.2); const SEARCH: [OrdLintInfo; 5] = [RELAXED, ACQUIRE, SEQ_CST, RELEASE, ACQREL]; - let success_lint_info = Self::opt_ordering_defid(cx, success_order_arg) - .and_then(|success_ord_def_id| -> Option { - SEARCH - .iter() - .copied() - .find(|(ordering, ..)| { - Self::matches_ordering(cx, success_ord_def_id, &[*ordering]) - }) - }); + let success_lint_info = Self::opt_ordering_defid(cx, success_order_arg).and_then( + |success_ord_def_id| -> Option { + SEARCH.iter().copied().find(|(ordering, ..)| { + Self::matches_ordering(cx, success_ord_def_id, &[*ordering]) + }) + }, + ); if Self::matches_ordering(cx, fail_ordering_def_id, &[sym::Release, sym::AcqRel]) { // If we don't know the success order is, use what we'd suggest // if it were maximally permissive. let suggested = success_lint_info.unwrap_or(SEQ_CST).2; cx.struct_span_lint(INVALID_ATOMIC_ORDERING, failure_order_arg.span, |diag| { - let msg = format!( - "{}'s failure ordering may not be `Release` or `AcqRel`", - method, - ); - diag.build(&msg) - .help(&format!("consider using {} instead", suggested)) - .emit(); + let msg = + format!("{}'s failure ordering may not be `Release` or `AcqRel`", method,); + diag.build(&msg).help(&format!("consider using {} instead", suggested)).emit(); }); - } else if let Some((success_ord, bad_ords_given_success, suggested)) = success_lint_info { + } else if let Some((success_ord, bad_ords_given_success, suggested)) = success_lint_info + { if Self::matches_ordering(cx, fail_ordering_def_id, bad_ords_given_success) { cx.struct_span_lint(INVALID_ATOMIC_ORDERING, failure_order_arg.span, |diag| { let msg = format!( diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 5cfd9a5edfb19..fa4ed38015898 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -910,9 +910,10 @@ pub trait PrettyPrinter<'tcx>: for (assoc_item_def_id, term) in assoc_items { // Skip printing `<[generator@] as Generator<_>>::Return` from async blocks - if let Some(ty) = term.skip_binder().ty() && - let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = ty.kind() && - Some(*item_def_id) == self.tcx().lang_items().generator_return() { + if let Some(ty) = term.skip_binder().ty() + && let ty::Projection(ty::ProjectionTy { item_def_id, .. }) = ty.kind() + && Some(*item_def_id) == self.tcx().lang_items().generator_return() + { continue; } @@ -1202,14 +1203,12 @@ pub trait PrettyPrinter<'tcx>: } } } - ty::ConstKind::Infer(infer_ct) => { - match infer_ct { - ty::InferConst::Var(ct_vid) - if let Some(name) = self.const_infer_name(ct_vid) => - p!(write("{}", name)), - _ => print_underscore!(), + ty::ConstKind::Infer(infer_ct) => match infer_ct { + ty::InferConst::Var(ct_vid) if let Some(name) = self.const_infer_name(ct_vid) => { + p!(write("{}", name)) } - } + _ => print_underscore!(), + }, ty::ConstKind::Param(ParamConst { name, .. }) => p!(write("{}", name)), ty::ConstKind::Value(value) => { return self.pretty_print_const_value(value, ct.ty(), print_ty); diff --git a/compiler/rustc_mir_build/src/build/expr/stmt.rs b/compiler/rustc_mir_build/src/build/expr/stmt.rs index 46c616ff36241..1f75ebc6d0fd6 100644 --- a/compiler/rustc_mir_build/src/build/expr/stmt.rs +++ b/compiler/rustc_mir_build/src/build/expr/stmt.rs @@ -118,9 +118,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let adjusted_span = (|| { if let ExprKind::Block { body } = &expr.kind && let Some(tail_ex) = body.expr { let mut expr = &this.thir[tail_ex]; - while let ExprKind::Block { - body: Block { expr: Some(nested_expr), .. }, - } + while let ExprKind::Block { body: Block { expr: Some(nested_expr), .. } } | ExprKind::Scope { value: nested_expr, .. } = expr.kind { expr = &this.thir[nested_expr]; diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index c724e3e1b8f2a..0ed3bde7713c3 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -1597,8 +1597,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } // Insert a Shallow borrow of any places that is switched on. - if let Some(fb) = fake_borrows && let Ok(match_place_resolved) = - match_place.clone().try_upvars_resolved(self.tcx, self.typeck_results) + if let Some(fb) = fake_borrows + && let Ok(match_place_resolved) = + match_place.clone().try_upvars_resolved(self.tcx, self.typeck_results) { let resolved_place = match_place_resolved.into_place(self.tcx, self.typeck_results); fb.insert(resolved_place); diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 122af3f621087..bebeb91b50b56 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -421,9 +421,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { if let ty::Adt(adt_def, _) = lhs.ty.kind() && adt_def.is_union() { if let Some((assigned_ty, assignment_span)) = self.assignment_info { // To avoid semver hazard, we only consider `Copy` and `ManuallyDrop` non-dropping. - if !(assigned_ty - .ty_adt_def() - .map_or(false, |adt| adt.is_manually_drop()) + if !(assigned_ty.ty_adt_def().map_or(false, |adt| adt.is_manually_drop()) || assigned_ty .is_copy_modulo_regions(self.tcx.at(expr.span), self.param_env)) { diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 8a3a46c11903a..272140c13d843 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -355,7 +355,10 @@ impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> { diag.emit() }); }; - if let Some(until) = chain_refutabilities.iter().position(|r| !matches!(*r, Some((_, false)))) && until > 0 { + if let Some(until) = + chain_refutabilities.iter().position(|r| !matches!(*r, Some((_, false)))) + && until > 0 + { // The chain has a non-zero prefix of irrefutable `let` statements. // Check if the let source is while, for there is no alternative place to put a prefix, @@ -367,7 +370,10 @@ impl<'p, 'tcx> MatchVisitor<'_, 'p, 'tcx> { lint_affix(prefix, "leading", "outside of the construct"); } } - if let Some(from) = chain_refutabilities.iter().rposition(|r| !matches!(*r, Some((_, false)))) && from != (chain_refutabilities.len() - 1) { + if let Some(from) = + chain_refutabilities.iter().rposition(|r| !matches!(*r, Some((_, false)))) + && from != (chain_refutabilities.len() - 1) + { // The chain has a non-empty suffix of irrefutable `let` statements let suffix = &chain_refutabilities[from + 1..]; lint_affix(suffix, "trailing", "into the body"); @@ -551,32 +557,27 @@ fn check_for_bindings_named_same_as_variants( }) { let variant_count = edef.variants().len(); - cx.tcx.struct_span_lint_hir( - BINDINGS_WITH_VARIANT_NAME, - p.hir_id, - p.span, - |lint| { - let ty_path = cx.tcx.def_path_str(edef.did()); - let mut err = lint.build(&format!( - "pattern binding `{}` is named the same as one \ + cx.tcx.struct_span_lint_hir(BINDINGS_WITH_VARIANT_NAME, p.hir_id, p.span, |lint| { + let ty_path = cx.tcx.def_path_str(edef.did()); + let mut err = lint.build(&format!( + "pattern binding `{}` is named the same as one \ of the variants of the type `{}`", - ident, ty_path - )); - err.code(error_code!(E0170)); - // If this is an irrefutable pattern, and there's > 1 variant, - // then we can't actually match on this. Applying the below - // suggestion would produce code that breaks on `check_irrefutable`. - if rf == Refutable || variant_count == 1 { - err.span_suggestion( - p.span, - "to match on the variant, qualify the path", - format!("{}::{}", ty_path, ident), - Applicability::MachineApplicable, - ); - } - err.emit(); - }, - ) + ident, ty_path + )); + err.code(error_code!(E0170)); + // If this is an irrefutable pattern, and there's > 1 variant, + // then we can't actually match on this. Applying the below + // suggestion would produce code that breaks on `check_irrefutable`. + if rf == Refutable || variant_count == 1 { + err.span_suggestion( + p.span, + "to match on the variant, qualify the path", + format!("{}::{}", ty_path, ident), + Applicability::MachineApplicable, + ); + } + err.emit(); + }) } }); } diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index d21fbb9edffb7..07312d9135fd7 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -790,10 +790,11 @@ crate fn compare_const_vals<'tcx>( }; } - if let ty::Str = ty.kind() && let ( - ty::ConstKind::Value(a_val @ ConstValue::Slice { .. }), - ty::ConstKind::Value(b_val @ ConstValue::Slice { .. }), - ) = (a.val(), b.val()) + if let ty::Str = ty.kind() + && let ( + ty::ConstKind::Value(a_val @ ConstValue::Slice { .. }), + ty::ConstKind::Value(b_val @ ConstValue::Slice { .. }), + ) = (a.val(), b.val()) { let a_bytes = get_slice_bytes(&tcx, a_val); let b_bytes = get_slice_bytes(&tcx, b_val); diff --git a/compiler/rustc_mir_transform/src/coverage/debug.rs b/compiler/rustc_mir_transform/src/coverage/debug.rs index 8e28ed2426bbb..d5981cafcd6f9 100644 --- a/compiler/rustc_mir_transform/src/coverage/debug.rs +++ b/compiler/rustc_mir_transform/src/coverage/debug.rs @@ -358,11 +358,7 @@ impl DebugCounters { if let Some(DebugCounter { counter_kind, some_block_label }) = counters.get(&operand) { if let CoverageKind::Expression { .. } = counter_kind { if let Some(label) = some_block_label && debug_options().counter_format.block { - return format!( - "{}:({})", - label, - self.format_counter_kind(counter_kind) - ); + return format!("{}:({})", label, self.format_counter_kind(counter_kind)); } return format!("({})", self.format_counter_kind(counter_kind)); } diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index a36ba9300e4ff..be75224ab1c6b 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -191,11 +191,13 @@ impl CoverageSpan { /// If the span is part of a macro, and the macro is visible (expands directly to the given /// body_span), returns the macro name symbol. pub fn visible_macro(&self, body_span: Span) -> Option { - if let Some(current_macro) = self.current_macro() && self - .expn_span - .parent_callsite() - .unwrap_or_else(|| bug!("macro must have a parent")) - .ctxt() == body_span.ctxt() + if let Some(current_macro) = self.current_macro() + && self + .expn_span + .parent_callsite() + .unwrap_or_else(|| bug!("macro must have a parent")) + .ctxt() + == body_span.ctxt() { return Some(current_macro); } diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index a3e66464fbc8f..dc10981451104 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -269,10 +269,7 @@ pub fn nt_to_tokenstream( Nonterminal::NtBlock(ref block) => convert_tokens(block.tokens.as_ref()), Nonterminal::NtStmt(ref stmt) if let ast::StmtKind::Empty = stmt.kind => { let tokens = AttrAnnotatedTokenStream::new(vec![( - tokenstream::AttrAnnotatedTokenTree::Token(Token::new( - TokenKind::Semi, - stmt.span, - )), + tokenstream::AttrAnnotatedTokenTree::Token(Token::new(TokenKind::Semi, stmt.span)), Spacing::Alone, )]); prepend_attrs(&stmt.attrs(), Some(&LazyTokenStream::new(tokens))) diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index b5b628a3f55bd..6dcf81f701378 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -796,8 +796,7 @@ impl<'a> Parser<'a> { .emit(); match self.parse_expr() { Ok(_) => { - *expr = - self.mk_expr_err(expr.span.to(self.prev_token.span)); + *expr = self.mk_expr_err(expr.span.to(self.prev_token.span)); return Ok(()); } Err(err) => { diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 148e0a24ec304..8c9e808bdcbb4 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -2118,10 +2118,13 @@ impl<'a> Parser<'a> { let missing_then_block_binop_span = || { match cond.kind { - ExprKind::Binary(Spanned { span: binop_span, .. }, _, ref right) - if let ExprKind::Block(..) = right.kind => Some(binop_span), - _ => None + ExprKind::Binary(Spanned { span: binop_span, .. }, _, ref right) + if let ExprKind::Block(..) = right.kind => + { + Some(binop_span) } + _ => None, + } }; // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 40902fa183313..5ed7783c46de4 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -124,9 +124,12 @@ impl<'a> Parser<'a> { NonterminalKind::PatParam { .. } | NonterminalKind::PatWithOr { .. } => { token::NtPat(self.collect_tokens_no_attrs(|this| match kind { NonterminalKind::PatParam { .. } => this.parse_pat_no_top_alt(None), - NonterminalKind::PatWithOr { .. } => { - this.parse_pat_allow_top_alt(None, RecoverComma::No, RecoverColon::No, CommaRecoveryMode::EitherTupleOrPipe) - } + NonterminalKind::PatWithOr { .. } => this.parse_pat_allow_top_alt( + None, + RecoverComma::No, + RecoverColon::No, + CommaRecoveryMode::EitherTupleOrPipe, + ), _ => unreachable!(), })?) } @@ -139,13 +142,11 @@ impl<'a> Parser<'a> { ) } - NonterminalKind::Ty => { - token::NtTy(self.collect_tokens_no_attrs(|this| this.parse_no_question_mark_recover())?) - } + NonterminalKind::Ty => token::NtTy( + self.collect_tokens_no_attrs(|this| this.parse_no_question_mark_recover())?, + ), // this could be handled like a token, since it is one - NonterminalKind::Ident - if let Some((ident, is_raw)) = get_macro_ident(&self.token) => - { + NonterminalKind::Ident if let Some((ident, is_raw)) = get_macro_ident(&self.token) => { self.bump(); token::NtIdent(ident, is_raw) } diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index e3bcd945db716..962cecae4c550 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -595,7 +595,9 @@ impl<'a> Parser<'a> { } eat_semi = false; } - StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false, + StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => { + eat_semi = false + } } if eat_semi && self.eat(&token::Semi) { diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4f9e1d3fa3bca..1c8a82ed24a4e 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1954,23 +1954,17 @@ impl CheckAttrVisitor<'_> { | sym::target_feature ) && attr.meta_item_list().map_or(false, |list| list.is_empty()) { - format!( - "attribute `{}` with an empty list has no effect", - attr.name_or_empty() - ) + format!("attribute `{}` with an empty list has no effect", attr.name_or_empty()) } else if matches!( - attr.name_or_empty(), - sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect - ) && let Some(meta) = attr.meta_item_list() + attr.name_or_empty(), + sym::allow | sym::warn | sym::deny | sym::forbid | sym::expect + ) && let Some(meta) = attr.meta_item_list() && meta.len() == 1 && let Some(item) = meta[0].meta_item() && let MetaItemKind::NameValue(_) = &item.kind && item.path == sym::reason { - format!( - "attribute `{}` without any lints has no effect", - attr.name_or_empty() - ) + format!("attribute `{}` without any lints has no effect", attr.name_or_empty()) } else { return; }; diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index 0e04a2cfb11ad..1e8cfbd28a680 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -80,57 +80,56 @@ impl<'tcx> hir::itemlikevisit::ItemLikeVisitor<'tcx> for CheckConstTraitVisitor< /// of the trait being implemented; as those provided functions can be non-const. fn visit_item<'hir>(&mut self, item: &'hir hir::Item<'hir>) { let _: Option<_> = try { - if let hir::ItemKind::Impl(ref imp) = item.kind && let hir::Constness::Const = imp.constness { - let trait_def_id = imp.of_trait.as_ref()?.trait_def_id()?; - let ancestors = self - .tcx - .trait_def(trait_def_id) - .ancestors(self.tcx, item.def_id.to_def_id()) - .ok()?; - let mut to_implement = Vec::new(); - - for trait_item in self.tcx.associated_items(trait_def_id).in_definition_order() + if let hir::ItemKind::Impl(ref imp) = item.kind + && let hir::Constness::Const = imp.constness + { + let trait_def_id = imp.of_trait.as_ref()?.trait_def_id()?; + let ancestors = self + .tcx + .trait_def(trait_def_id) + .ancestors(self.tcx, item.def_id.to_def_id()) + .ok()?; + let mut to_implement = Vec::new(); + + for trait_item in self.tcx.associated_items(trait_def_id).in_definition_order() { + if let ty::AssocItem { + kind: ty::AssocKind::Fn, + defaultness, + def_id: trait_item_id, + .. + } = *trait_item { - if let ty::AssocItem { - kind: ty::AssocKind::Fn, - defaultness, - def_id: trait_item_id, - .. - } = *trait_item + // we can ignore functions that do not have default bodies: + // if those are unimplemented it will be catched by typeck. + if !defaultness.has_value() + || self.tcx.has_attr(trait_item_id, sym::default_method_body_is_const) { - // we can ignore functions that do not have default bodies: - // if those are unimplemented it will be catched by typeck. - if !defaultness.has_value() - || self - .tcx - .has_attr(trait_item_id, sym::default_method_body_is_const) - { - continue; - } - - let is_implemented = ancestors - .leaf_def(self.tcx, trait_item_id) - .map(|node_item| !node_item.defining_node.is_from_trait()) - .unwrap_or(false); - - if !is_implemented { - to_implement.push(self.tcx.item_name(trait_item_id).to_string()); - } + continue; } - } - // all nonconst trait functions (not marked with #[default_method_body_is_const]) - // must be implemented - if !to_implement.is_empty() { - self.tcx - .sess - .struct_span_err( - item.span, - "const trait implementations may not use non-const default functions", - ) - .note(&format!("`{}` not implemented", to_implement.join("`, `"))) - .emit(); + let is_implemented = ancestors + .leaf_def(self.tcx, trait_item_id) + .map(|node_item| !node_item.defining_node.is_from_trait()) + .unwrap_or(false); + + if !is_implemented { + to_implement.push(self.tcx.item_name(trait_item_id).to_string()); + } } + } + + // all nonconst trait functions (not marked with #[default_method_body_is_const]) + // must be implemented + if !to_implement.is_empty() { + self.tcx + .sess + .struct_span_err( + item.span, + "const trait implementations may not use non-const default functions", + ) + .note(&format!("`{}` not implemented", to_implement.join("`, `"))) + .emit(); + } } }; } diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index 5a1373ad1a218..96efe5c52e94d 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -148,9 +148,13 @@ fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(De } else if let Some((def_id, _)) = visitor.attr_main_fn { Some((def_id.to_def_id(), EntryFnType::Main)) } else { - if let Some(main_def) = tcx.resolutions(()).main_def && let Some(def_id) = main_def.opt_fn_def_id() { + if let Some(main_def) = tcx.resolutions(()).main_def + && let Some(def_id) = main_def.opt_fn_def_id() + { // non-local main imports are handled below - if let Some(def_id) = def_id.as_local() && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) { + if let Some(def_id) = def_id.as_local() + && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) + { tcx.sess .struct_span_err( tcx.def_span(def_id), @@ -221,7 +225,7 @@ fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) { err.note(¬e); } - if let Some(main_def) = tcx.resolutions(()).main_def && main_def.opt_fn_def_id().is_none(){ + if let Some(main_def) = tcx.resolutions(()).main_def && main_def.opt_fn_def_id().is_none() { // There is something at `crate::main`, but it is not a function definition. err.span_label(main_def.span, "non-function item at `crate::main` is found"); } diff --git a/compiler/rustc_passes/src/intrinsicck.rs b/compiler/rustc_passes/src/intrinsicck.rs index 027eac16bad30..b28c4c98ece9d 100644 --- a/compiler/rustc_passes/src/intrinsicck.rs +++ b/compiler/rustc_passes/src/intrinsicck.rs @@ -79,7 +79,9 @@ impl<'tcx> ExprVisitor<'tcx> { // Special-case transmuting from `typeof(function)` and // `Option` to present a clearer error. let from = unpack_option_like(self.tcx, from); - if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) && size_to == Pointer.size(&self.tcx) { + if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) + && size_to == Pointer.size(&self.tcx) + { struct_span_err!(self.tcx.sess, span, E0591, "can't transmute zero-sized type") .note(&format!("source type: {from}")) .note(&format!("target type: {to}")) @@ -505,9 +507,7 @@ impl<'tcx> Visitor<'tcx> for ExprVisitor<'tcx> { match expr.kind { hir::ExprKind::Path(ref qpath) => { let res = self.typeck_results.qpath_res(qpath, expr.hir_id); - if let Res::Def(DefKind::Fn, did) = res - && self.def_id_is_transmute(did) - { + if let Res::Def(DefKind::Fn, did) = res && self.def_id_is_transmute(did) { let typ = self.typeck_results.node_type(expr.hir_id); let sig = typ.fn_sig(self.tcx); let from = sig.inputs().skip_binder()[0]; diff --git a/compiler/rustc_span/src/source_map.rs b/compiler/rustc_span/src/source_map.rs index 95177102dcf86..73689ba947479 100644 --- a/compiler/rustc_span/src/source_map.rs +++ b/compiler/rustc_span/src/source_map.rs @@ -1031,11 +1031,11 @@ impl SourceMap { pub fn ensure_source_file_source_present(&self, source_file: Lrc) -> bool { source_file.add_external_src(|| { match source_file.name { - FileName::Real(ref name) if let Some(local_path) = name.local_path() => { - self.file_loader.read_file(local_path).ok() - } - _ => None, + FileName::Real(ref name) if let Some(local_path) = name.local_path() => { + self.file_loader.read_file(local_path).ok() } + _ => None, + } }) } diff --git a/compiler/rustc_trait_selection/src/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/on_unimplemented.rs index 38be28c07ff18..a2e5a8eae8a4d 100644 --- a/compiler/rustc_trait_selection/src/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/on_unimplemented.rs @@ -224,20 +224,22 @@ impl<'tcx> OnUnimplementedDirective { options.iter().filter_map(|(k, v)| v.as_ref().map(|v| (*k, v.to_owned()))).collect(); for command in self.subcommands.iter().chain(Some(self)).rev() { - if let Some(ref condition) = command.condition && !attr::eval_condition( - condition, - &tcx.sess.parse_sess, - Some(tcx.features()), - &mut |c| { - c.ident().map_or(false, |ident| { - let value = c.value_str().map(|s| { - OnUnimplementedFormatString(s).format(tcx, trait_ref, &options_map) - }); + if let Some(ref condition) = command.condition + && !attr::eval_condition( + condition, + &tcx.sess.parse_sess, + Some(tcx.features()), + &mut |c| { + c.ident().map_or(false, |ident| { + let value = c.value_str().map(|s| { + OnUnimplementedFormatString(s).format(tcx, trait_ref, &options_map) + }); - options.contains(&(ident.name, value)) - }) - }, - ) { + options.contains(&(ident.name, value)) + }) + }, + ) + { debug!("evaluate: skipping {:?} due to condition", command); continue; } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 4135fbca06099..d22b2fdc1409f 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -580,7 +580,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { subobligations, ); if let Ok(eval_rslt) = res - && (eval_rslt == EvaluatedToOk || eval_rslt == EvaluatedToOkModuloRegions) + && (eval_rslt == EvaluatedToOk + || eval_rslt == EvaluatedToOkModuloRegions) && let Some(key) = ProjectionCacheKey::from_poly_projection_predicate( self, data, diff --git a/compiler/rustc_typeck/src/check/check.rs b/compiler/rustc_typeck/src/check/check.rs index e57d55fdc2377..fedbba844a347 100644 --- a/compiler/rustc_typeck/src/check/check.rs +++ b/compiler/rustc_typeck/src/check/check.rs @@ -286,8 +286,8 @@ pub(super) fn check_fn<'a, 'tcx>( && let ItemKind::Fn(_, ref generics, _) = item.kind && !generics.params.is_empty() { - sess.span_err(span, "should have no type parameters"); - } + sess.span_err(span, "should have no type parameters"); + } } else { let span = sess.source_map().guess_head_span(span); sess.span_err(span, "function should have one argument"); @@ -322,11 +322,11 @@ pub(super) fn check_fn<'a, 'tcx>( && let ItemKind::Fn(_, ref generics, _) = item.kind && !generics.params.is_empty() { - sess.span_err( - span, + sess.span_err( + span, "`#[alloc_error_handler]` function should have no type parameters", - ); - } + ); + } } else { let span = sess.source_map().guess_head_span(span); sess.span_err(span, "function should have one argument"); @@ -1148,13 +1148,13 @@ pub(super) fn check_packed(tcx: TyCtxt<'_>, sp: Span, def: ty::AdtDef<'_>) { && let Some(repr_pack) = repr.pack && pack as u64 != repr_pack.bytes() { - struct_span_err!( - tcx.sess, - sp, - E0634, - "type has conflicting packed representation hints" - ) - .emit(); + struct_span_err!( + tcx.sess, + sp, + E0634, + "type has conflicting packed representation hints" + ) + .emit(); } } } @@ -1400,7 +1400,7 @@ fn display_discriminant_value<'tcx>( && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node && evaluated != *lit_value { - return format!("`{}` (overflowed from `{}`)", evaluated, lit_value); + return format!("`{}` (overflowed from `{}`)", evaluated, lit_value); } } format!("`{}`", evaluated) diff --git a/compiler/rustc_typeck/src/check/coercion.rs b/compiler/rustc_typeck/src/check/coercion.rs index c0eda02a99967..b0d1c5bf7f560 100644 --- a/compiler/rustc_typeck/src/check/coercion.rs +++ b/compiler/rustc_typeck/src/check/coercion.rs @@ -1703,7 +1703,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { && let ty = >::ast_ty_to_ty(fcx, ty) && let ty::Dynamic(..) = ty.kind() { - return true; + return true; } false } diff --git a/compiler/rustc_typeck/src/check/demand.rs b/compiler/rustc_typeck/src/check/demand.rs index 58e5c9315c30c..7bfbc74793b7f 100644 --- a/compiler/rustc_typeck/src/check/demand.rs +++ b/compiler/rustc_typeck/src/check/demand.rs @@ -609,29 +609,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let Ok(src) = sm.span_to_snippet(sp) && replace_prefix(&src, "b\"", "\"").is_some() { - let pos = sp.lo() + BytePos(1); - return Some(( - sp.with_hi(pos), - "consider removing the leading `b`".to_string(), - String::new(), - Applicability::MachineApplicable, - true, - )); - } - } + let pos = sp.lo() + BytePos(1); + return Some(( + sp.with_hi(pos), + "consider removing the leading `b`".to_string(), + String::new(), + Applicability::MachineApplicable, + true, + )); + } + } (&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => { if let hir::ExprKind::Lit(_) = expr.kind && let Ok(src) = sm.span_to_snippet(sp) && replace_prefix(&src, "\"", "b\"").is_some() { - return Some(( - sp.shrink_to_lo(), - "consider adding a leading `b`".to_string(), - "b".to_string(), - Applicability::MachineApplicable, - true, - )); - + return Some(( + sp.shrink_to_lo(), + "consider adding a leading `b`".to_string(), + "b".to_string(), + Applicability::MachineApplicable, + true, + )); } } _ => {} diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs index e3439a6f1d963..c8b74290a7cdd 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs @@ -1164,9 +1164,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut user_self_ty = None; let mut is_alias_variant_ctor = false; match res { - Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) - if let Some(self_ty) = self_ty => - { + Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) if let Some(self_ty) = self_ty => { let adt_def = self_ty.ty_adt_def().unwrap(); user_self_ty = Some(UserSelfTy { impl_def_id: adt_def.did(), self_ty }); is_alias_variant_ctor = true; diff --git a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs index d336573c254f8..d84520899c938 100644 --- a/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs +++ b/compiler/rustc_typeck/src/check/fn_ctxt/checks.rs @@ -1096,18 +1096,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } result_code } - let self_: ty::subst::GenericArg<'_> = match &*unpeel_to_top(error.obligation.cause.clone_code()) { - ObligationCauseCode::BuiltinDerivedObligation(code) | - ObligationCauseCode::ImplDerivedObligation(code) | - ObligationCauseCode::DerivedObligation(code) => { - code.parent_trait_pred.self_ty().skip_binder().into() - } - _ if let ty::PredicateKind::Trait(predicate) = - error.obligation.predicate.kind().skip_binder() => { + let self_: ty::subst::GenericArg<'_> = + match &*unpeel_to_top(error.obligation.cause.clone_code()) { + ObligationCauseCode::BuiltinDerivedObligation(code) + | ObligationCauseCode::ImplDerivedObligation(code) + | ObligationCauseCode::DerivedObligation(code) => { + code.parent_trait_pred.self_ty().skip_binder().into() + } + _ if let ty::PredicateKind::Trait(predicate) = + error.obligation.predicate.kind().skip_binder() => + { predicate.self_ty().into() } - _ => continue, - }; + _ => continue, + }; let self_ = self.resolve_vars_if_possible(self_); // Collect the argument position for all arguments that could have caused this diff --git a/compiler/rustc_typeck/src/check/method/probe.rs b/compiler/rustc_typeck/src/check/method/probe.rs index 4e1645adca5d3..1730ad3fb592f 100644 --- a/compiler/rustc_typeck/src/check/method/probe.rs +++ b/compiler/rustc_typeck/src/check/method/probe.rs @@ -635,8 +635,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { // will still match the original object type, but it won't pollute our // type variables in any form, so just do that! let (QueryResponse { value: generalized_self_ty, .. }, _ignored_var_values) = - self.fcx - .instantiate_canonical_with_fresh_inference_vars(self.span, self_ty); + self.fcx.instantiate_canonical_with_fresh_inference_vars(self.span, self_ty); self.assemble_inherent_candidates_from_object(generalized_self_ty); self.assemble_inherent_impl_candidates_for_type(p.def_id()); diff --git a/compiler/rustc_typeck/src/check/method/suggest.rs b/compiler/rustc_typeck/src/check/method/suggest.rs index bf7db8221a26f..57873fa444fe3 100644 --- a/compiler/rustc_typeck/src/check/method/suggest.rs +++ b/compiler/rustc_typeck/src/check/method/suggest.rs @@ -1597,13 +1597,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (self.tcx.mk_diagnostic_item(*rcvr_ty, sym::Arc), "Arc::new"), (self.tcx.mk_diagnostic_item(*rcvr_ty, sym::Rc), "Rc::new"), ] { - if let Some(new_rcvr_t) = *rcvr_ty && let Ok(pick) = self.lookup_probe( - span, - item_name, - new_rcvr_t, - rcvr, - crate::check::method::probe::ProbeScope::AllTraits, - ) { + if let Some(new_rcvr_t) = *rcvr_ty + && let Ok(pick) = self.lookup_probe( + span, + item_name, + new_rcvr_t, + rcvr, + crate::check::method::probe::ProbeScope::AllTraits, + ) + { debug!("try_alt_rcvr: pick candidate {:?}", pick); let did = Some(pick.item.container.id()); // We don't want to suggest a container type when the missing diff --git a/compiler/rustc_typeck/src/check/pat.rs b/compiler/rustc_typeck/src/check/pat.rs index 1c4fbbbb9bfaf..6495f17e2a4f9 100644 --- a/compiler/rustc_typeck/src/check/pat.rs +++ b/compiler/rustc_typeck/src/check/pat.rs @@ -690,23 +690,23 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let Some(mt) = self.shallow_resolve(expected).builtin_deref(true) && let ty::Dynamic(..) = mt.ty.kind() { - // This is "x = SomeTrait" being reduced from - // "let &x = &SomeTrait" or "let box x = Box", an error. - let type_str = self.ty_to_string(expected); - let mut err = struct_span_err!( - self.tcx.sess, - span, - E0033, - "type `{}` cannot be dereferenced", - type_str - ); - err.span_label(span, format!("type `{}` cannot be dereferenced", type_str)); - if self.tcx.sess.teach(&err.get_code().unwrap()) { - err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ); - } - err.emit(); - return false; - } + // This is "x = SomeTrait" being reduced from + // "let &x = &SomeTrait" or "let box x = Box", an error. + let type_str = self.ty_to_string(expected); + let mut err = struct_span_err!( + self.tcx.sess, + span, + E0033, + "type `{}` cannot be dereferenced", + type_str + ); + err.span_label(span, format!("type `{}` cannot be dereferenced", type_str)); + if self.tcx.sess.teach(&err.get_code().unwrap()) { + err.note(CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ); + } + err.emit(); + return false; + } true } @@ -1363,7 +1363,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (Some(mut err), None) => { err.emit(); } - (None, None) if let Some(mut err) = + (None, None) + if let Some(mut err) = self.error_tuple_variant_index_shorthand(variant, pat, fields) => { err.emit(); diff --git a/compiler/rustc_typeck/src/check/writeback.rs b/compiler/rustc_typeck/src/check/writeback.rs index 16ffabb76a515..c72f84c0f7a5e 100644 --- a/compiler/rustc_typeck/src/check/writeback.rs +++ b/compiler/rustc_typeck/src/check/writeback.rs @@ -176,7 +176,8 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { } } hir::ExprKind::AssignOp(..) - if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) => + if let Some(a) = + typeck_results.adjustments_mut().get_mut(lhs.hir_id) => { a.pop(); } diff --git a/compiler/rustc_typeck/src/collect.rs b/compiler/rustc_typeck/src/collect.rs index 6a4c5d4a6c7ea..63700ff03cef0 100644 --- a/compiler/rustc_typeck/src/collect.rs +++ b/compiler/rustc_typeck/src/collect.rs @@ -202,10 +202,8 @@ crate fn placeholder_type_error<'tcx>( Node::Item(&hir::Item { kind: hir::ItemKind::Const(..) | hir::ItemKind::Static(..), .. - }) | Node::TraitItem(&hir::TraitItem { - kind: hir::TraitItemKind::Const(..), - .. - }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. }) + }) | Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Const(..), .. }) + | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Const(..), .. }) ); } @@ -3279,10 +3277,7 @@ fn should_inherit_track_caller(tcx: TyCtxt<'_>, def_id: DefId) -> bool { && let ty::AssocItemContainer::ImplContainer(_) = impl_item.container && let Some(trait_item) = impl_item.trait_item_def_id { - return tcx - .codegen_fn_attrs(trait_item) - .flags - .intersects(CodegenFnAttrFlags::TRACK_CALLER); + return tcx.codegen_fn_attrs(trait_item).flags.intersects(CodegenFnAttrFlags::TRACK_CALLER); } false diff --git a/compiler/rustc_typeck/src/collect/type_of.rs b/compiler/rustc_typeck/src/collect/type_of.rs index d422f355ad3a4..48671591eaa19 100644 --- a/compiler/rustc_typeck/src/collect/type_of.rs +++ b/compiler/rustc_typeck/src/collect/type_of.rs @@ -337,8 +337,9 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { icx.to_ty(ty) } } - ItemKind::TyAlias(self_ty, _) - | ItemKind::Impl(hir::Impl { self_ty, .. }) => icx.to_ty(self_ty), + ItemKind::TyAlias(self_ty, _) | ItemKind::Impl(hir::Impl { self_ty, .. }) => { + icx.to_ty(self_ty) + } ItemKind::Fn(..) => { let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id()); tcx.mk_fn_def(def_id.to_def_id(), substs) @@ -352,7 +353,11 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { find_opaque_ty_constraints(tcx, def_id) } // Opaque types desugared from `impl Trait`. - ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(owner) | hir::OpaqueTyOrigin::AsyncFn(owner), .. }) => { + ItemKind::OpaqueTy(OpaqueTy { + origin: + hir::OpaqueTyOrigin::FnReturn(owner) | hir::OpaqueTyOrigin::AsyncFn(owner), + .. + }) => { let concrete_ty = tcx .mir_borrowck(owner) .concrete_opaque_types @@ -366,9 +371,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { owner, def_id, ), ); - if let Some(_) = - tcx.typeck(owner).tainted_by_errors - { + if let Some(_) = tcx.typeck(owner).tainted_by_errors { // Some error in the // owner fn prevented us from populating // the `concrete_opaque_types` table. @@ -424,7 +427,9 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { Node::Field(field) => icx.to_ty(field.ty), - Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => tcx.typeck(def_id).node_type(hir_id), + Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => { + tcx.typeck(def_id).node_type(hir_id) + } Node::AnonConst(_) if let Some(param) = tcx.opt_const_param_of(def_id) => { // We defer to `type_of` of the corresponding parameter @@ -462,44 +467,40 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { tcx.typeck(def_id).node_type(hir_id) } - Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => tcx - .adt_def(tcx.hir().get_parent_item(hir_id)) - .repr() - .discr_type() - .to_ty(tcx), - - Node::TraitRef(trait_ref @ &TraitRef { - path, .. - }) if let Some((binding, seg)) = - path - .segments - .iter() - .find_map(|seg| { - seg.args?.bindings - .iter() - .find_map(|binding| if binding.opt_const()?.hir_id == hir_id { + Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => { + tcx.adt_def(tcx.hir().get_parent_item(hir_id)).repr().discr_type().to_ty(tcx) + } + + Node::TraitRef(trait_ref @ &TraitRef { path, .. }) + if let Some((binding, seg)) = path.segments.iter().find_map(|seg| { + seg.args?.bindings.iter().find_map(|binding| { + if binding.opt_const()?.hir_id == hir_id { Some((binding, seg)) - } else { + } else { None - }) - }) => + } + }) + }) => { - let Some(trait_def_id) = trait_ref.trait_def_id() else { + let Some(trait_def_id) = trait_ref.trait_def_id() else { return tcx.ty_error_with_message(DUMMY_SP, "Could not find trait"); }; - let assoc_items = tcx.associated_items(trait_def_id); - let assoc_item = assoc_items.find_by_name_and_kind( - tcx, binding.ident, ty::AssocKind::Const, def_id.to_def_id(), - ); - if let Some(assoc_item) = assoc_item { - tcx.type_of(assoc_item.def_id) - } else { - // FIXME(associated_const_equality): add a useful error message here. - tcx.ty_error_with_message( - DUMMY_SP, - "Could not find associated const on trait", - ) - } + let assoc_items = tcx.associated_items(trait_def_id); + let assoc_item = assoc_items.find_by_name_and_kind( + tcx, + binding.ident, + ty::AssocKind::Const, + def_id.to_def_id(), + ); + if let Some(assoc_item) = assoc_item { + tcx.type_of(assoc_item.def_id) + } else { + // FIXME(associated_const_equality): add a useful error message here. + tcx.ty_error_with_message( + DUMMY_SP, + "Could not find associated const on trait", + ) + } } Node::GenericParam(&GenericParam { @@ -508,8 +509,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { .. }) if ct.hir_id == hir_id => tcx.type_of(tcx.hir().local_def_id(param_hir_id)), - x => - tcx.ty_error_with_message( + x => tcx.ty_error_with_message( DUMMY_SP, &format!("unexpected const parent in type_of(): {x:?}"), ),