diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 8ad33749f34..fc34b288933 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -1184,10 +1184,13 @@ impl Scalar { #[inline] pub fn is_bool(&self) -> bool { use Integer::*; - matches!(self, Scalar::Initialized { - value: Primitive::Int(I8, false), - valid_range: WrappingRange { start: 0, end: 1 } - }) + matches!( + self, + Scalar::Initialized { + value: Primitive::Int(I8, false), + valid_range: WrappingRange { start: 0, end: 1 } + } + ) } /// Get the primitive representation of this type, ignoring the valid range and whether the diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index dded18fce0a..923fd65dcca 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -828,15 +828,18 @@ impl<'hir> LoweringContext<'_, 'hir> { span, Some(Arc::clone(&self.allow_gen_future)), ); - self.lower_attrs(inner_hir_id, &[Attribute { - kind: AttrKind::Normal(ptr::P(NormalAttr::from_ident(Ident::new( - sym::track_caller, - span, - )))), - id: self.tcx.sess.psess.attr_id_generator.mk_attr_id(), - style: AttrStyle::Outer, - span: unstable_span, - }]); + self.lower_attrs( + inner_hir_id, + &[Attribute { + kind: AttrKind::Normal(ptr::P(NormalAttr::from_ident(Ident::new( + sym::track_caller, + span, + )))), + id: self.tcx.sess.psess.attr_id_generator.mk_attr_id(), + style: AttrStyle::Outer, + span: unstable_span, + }], + ); } } diff --git a/compiler/rustc_ast_lowering/src/format.rs b/compiler/rustc_ast_lowering/src/format.rs index 22aa1e6fc20..07b94dbc2ae 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -362,13 +362,16 @@ fn make_format_spec<'hir>( debug_hex, } = &placeholder.format_options; let fill = ctx.expr_char(sp, fill.unwrap_or(' ')); - let align = - ctx.expr_lang_item_type_relative(sp, hir::LangItem::FormatAlignment, match alignment { + let align = ctx.expr_lang_item_type_relative( + sp, + hir::LangItem::FormatAlignment, + match alignment { Some(FormatAlignment::Left) => sym::Left, Some(FormatAlignment::Right) => sym::Right, Some(FormatAlignment::Center) => sym::Center, None => sym::Unknown, - }); + }, + ); // This needs to match `Flag` in library/core/src/fmt/rt.rs. let flags: u32 = ((sign == Some(FormatSign::Plus)) as u32) | ((sign == Some(FormatSign::Minus)) as u32) << 1 diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index c96110fee61..11d60b9348d 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -304,12 +304,15 @@ impl<'hir> LoweringContext<'_, 'hir> { ); this.arena.alloc(this.ty(span, hir::TyKind::Err(guar))) } - Some(ty) => this.lower_ty(ty, ImplTraitContext::OpaqueTy { - origin: hir::OpaqueTyOrigin::TyAlias { - parent: this.local_def_id(id), - in_assoc_ty: false, + Some(ty) => this.lower_ty( + ty, + ImplTraitContext::OpaqueTy { + origin: hir::OpaqueTyOrigin::TyAlias { + parent: this.local_def_id(id), + in_assoc_ty: false, + }, }, - }), + ), }, ); hir::ItemKind::TyAlias(ty, generics) @@ -966,12 +969,15 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::ImplItemKind::Type(ty) } Some(ty) => { - let ty = this.lower_ty(ty, ImplTraitContext::OpaqueTy { - origin: hir::OpaqueTyOrigin::TyAlias { - parent: this.local_def_id(i.id), - in_assoc_ty: true, + let ty = this.lower_ty( + ty, + ImplTraitContext::OpaqueTy { + origin: hir::OpaqueTyOrigin::TyAlias { + parent: this.local_def_id(i.id), + in_assoc_ty: true, + }, }, - }); + ); hir::ImplItemKind::Type(ty) } }, @@ -1152,10 +1158,13 @@ impl<'hir> LoweringContext<'_, 'hir> { pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId { self.lower_body(|this| { - (&[], match expr { - Some(expr) => this.lower_expr_mut(expr), - None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")), - }) + ( + &[], + match expr { + Some(expr) => this.lower_expr_mut(expr), + None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")), + }, + ) }) } diff --git a/compiler/rustc_attr_parsing/src/session_diagnostics.rs b/compiler/rustc_attr_parsing/src/session_diagnostics.rs index b1d8ec49774..92bc2a8aeb0 100644 --- a/compiler/rustc_attr_parsing/src/session_diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/session_diagnostics.rs @@ -204,21 +204,27 @@ pub(crate) struct UnsupportedLiteral { impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for UnsupportedLiteral { fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> { - let mut diag = Diag::new(dcx, level, match self.reason { - UnsupportedLiteralReason::Generic => fluent::attr_parsing_unsupported_literal_generic, - UnsupportedLiteralReason::CfgString => { - fluent::attr_parsing_unsupported_literal_cfg_string - } - UnsupportedLiteralReason::CfgBoolean => { - fluent::attr_parsing_unsupported_literal_cfg_boolean - } - UnsupportedLiteralReason::DeprecatedString => { - fluent::attr_parsing_unsupported_literal_deprecated_string - } - UnsupportedLiteralReason::DeprecatedKvPair => { - fluent::attr_parsing_unsupported_literal_deprecated_kv_pair - } - }); + let mut diag = Diag::new( + dcx, + level, + match self.reason { + UnsupportedLiteralReason::Generic => { + fluent::attr_parsing_unsupported_literal_generic + } + UnsupportedLiteralReason::CfgString => { + fluent::attr_parsing_unsupported_literal_cfg_string + } + UnsupportedLiteralReason::CfgBoolean => { + fluent::attr_parsing_unsupported_literal_cfg_boolean + } + UnsupportedLiteralReason::DeprecatedString => { + fluent::attr_parsing_unsupported_literal_deprecated_string + } + UnsupportedLiteralReason::DeprecatedKvPair => { + fluent::attr_parsing_unsupported_literal_deprecated_kv_pair + } + }, + ); diag.span(self.span); diag.code(E0565); if self.is_bytestr { diff --git a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs index 475897d8f3e..30b0a358580 100644 --- a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs @@ -156,24 +156,25 @@ pub(crate) trait TypeOpInfo<'tcx> { return; }; - let placeholder_region = ty::Region::new_placeholder(tcx, ty::Placeholder { - universe: adjusted_universe.into(), - bound: placeholder.bound, - }); + let placeholder_region = ty::Region::new_placeholder( + tcx, + ty::Placeholder { universe: adjusted_universe.into(), bound: placeholder.bound }, + ); - let error_region = - if let RegionElement::PlaceholderRegion(error_placeholder) = error_element { - let adjusted_universe = - error_placeholder.universe.as_u32().checked_sub(base_universe.as_u32()); - adjusted_universe.map(|adjusted| { - ty::Region::new_placeholder(tcx, ty::Placeholder { - universe: adjusted.into(), - bound: error_placeholder.bound, - }) - }) - } else { - None - }; + let error_region = if let RegionElement::PlaceholderRegion(error_placeholder) = + error_element + { + let adjusted_universe = + error_placeholder.universe.as_u32().checked_sub(base_universe.as_u32()); + adjusted_universe.map(|adjusted| { + ty::Region::new_placeholder( + tcx, + ty::Placeholder { universe: adjusted.into(), bound: error_placeholder.bound }, + ) + }) + } else { + None + }; debug!(?placeholder_region); diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index b3fb2cd938b..6269728e67f 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -147,10 +147,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { span, desired_action.as_noun(), partially_str, - self.describe_place_with_options(moved_place, DescribePlaceOpt { - including_downcast: true, - including_tuple_field: true, - }), + self.describe_place_with_options( + moved_place, + DescribePlaceOpt { including_downcast: true, including_tuple_field: true }, + ), ); let reinit_spans = maybe_reinitialized_locations @@ -280,10 +280,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { self.suggest_adding_bounds(&mut err, ty, copy_did, span); } - let opt_name = self.describe_place_with_options(place.as_ref(), DescribePlaceOpt { - including_downcast: true, - including_tuple_field: true, - }); + let opt_name = self.describe_place_with_options( + place.as_ref(), + DescribePlaceOpt { including_downcast: true, including_tuple_field: true }, + ); let note_msg = match opt_name { Some(name) => format!("`{name}`"), None => "value".to_owned(), @@ -765,17 +765,17 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } let spans: Vec<_> = spans_set.into_iter().collect(); - let (name, desc) = match self.describe_place_with_options(moved_place, DescribePlaceOpt { - including_downcast: true, - including_tuple_field: true, - }) { + let (name, desc) = match self.describe_place_with_options( + moved_place, + DescribePlaceOpt { including_downcast: true, including_tuple_field: true }, + ) { Some(name) => (format!("`{name}`"), format!("`{name}` ")), None => ("the variable".to_string(), String::new()), }; - let path = match self.describe_place_with_options(used_place, DescribePlaceOpt { - including_downcast: true, - including_tuple_field: true, - }) { + let path = match self.describe_place_with_options( + used_place, + DescribePlaceOpt { including_downcast: true, including_tuple_field: true }, + ) { Some(name) => format!("`{name}`"), None => "value".to_string(), }; diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index 01ed0464c8a..860c7c267ea 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -304,10 +304,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { /// End-user visible description of `place` if one can be found. /// If the place is a temporary for instance, `None` will be returned. pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option { - self.describe_place_with_options(place_ref, DescribePlaceOpt { - including_downcast: false, - including_tuple_field: true, - }) + self.describe_place_with_options( + place_ref, + DescribePlaceOpt { including_downcast: false, including_tuple_field: true }, + ) } /// End-user visible description of `place` if one can be found. If the place is a temporary diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 3c4e4c29197..b809b40a399 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -1100,12 +1100,15 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let closure_ty = Ty::new_closure( tcx, closure_def_id.to_def_id(), - ty::ClosureArgs::new(tcx, ty::ClosureArgsParts { - parent_args: args.parent_args(), - closure_kind_ty: args.kind_ty(), - tupled_upvars_ty: args.tupled_upvars_ty(), - closure_sig_as_fn_ptr_ty, - }) + ty::ClosureArgs::new( + tcx, + ty::ClosureArgsParts { + parent_args: args.parent_args(), + closure_kind_ty: args.kind_ty(), + tupled_upvars_ty: args.tupled_upvars_ty(), + closure_sig_as_fn_ptr_ty, + }, + ) .args, ); diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 8ddc8add675..53cf4f34ae7 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -1668,9 +1668,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> { match elem { ProjectionElem::Deref => match place_ty.ty.kind() { ty::Ref(..) | ty::RawPtr(..) => { - self.move_errors.push(MoveError::new(place, location, BorrowedContent { - target_place: place_ref.project_deeper(&[elem], tcx), - })); + self.move_errors.push(MoveError::new( + place, + location, + BorrowedContent { + target_place: place_ref.project_deeper(&[elem], tcx), + }, + )); return; } ty::Adt(adt, _) => { diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index 5440d451ec8..9c19f8b3ad8 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -166,10 +166,10 @@ impl<'tcx> RegionInferenceContext<'tcx> { // FIXME(oli-obk): collect multiple spans for better diagnostics down the road. prev.span = prev.span.substitute_dummy(concrete_type.span); } else { - result.insert(opaque_type_key.def_id, OpaqueHiddenType { - ty, - span: concrete_type.span, - }); + result.insert( + opaque_type_key.def_id, + OpaqueHiddenType { ty, span: concrete_type.span }, + ); } // Check that all opaque types have the same region parameters if they have the same diff --git a/compiler/rustc_borrowck/src/type_check/input_output.rs b/compiler/rustc_borrowck/src/type_check/input_output.rs index 1f2ec168f03..f70b17e3362 100644 --- a/compiler/rustc_borrowck/src/type_check/input_output.rs +++ b/compiler/rustc_borrowck/src/type_check/input_output.rs @@ -75,17 +75,20 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let output_ty = Ty::new_coroutine( self.tcx(), self.tcx().coroutine_for_closure(mir_def_id), - ty::CoroutineArgs::new(self.tcx(), ty::CoroutineArgsParts { - parent_args: args.parent_args(), - kind_ty: Ty::from_coroutine_closure_kind(self.tcx(), args.kind()), - return_ty: user_provided_sig.output(), - tupled_upvars_ty, - // For async closures, none of these can be annotated, so just fill - // them with fresh ty vars. - resume_ty: next_ty_var(), - yield_ty: next_ty_var(), - witness: next_ty_var(), - }) + ty::CoroutineArgs::new( + self.tcx(), + ty::CoroutineArgsParts { + parent_args: args.parent_args(), + kind_ty: Ty::from_coroutine_closure_kind(self.tcx(), args.kind()), + return_ty: user_provided_sig.output(), + tupled_upvars_ty, + // For async closures, none of these can be annotated, so just fill + // them with fresh ty vars. + resume_ty: next_ty_var(), + yield_ty: next_ty_var(), + witness: next_ty_var(), + }, + ) .args, ); diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 002f6e36cd8..26a5d438edb 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -411,10 +411,10 @@ impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> { } else { self.typeck.ascribe_user_type( constant.const_.ty(), - ty::UserType::new(ty::UserTypeKind::TypeOf(uv.def, UserArgs { - args: uv.args, - user_self_ty: None, - })), + ty::UserType::new(ty::UserTypeKind::TypeOf( + uv.def, + UserArgs { args: uv.args, user_self_ty: None }, + )), locations.span(self.typeck.body), ); } @@ -1642,10 +1642,11 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } &Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, ty) => { - let trait_ref = - ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Sized, Some(span)), [ - ty, - ]); + let trait_ref = ty::TraitRef::new( + tcx, + tcx.require_lang_item(LangItem::Sized, Some(span)), + [ty], + ); self.prove_trait_ref( trait_ref, @@ -1659,10 +1660,11 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { Rvalue::ShallowInitBox(operand, ty) => { self.check_operand(operand, location); - let trait_ref = - ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Sized, Some(span)), [ - *ty, - ]); + let trait_ref = ty::TraitRef::new( + tcx, + tcx.require_lang_item(LangItem::Sized, Some(span)), + [*ty], + ); self.prove_trait_ref( trait_ref, diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 26af86c0cdd..eb0079a3883 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -620,10 +620,10 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { let ty = tcx .typeck(self.mir_def) .node_type(tcx.local_def_id_to_hir_id(self.mir_def)); - let args = InlineConstArgs::new(tcx, InlineConstArgsParts { - parent_args: identity_args, - ty, - }) + let args = InlineConstArgs::new( + tcx, + InlineConstArgsParts { parent_args: identity_args, ty }, + ) .args; let args = self.infcx.replace_free_regions_with_nll_infer_vars(FR, args); DefiningTy::InlineConst(self.mir_def.to_def_id(), args) diff --git a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs index cffc4978601..78bf2195975 100644 --- a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs +++ b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs @@ -67,10 +67,11 @@ fn generate_handler(cx: &ExtCtxt<'_>, handler: Ident, span: Span, sig_span: Span let layout_new = cx.std_path(&[sym::alloc, sym::Layout, sym::from_size_align_unchecked]); let layout_new = cx.expr_path(cx.path(span, layout_new)); - let layout = cx.expr_call(span, layout_new, thin_vec![ - cx.expr_ident(span, size), - cx.expr_ident(span, align) - ]); + let layout = cx.expr_call( + span, + layout_new, + thin_vec![cx.expr_ident(span, size), cx.expr_ident(span, align)], + ); let call = cx.expr_call_ident(sig_span, handler, thin_vec![layout]); diff --git a/compiler/rustc_builtin_macros/src/autodiff.rs b/compiler/rustc_builtin_macros/src/autodiff.rs index 8960cf6ab59..24c54edd705 100644 --- a/compiler/rustc_builtin_macros/src/autodiff.rs +++ b/compiler/rustc_builtin_macros/src/autodiff.rs @@ -406,19 +406,21 @@ mod llvm_enzyme { let unsf_expr = ecx.expr_block(P(unsf_block)); let blackbox_call_expr = ecx.expr_path(ecx.path(span, blackbox_path)); let primal_call = gen_primal_call(ecx, span, primal, idents); - let black_box_primal_call = - ecx.expr_call(new_decl_span, blackbox_call_expr.clone(), thin_vec![ - primal_call.clone() - ]); + let black_box_primal_call = ecx.expr_call( + new_decl_span, + blackbox_call_expr.clone(), + thin_vec![primal_call.clone()], + ); let tup_args = new_names .iter() .map(|arg| ecx.expr_path(ecx.path_ident(span, Ident::from_str(arg)))) .collect(); - let black_box_remaining_args = - ecx.expr_call(sig_span, blackbox_call_expr.clone(), thin_vec![ - ecx.expr_tuple(sig_span, tup_args) - ]); + let black_box_remaining_args = ecx.expr_call( + sig_span, + blackbox_call_expr.clone(), + thin_vec![ecx.expr_tuple(sig_span, tup_args)], + ); let mut body = ecx.block(span, ThinVec::new()); body.stmts.push(ecx.stmt_semi(unsf_expr)); @@ -532,8 +534,11 @@ mod llvm_enzyme { return body; } [arg] => { - ret = ecx - .expr_call(new_decl_span, blackbox_call_expr.clone(), thin_vec![arg.clone()]); + ret = ecx.expr_call( + new_decl_span, + blackbox_call_expr.clone(), + thin_vec![arg.clone()], + ); } args => { let ret_tuple: P = ecx.expr_tuple(span, args.into()); diff --git a/compiler/rustc_builtin_macros/src/deriving/clone.rs b/compiler/rustc_builtin_macros/src/deriving/clone.rs index 78f50ba8d29..c3656e8244f 100644 --- a/compiler/rustc_builtin_macros/src/deriving/clone.rs +++ b/compiler/rustc_builtin_macros/src/deriving/clone.rs @@ -114,10 +114,13 @@ fn cs_clone_simple( // type parameters. } else { // let _: AssertParamIsClone; - super::assert_ty_bounds(cx, &mut stmts, field.ty.clone(), field.span, &[ - sym::clone, - sym::AssertParamIsClone, - ]); + super::assert_ty_bounds( + cx, + &mut stmts, + field.ty.clone(), + field.span, + &[sym::clone, sym::AssertParamIsClone], + ); } } }; @@ -126,10 +129,13 @@ fn cs_clone_simple( // Just a single assertion for unions, that the union impls `Copy`. // let _: AssertParamIsCopy; let self_ty = cx.ty_path(cx.path_ident(trait_span, Ident::with_dummy_span(kw::SelfUpper))); - super::assert_ty_bounds(cx, &mut stmts, self_ty, trait_span, &[ - sym::clone, - sym::AssertParamIsCopy, - ]); + super::assert_ty_bounds( + cx, + &mut stmts, + self_ty, + trait_span, + &[sym::clone, sym::AssertParamIsCopy], + ); } else { match *substr.fields { StaticStruct(vdata, ..) => { diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs index 5790350203a..eca79e4dc48 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs @@ -65,10 +65,13 @@ fn cs_total_eq_assert( // Already produced an assertion for this type. } else { // let _: AssertParamIsEq; - super::assert_ty_bounds(cx, &mut stmts, field.ty.clone(), field.span, &[ - sym::cmp, - sym::AssertParamIsEq, - ]); + super::assert_ty_bounds( + cx, + &mut stmts, + field.ty.clone(), + field.span, + &[sym::cmp, sym::AssertParamIsEq], + ); } } }; diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index 2388b7dd648..1fe567e23f4 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -108,30 +108,38 @@ fn default_enum_substructure( Ok(default_variant) => { // We now know there is exactly one unit variant with exactly one `#[default]` attribute. match &default_variant.data { - VariantData::Unit(_) => cx.expr_path(cx.path(default_variant.span, vec![ - Ident::new(kw::SelfUpper, default_variant.span), - default_variant.ident, - ])), + VariantData::Unit(_) => cx.expr_path(cx.path( + default_variant.span, + vec![Ident::new(kw::SelfUpper, default_variant.span), default_variant.ident], + )), VariantData::Struct { fields, .. } => { // This only happens if `#![feature(default_field_values)]`. We have validated // all fields have default values in the definition. let default_fields = fields .iter() .map(|field| { - cx.field_imm(field.span, field.ident.unwrap(), match &field.default { - // We use `Default::default()`. - None => default_call(cx, field.span), - // We use the field default const expression. - Some(val) => { - cx.expr(val.value.span, ast::ExprKind::ConstBlock(val.clone())) - } - }) + cx.field_imm( + field.span, + field.ident.unwrap(), + match &field.default { + // We use `Default::default()`. + None => default_call(cx, field.span), + // We use the field default const expression. + Some(val) => cx.expr( + val.value.span, + ast::ExprKind::ConstBlock(val.clone()), + ), + }, + ) }) .collect(); - let path = cx.path(default_variant.span, vec![ - Ident::new(kw::SelfUpper, default_variant.span), - default_variant.ident, - ]); + let path = cx.path( + default_variant.span, + vec![ + Ident::new(kw::SelfUpper, default_variant.span), + default_variant.ident, + ], + ); cx.expr_struct(default_variant.span, path, default_fields) } // Logic error in `extract_default_variant`. diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 0631c5a80fc..234ec858216 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -1220,10 +1220,12 @@ impl<'a> MethodDef<'a> { let discr_let_stmts: ThinVec<_> = iter::zip(&discr_idents, &selflike_args) .map(|(&ident, selflike_arg)| { - let variant_value = - deriving::call_intrinsic(cx, span, sym::discriminant_value, thin_vec![ - selflike_arg.clone() - ]); + let variant_value = deriving::call_intrinsic( + cx, + span, + sym::discriminant_value, + thin_vec![selflike_arg.clone()], + ); cx.stmt_let(span, false, ident, variant_value) }) .collect(); diff --git a/compiler/rustc_builtin_macros/src/env.rs b/compiler/rustc_builtin_macros/src/env.rs index 8831261759c..0913dc91a53 100644 --- a/compiler/rustc_builtin_macros/src/env.rs +++ b/compiler/rustc_builtin_macros/src/env.rs @@ -77,11 +77,11 @@ pub(crate) fn expand_option_env<'cx>( let guar = cx.dcx().emit_err(errors::EnvNotUnicode { span: sp, var: *symbol }); return ExpandResult::Ready(DummyResult::any(sp, guar)); } - Ok(value) => { - cx.expr_call_global(sp, cx.std_path(&[sym::option, sym::Option, sym::Some]), thin_vec![ - cx.expr_str(sp, value) - ]) - } + Ok(value) => cx.expr_call_global( + sp, + cx.std_path(&[sym::option, sym::Option, sym::Some]), + thin_vec![cx.expr_str(sp, value)], + ), }; ExpandResult::Ready(MacEager::expr(e)) } diff --git a/compiler/rustc_builtin_macros/src/format_foreign.rs b/compiler/rustc_builtin_macros/src/format_foreign.rs index 71320e6d5ad..866ec72f116 100644 --- a/compiler/rustc_builtin_macros/src/format_foreign.rs +++ b/compiler/rustc_builtin_macros/src/format_foreign.rs @@ -183,10 +183,14 @@ pub(crate) mod printf { s.push('{'); if let Some(arg) = self.parameter { - match write!(s, "{}", match arg.checked_sub(1) { - Some(a) => a, - None => return Err(None), - }) { + match write!( + s, + "{}", + match arg.checked_sub(1) { + Some(a) => a, + None => return Err(None), + } + ) { Err(_) => return Err(None), _ => {} } diff --git a/compiler/rustc_builtin_macros/src/format_foreign/printf/tests.rs b/compiler/rustc_builtin_macros/src/format_foreign/printf/tests.rs index 8fe06df48e5..1fd54e170b9 100644 --- a/compiler/rustc_builtin_macros/src/format_foreign/printf/tests.rs +++ b/compiler/rustc_builtin_macros/src/format_foreign/printf/tests.rs @@ -99,12 +99,10 @@ fn test_parse() { fn test_iter() { let s = "The %d'th word %% is: `%.*s` %!\n"; let subs: Vec<_> = iter_subs(s, 0).map(|sub| sub.translate().ok()).collect(); - assert_eq!(subs.iter().map(Option::as_deref).collect::>(), vec![ - Some("{}"), - None, - Some("{:.*}"), - None - ]); + assert_eq!( + subs.iter().map(Option::as_deref).collect::>(), + vec![Some("{}"), None, Some("{:.*}"), None] + ); } /// Checks that the translations are what we expect. diff --git a/compiler/rustc_builtin_macros/src/format_foreign/shell/tests.rs b/compiler/rustc_builtin_macros/src/format_foreign/shell/tests.rs index dd2ee2b6ca9..145e3e529b0 100644 --- a/compiler/rustc_builtin_macros/src/format_foreign/shell/tests.rs +++ b/compiler/rustc_builtin_macros/src/format_foreign/shell/tests.rs @@ -38,11 +38,10 @@ fn test_iter() { use super::iter_subs; let s = "The $0'th word $$ is: `$WORD` $!\n"; let subs: Vec<_> = iter_subs(s, 0).map(|sub| sub.translate().ok()).collect(); - assert_eq!(subs.iter().map(Option::as_deref).collect::>(), vec![ - Some("{0}"), - None, - Some("{WORD}") - ]); + assert_eq!( + subs.iter().map(Option::as_deref).collect::>(), + vec![Some("{0}"), None, Some("{WORD}")] + ); } #[test] diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index dee185ff0c9..ee6475c8b8e 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -301,13 +301,10 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { }; let local_path = |cx: &ExtCtxt<'_>, name| cx.expr_path(cx.path(span, vec![name])); let proc_macro_ty_method_path = |cx: &ExtCtxt<'_>, method| { - cx.expr_path(cx.path(span.with_ctxt(harness_span.ctxt()), vec![ - proc_macro, - bridge, - client, - proc_macro_ty, - method, - ])) + cx.expr_path(cx.path( + span.with_ctxt(harness_span.ctxt()), + vec![proc_macro, bridge, client, proc_macro_ty, method], + )) }; match m { ProcMacro::Derive(cd) => { @@ -340,10 +337,14 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { // The call needs to use `harness_span` so that the const stability checker // accepts it. - cx.expr_call(harness_span, proc_macro_ty_method_path(cx, ident), thin_vec![ - cx.expr_str(span, ca.function_name.name), - local_path(cx, ca.function_name), - ]) + cx.expr_call( + harness_span, + proc_macro_ty_method_path(cx, ident), + thin_vec![ + cx.expr_str(span, ca.function_name.name), + local_path(cx, ca.function_name), + ], + ) } } }) @@ -357,12 +358,9 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { span, cx.ty( span, - ast::TyKind::Slice(cx.ty_path(cx.path(span, vec![ - proc_macro, - bridge, - client, - proc_macro_ty, - ]))), + ast::TyKind::Slice( + cx.ty_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty])), + ), ), None, ast::Mutability::Not, diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index 3f73ddbdd29..a05fff2dcd1 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -169,20 +169,26 @@ pub(crate) fn expand_test_or_bench( // creates test::ShouldPanic::$name let should_panic_path = |name| { - cx.path(sp, vec![ - test_id, - Ident::from_str_and_span("ShouldPanic", sp), - Ident::from_str_and_span(name, sp), - ]) + cx.path( + sp, + vec![ + test_id, + Ident::from_str_and_span("ShouldPanic", sp), + Ident::from_str_and_span(name, sp), + ], + ) }; // creates test::TestType::$name let test_type_path = |name| { - cx.path(sp, vec![ - test_id, - Ident::from_str_and_span("TestType", sp), - Ident::from_str_and_span(name, sp), - ]) + cx.path( + sp, + vec![ + test_id, + Ident::from_str_and_span("TestType", sp), + Ident::from_str_and_span(name, sp), + ], + ) }; // creates $name: $expr @@ -202,39 +208,55 @@ pub(crate) fn expand_test_or_bench( // A simple ident for a lambda let b = Ident::from_str_and_span("b", attr_sp); - cx.expr_call(sp, cx.expr_path(test_path("StaticBenchFn")), thin_vec![ - // #[coverage(off)] - // |b| self::test::assert_test_result( - coverage_off(cx.lambda1( - sp, - cx.expr_call(sp, cx.expr_path(test_path("assert_test_result")), thin_vec![ - // super::$test_fn(b) + cx.expr_call( + sp, + cx.expr_path(test_path("StaticBenchFn")), + thin_vec![ + // #[coverage(off)] + // |b| self::test::assert_test_result( + coverage_off(cx.lambda1( + sp, cx.expr_call( - ret_ty_sp, - cx.expr_path(cx.path(sp, vec![item.ident])), - thin_vec![cx.expr_ident(sp, b)], + sp, + cx.expr_path(test_path("assert_test_result")), + thin_vec![ + // super::$test_fn(b) + cx.expr_call( + ret_ty_sp, + cx.expr_path(cx.path(sp, vec![item.ident])), + thin_vec![cx.expr_ident(sp, b)], + ), + ], ), - ],), - b, - )), // ) - ]) + b, + )), // ) + ], + ) } else { - cx.expr_call(sp, cx.expr_path(test_path("StaticTestFn")), thin_vec![ - // #[coverage(off)] - // || { - coverage_off(cx.lambda0( - sp, - // test::assert_test_result( - cx.expr_call(sp, cx.expr_path(test_path("assert_test_result")), thin_vec![ - // $test_fn() + cx.expr_call( + sp, + cx.expr_path(test_path("StaticTestFn")), + thin_vec![ + // #[coverage(off)] + // || { + coverage_off(cx.lambda0( + sp, + // test::assert_test_result( cx.expr_call( - ret_ty_sp, - cx.expr_path(cx.path(sp, vec![item.ident])), - ThinVec::new(), - ), // ) - ],), // } - )), // ) - ]) + sp, + cx.expr_path(test_path("assert_test_result")), + thin_vec![ + // $test_fn() + cx.expr_call( + ret_ty_sp, + cx.expr_path(cx.path(sp, vec![item.ident])), + ThinVec::new(), + ), // ) + ], + ), // } + )), // ) + ], + ) }; let test_path_symbol = Symbol::intern(&item_path( @@ -245,26 +267,30 @@ pub(crate) fn expand_test_or_bench( let location_info = get_location_info(cx, &item); - let mut test_const = cx.item( - sp, - Ident::new(item.ident.name, sp), - thin_vec![ - // #[cfg(test)] - cx.attr_nested_word(sym::cfg, sym::test, attr_sp), - // #[rustc_test_marker = "test_case_sort_key"] - cx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, attr_sp), - // #[doc(hidden)] - cx.attr_nested_word(sym::doc, sym::hidden, attr_sp), - ], - // const $ident: test::TestDescAndFn = - ast::ItemKind::Const( - ast::ConstItem { - defaultness: ast::Defaultness::Final, - generics: ast::Generics::default(), - ty: cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))), - // test::TestDescAndFn { - expr: Some( - cx.expr_struct(sp, test_path("TestDescAndFn"), thin_vec![ + let mut test_const = + cx.item( + sp, + Ident::new(item.ident.name, sp), + thin_vec![ + // #[cfg(test)] + cx.attr_nested_word(sym::cfg, sym::test, attr_sp), + // #[rustc_test_marker = "test_case_sort_key"] + cx.attr_name_value_str(sym::rustc_test_marker, test_path_symbol, attr_sp), + // #[doc(hidden)] + cx.attr_nested_word(sym::doc, sym::hidden, attr_sp), + ], + // const $ident: test::TestDescAndFn = + ast::ItemKind::Const( + ast::ConstItem { + defaultness: ast::Defaultness::Final, + generics: ast::Generics::default(), + ty: cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))), + // test::TestDescAndFn { + expr: Some( + cx.expr_struct( + sp, + test_path("TestDescAndFn"), + thin_vec![ // desc: test::TestDesc { field( "desc", @@ -340,12 +366,13 @@ pub(crate) fn expand_test_or_bench( ), // testfn: test::StaticTestFn(...) | test::StaticBenchFn(...) field("testfn", test_fn), // } - ]), // } - ), - } - .into(), - ), - ); + ], + ), // } + ), + } + .into(), + ), + ); test_const = test_const.map(|mut tc| { tc.vis.kind = ast::VisibilityKind::Public; tc diff --git a/compiler/rustc_codegen_cranelift/example/std_example.rs b/compiler/rustc_codegen_cranelift/example/std_example.rs index 0b1d83c5630..ffdc6a7d484 100644 --- a/compiler/rustc_codegen_cranelift/example/std_example.rs +++ b/compiler/rustc_codegen_cranelift/example/std_example.rs @@ -241,9 +241,10 @@ unsafe fn test_simd() { let (zero0, zero1) = std::mem::transmute::<_, (u64, u64)>(x); assert_eq!((zero0, zero1), (0, 0)); assert_eq!(std::mem::transmute::<_, [u16; 8]>(or), [7, 7, 7, 7, 7, 7, 7, 7]); - assert_eq!(std::mem::transmute::<_, [u16; 8]>(cmp_eq), [ - 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff - ]); + assert_eq!( + std::mem::transmute::<_, [u16; 8]>(cmp_eq), + [0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff] + ); assert_eq!(std::mem::transmute::<_, [u16; 8]>(cmp_lt), [0, 0, 0, 0, 0, 0, 0, 0]); test_mm_slli_si128(); diff --git a/compiler/rustc_codegen_cranelift/src/cast.rs b/compiler/rustc_codegen_cranelift/src/cast.rs index 4463631c524..e2346324232 100644 --- a/compiler/rustc_codegen_cranelift/src/cast.rs +++ b/compiler/rustc_codegen_cranelift/src/cast.rs @@ -96,9 +96,12 @@ pub(crate) fn clif_int_or_float_cast( }, ); - fx.lib_call(&name, vec![AbiParam::new(from_ty)], vec![AbiParam::new(types::I128)], &[ - from, - ])[0] + fx.lib_call( + &name, + vec![AbiParam::new(from_ty)], + vec![AbiParam::new(types::I128)], + &[from], + )[0] } else if to_ty == types::I8 || to_ty == types::I16 { // FIXME implement fcvt_to_*int_sat.i8/i16 let val = if to_signed { diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs index 048a388731f..1c6e471cc87 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs @@ -73,16 +73,19 @@ impl WriteDebugInfo for ObjectProduct { } }; self.object - .add_relocation(from.0, Relocation { - offset: u64::from(reloc.offset), - symbol, - flags: RelocationFlags::Generic { - kind: reloc.kind, - encoding: RelocationEncoding::Generic, - size: reloc.size * 8, + .add_relocation( + from.0, + Relocation { + offset: u64::from(reloc.offset), + symbol, + flags: RelocationFlags::Generic { + kind: reloc.kind, + encoding: RelocationEncoding::Generic, + size: reloc.size * 8, + }, + addend: i64::try_from(symbol_offset).unwrap() + reloc.addend, }, - addend: i64::try_from(symbol_offset).unwrap() + reloc.addend, - }) + ) .unwrap(); } } diff --git a/compiler/rustc_codegen_cranelift/src/driver/jit.rs b/compiler/rustc_codegen_cranelift/src/driver/jit.rs index b18f4ff4747..2e713171ae0 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/jit.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/jit.rs @@ -342,11 +342,15 @@ fn codegen_shim<'tcx>( let instance_ptr = Box::into_raw(Box::new(inst)); let jit_fn = module - .declare_function("__clif_jit_fn", Linkage::Import, &Signature { - call_conv: module.target_config().default_call_conv, - params: vec![AbiParam::new(pointer_type), AbiParam::new(pointer_type)], - returns: vec![AbiParam::new(pointer_type)], - }) + .declare_function( + "__clif_jit_fn", + Linkage::Import, + &Signature { + call_conv: module.target_config().default_call_conv, + params: vec![AbiParam::new(pointer_type), AbiParam::new(pointer_type)], + returns: vec![AbiParam::new(pointer_type)], + }, + ) .unwrap(); let context = cached_context; diff --git a/compiler/rustc_codegen_cranelift/src/inline_asm.rs b/compiler/rustc_codegen_cranelift/src/inline_asm.rs index 6ff75f75d3b..f2b0ec977c6 100644 --- a/compiler/rustc_codegen_cranelift/src/inline_asm.rs +++ b/compiler/rustc_codegen_cranelift/src/inline_asm.rs @@ -875,11 +875,15 @@ fn call_inline_asm<'tcx>( let inline_asm_func = fx .module - .declare_function(asm_name, Linkage::Import, &Signature { - call_conv: CallConv::SystemV, - params: vec![AbiParam::new(fx.pointer_type)], - returns: vec![], - }) + .declare_function( + asm_name, + Linkage::Import, + &Signature { + call_conv: CallConv::SystemV, + params: vec![AbiParam::new(fx.pointer_type)], + returns: vec![], + }, + ) .unwrap(); let inline_asm_func = fx.module.declare_func_in_func(inline_asm_func, fx.bcx.func); if fx.clif_comments.enabled() { diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs index d682efd19aa..fcccda62355 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs @@ -558,9 +558,12 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( (sym::simd_round, types::F64) => "round", _ => unreachable!("{:?}", intrinsic), }; - fx.lib_call(name, vec![AbiParam::new(lane_ty)], vec![AbiParam::new(lane_ty)], &[ - lane, - ])[0] + fx.lib_call( + name, + vec![AbiParam::new(lane_ty)], + vec![AbiParam::new(lane_ty)], + &[lane], + )[0] }); } diff --git a/compiler/rustc_codegen_cranelift/src/main_shim.rs b/compiler/rustc_codegen_cranelift/src/main_shim.rs index f6843496895..6d5df2b0043 100644 --- a/compiler/rustc_codegen_cranelift/src/main_shim.rs +++ b/compiler/rustc_codegen_cranelift/src/main_shim.rs @@ -15,9 +15,12 @@ pub(crate) fn maybe_create_entry_wrapper( is_primary_cgu: bool, ) { let (main_def_id, sigpipe) = match tcx.entry_fn(()) { - Some((def_id, entry_ty)) => (def_id, match entry_ty { - EntryFnType::Main { sigpipe } => sigpipe, - }), + Some((def_id, entry_ty)) => ( + def_id, + match entry_ty { + EntryFnType::Main { sigpipe } => sigpipe, + }, + ), None => return, }; diff --git a/compiler/rustc_codegen_cranelift/src/trap.rs b/compiler/rustc_codegen_cranelift/src/trap.rs index 9ef1a523d6d..ac3f58ee1ee 100644 --- a/compiler/rustc_codegen_cranelift/src/trap.rs +++ b/compiler/rustc_codegen_cranelift/src/trap.rs @@ -5,11 +5,15 @@ use crate::prelude::*; fn codegen_print(fx: &mut FunctionCx<'_, '_, '_>, msg: &str) { let puts = fx .module - .declare_function("puts", Linkage::Import, &Signature { - call_conv: fx.target_config.default_call_conv, - params: vec![AbiParam::new(fx.pointer_type)], - returns: vec![AbiParam::new(types::I32)], - }) + .declare_function( + "puts", + Linkage::Import, + &Signature { + call_conv: fx.target_config.default_call_conv, + params: vec![AbiParam::new(fx.pointer_type)], + returns: vec![AbiParam::new(types::I32)], + }, + ) .unwrap(); let puts = fx.module.declare_func_in_func(puts, &mut fx.bcx.func); if fx.clif_comments.enabled() { diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index bba19d06258..1c3d6cc899a 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -155,14 +155,11 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { // NOTE: not sure why, but we have the wrong type here. let int_type = compare_exchange.get_param(2).to_rvalue().get_type(); let src = self.context.new_bitcast(self.location, src, int_type); - self.context.new_call(self.location, compare_exchange, &[ - dst, - expected, - src, - weak, - order, - failure_order, - ]) + self.context.new_call( + self.location, + compare_exchange, + &[dst, expected, src, weak, order, failure_order], + ) } pub fn assign(&self, lvalue: LValue<'gcc>, value: RValue<'gcc>) { @@ -1076,9 +1073,11 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size); cg_elem.val.store(self, PlaceRef::new_sized_aligned(current_val, cg_elem.layout, align)); - let next = self.inbounds_gep(self.backend_type(cg_elem.layout), current.to_rvalue(), &[ - self.const_usize(1), - ]); + let next = self.inbounds_gep( + self.backend_type(cg_elem.layout), + current.to_rvalue(), + &[self.const_usize(1)], + ); self.llbb().add_assignment(self.location, current, next); self.br(header_bb); diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs b/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs index 231307def29..2d731f88d7d 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs @@ -687,11 +687,12 @@ pub fn adjust_intrinsic_return_value<'a, 'gcc, 'tcx>( let field2 = builder.context.new_field(None, args[1].get_type(), "carryResult"); let struct_type = builder.context.new_struct_type(None, "addcarryResult", &[field1, field2]); - return_value = - builder.context.new_struct_constructor(None, struct_type.as_type(), None, &[ - return_value, - last_arg.dereference(None).to_rvalue(), - ]); + return_value = builder.context.new_struct_constructor( + None, + struct_type.as_type(), + None, + &[return_value, last_arg.dereference(None).to_rvalue()], + ); } } "__builtin_ia32_stmxcsr" => { @@ -716,11 +717,12 @@ pub fn adjust_intrinsic_return_value<'a, 'gcc, 'tcx>( let field2 = builder.context.new_field(None, return_value.get_type(), "success"); let struct_type = builder.context.new_struct_type(None, "rdrand_result", &[field1, field2]); - return_value = - builder.context.new_struct_constructor(None, struct_type.as_type(), None, &[ - random_number, - success_variable.to_rvalue(), - ]); + return_value = builder.context.new_struct_constructor( + None, + struct_type.as_type(), + None, + &[random_number, success_variable.to_rvalue()], + ); } "fma" => { let f16_type = builder.context.new_c_type(CType::Float16); diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs index 12a7dab155b..84cd5b002fb 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs @@ -62,11 +62,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let arg_tys = sig.inputs(); if name == sym::simd_select_bitmask { - require_simd!(arg_tys[1], InvalidMonomorphization::SimdArgument { - span, - name, - ty: arg_tys[1] - }); + require_simd!( + arg_tys[1], + InvalidMonomorphization::SimdArgument { span, name, ty: arg_tys[1] } + ); let (len, _) = arg_tys[1].simd_size_and_type(bx.tcx()); let expected_int_bits = (len.max(8) - 1).next_power_of_two(); @@ -140,14 +139,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); require!( bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer, InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty } @@ -269,23 +271,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let lo_nibble = bx.context.new_rvalue_from_vector(None, long_byte_vector_type, &lo_nibble_elements); - let mask = bx.context.new_rvalue_from_vector(None, long_byte_vector_type, &vec![ - bx.context - .new_rvalue_from_int( - bx.u8_type, 0x0f - ); - byte_vector_type_size - as _ - ]); + let mask = bx.context.new_rvalue_from_vector( + None, + long_byte_vector_type, + &vec![bx.context.new_rvalue_from_int(bx.u8_type, 0x0f); byte_vector_type_size as _], + ); - let four_vec = bx.context.new_rvalue_from_vector(None, long_byte_vector_type, &vec![ - bx.context - .new_rvalue_from_int( - bx.u8_type, 4 - ); - byte_vector_type_size - as _ - ]); + let four_vec = bx.context.new_rvalue_from_vector( + None, + long_byte_vector_type, + &vec![bx.context.new_rvalue_from_int(bx.u8_type, 4); byte_vector_type_size as _], + ); // Step 2: Byte-swap the input. let swapped = simd_bswap(bx, args[0].immediate()); @@ -388,21 +384,14 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx()); - require!(out_len == n, InvalidMonomorphization::ReturnLength { - span, - name, - in_len: n, - ret_ty, - out_len - }); - require!(in_elem == out_ty, InvalidMonomorphization::ReturnElement { - span, - name, - in_elem, - in_ty, - ret_ty, - out_ty - }); + require!( + out_len == n, + InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len } + ); + require!( + in_elem == out_ty, + InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty } + ); let vector = args[2].immediate(); @@ -411,13 +400,16 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( #[cfg(feature = "master")] if name == sym::simd_insert { - require!(in_elem == arg_tys[2], InvalidMonomorphization::InsertedType { - span, - name, - in_elem, - in_ty, - out_ty: arg_tys[2] - }); + require!( + in_elem == arg_tys[2], + InvalidMonomorphization::InsertedType { + span, + name, + in_elem, + in_ty, + out_ty: arg_tys[2] + } + ); let vector = args[0].immediate(); let index = args[1].immediate(); let value = args[2].immediate(); @@ -431,13 +423,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( #[cfg(feature = "master")] if name == sym::simd_extract { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); let vector = args[0].immediate(); return Ok(bx.context.new_vector_access(None, vector, args[1].immediate()).to_rvalue()); } @@ -445,18 +434,15 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( if name == sym::simd_select { let m_elem_ty = in_elem; let m_len = in_len; - require_simd!(arg_tys[1], InvalidMonomorphization::SimdArgument { - span, - name, - ty: arg_tys[1] - }); + require_simd!( + arg_tys[1], + InvalidMonomorphization::SimdArgument { span, name, ty: arg_tys[1] } + ); let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx()); - require!(m_len == v_len, InvalidMonomorphization::MismatchedLengths { - span, - name, - m_len, - v_len - }); + require!( + m_len == v_len, + InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len } + ); match *m_elem_ty.kind() { ty::Int(_) => {} _ => return_error!(InvalidMonomorphization::MaskType { span, name, ty: m_elem_ty }), @@ -468,25 +454,27 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); match *in_elem.kind() { ty::RawPtr(p_ty, _) => { let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), ty) }); - require!(metadata.is_unit(), InvalidMonomorphization::CastWidePointer { - span, - name, - ty: in_elem - }); + require!( + metadata.is_unit(), + InvalidMonomorphization::CastWidePointer { span, name, ty: in_elem } + ); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem }) @@ -497,11 +485,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), ty) }); - require!(metadata.is_unit(), InvalidMonomorphization::CastWidePointer { - span, - name, - ty: out_elem - }); + require!( + metadata.is_unit(), + InvalidMonomorphization::CastWidePointer { span, name, ty: out_elem } + ); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem }) @@ -524,14 +511,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); match *in_elem.kind() { ty::RawPtr(_, _) => {} @@ -560,14 +550,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); match *in_elem.kind() { ty::Uint(ty::UintTy::Usize) => {} @@ -596,14 +589,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( if name == sym::simd_cast || name == sym::simd_as { require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); // casting cares about nominal type, not just structural type if in_elem == out_elem { return Ok(args[0].immediate()); @@ -629,14 +625,17 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( match (in_style, out_style) { (Style::Unsupported, Style::Unsupported) => { - require!(false, InvalidMonomorphization::UnsupportedCast { - span, - name, - in_ty, - in_elem, - ret_ty, - out_elem - }); + require!( + false, + InvalidMonomorphization::UnsupportedCast { + span, + name, + in_ty, + in_elem, + ret_ty, + out_elem + } + ); } _ => return Ok(bx.context.convert_vector(None, args[0].immediate(), llret_ty)), } @@ -914,45 +913,47 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( // All types must be simd vector types require_simd!(in_ty, InvalidMonomorphization::SimdFirst { span, name, ty: in_ty }); - require_simd!(arg_tys[1], InvalidMonomorphization::SimdSecond { - span, - name, - ty: arg_tys[1] - }); - require_simd!(arg_tys[2], InvalidMonomorphization::SimdThird { - span, - name, - ty: arg_tys[2] - }); + require_simd!( + arg_tys[1], + InvalidMonomorphization::SimdSecond { span, name, ty: arg_tys[1] } + ); + require_simd!( + arg_tys[2], + InvalidMonomorphization::SimdThird { span, name, ty: arg_tys[2] } + ); require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); // Of the same length: let (out_len, _) = arg_tys[1].simd_size_and_type(bx.tcx()); let (out_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx()); - require!(in_len == out_len, InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len - }); - require!(in_len == out_len2, InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: out_len2 - }); + require!( + in_len == out_len, + InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len + } + ); + require!( + in_len == out_len2, + InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: out_len2 + } + ); // The return type must match the first argument type - require!(ret_ty == in_ty, InvalidMonomorphization::ExpectedReturnType { - span, - name, - in_ty, - ret_ty - }); + require!( + ret_ty == in_ty, + InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty } + ); // This counts how many pointers fn ptr_count(t: Ty<'_>) -> usize { @@ -979,15 +980,18 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( (ptr_count(element_ty1), non_ptr(element_ty1)) } _ => { - require!(false, InvalidMonomorphization::ExpectedElementType { - span, - name, - expected_element: element_ty1, - second_arg: arg_tys[1], - in_elem, - in_ty, - mutability: ExpectedPointerMutability::Not, - }); + require!( + false, + InvalidMonomorphization::ExpectedElementType { + span, + name, + expected_element: element_ty1, + second_arg: arg_tys[1], + in_elem, + in_ty, + mutability: ExpectedPointerMutability::Not, + } + ); unreachable!(); } }; @@ -1000,12 +1004,15 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( match *element_ty2.kind() { ty::Int(_) => (), _ => { - require!(false, InvalidMonomorphization::ThirdArgElementType { - span, - name, - expected_element: element_ty2, - third_arg: arg_tys[2] - }); + require!( + false, + InvalidMonomorphization::ThirdArgElementType { + span, + name, + expected_element: element_ty2, + third_arg: arg_tys[2] + } + ); } } @@ -1029,36 +1036,40 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( // All types must be simd vector types require_simd!(in_ty, InvalidMonomorphization::SimdFirst { span, name, ty: in_ty }); - require_simd!(arg_tys[1], InvalidMonomorphization::SimdSecond { - span, - name, - ty: arg_tys[1] - }); - require_simd!(arg_tys[2], InvalidMonomorphization::SimdThird { - span, - name, - ty: arg_tys[2] - }); + require_simd!( + arg_tys[1], + InvalidMonomorphization::SimdSecond { span, name, ty: arg_tys[1] } + ); + require_simd!( + arg_tys[2], + InvalidMonomorphization::SimdThird { span, name, ty: arg_tys[2] } + ); // Of the same length: let (element_len1, _) = arg_tys[1].simd_size_and_type(bx.tcx()); let (element_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx()); - require!(in_len == element_len1, InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len: element_len1 - }); - require!(in_len == element_len2, InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: element_len2 - }); + require!( + in_len == element_len1, + InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len: element_len1 + } + ); + require!( + in_len == element_len2, + InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: element_len2 + } + ); // This counts how many pointers fn ptr_count(t: Ty<'_>) -> usize { @@ -1086,15 +1097,18 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( (ptr_count(element_ty1), non_ptr(element_ty1)) } _ => { - require!(false, InvalidMonomorphization::ExpectedElementType { - span, - name, - expected_element: element_ty1, - second_arg: arg_tys[1], - in_elem, - in_ty, - mutability: ExpectedPointerMutability::Mut, - }); + require!( + false, + InvalidMonomorphization::ExpectedElementType { + span, + name, + expected_element: element_ty1, + second_arg: arg_tys[1], + in_elem, + in_ty, + mutability: ExpectedPointerMutability::Mut, + } + ); unreachable!(); } }; @@ -1106,12 +1120,15 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( match *element_ty2.kind() { ty::Int(_) => (), _ => { - require!(false, InvalidMonomorphization::ThirdArgElementType { - span, - name, - expected_element: element_ty2, - third_arg: arg_tys[2] - }); + require!( + false, + InvalidMonomorphization::ThirdArgElementType { + span, + name, + expected_element: element_ty2, + third_arg: arg_tys[2] + } + ); } } @@ -1278,13 +1295,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( ($name:ident : $vec_op:expr, $float_reduce:ident, $ordered:expr, $op:ident, $identity:expr) => { if name == sym::$name { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); return match *in_elem.kind() { ty::Int(_) | ty::Uint(_) => { let r = bx.vector_reduce_op(args[0].immediate(), $vec_op); @@ -1350,13 +1364,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( macro_rules! minmax_red { ($name:ident: $int_red:ident, $float_red:ident) => { if name == sym::$name { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); return match *in_elem.kind() { ty::Int(_) | ty::Uint(_) => Ok(bx.$int_red(args[0].immediate())), ty::Float(_) => Ok(bx.$float_red(args[0].immediate())), @@ -1380,13 +1391,10 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( ($name:ident : $op:expr, $boolean:expr) => { if name == sym::$name { let input = if !$boolean { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); args[0].immediate() } else { match *in_elem.kind() { diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs index 31ee0eeca11..f4d78d59bac 100644 --- a/compiler/rustc_codegen_llvm/src/abi.rs +++ b/compiler/rustc_codegen_llvm/src/abi.rs @@ -448,11 +448,11 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { // LLVM also rejects full range. && !scalar.is_always_valid(cx) { - attributes::apply_to_llfn(llfn, idx, &[llvm::CreateRangeAttr( - cx.llcx, - scalar.size(cx), - scalar.valid_range(cx), - )]); + attributes::apply_to_llfn( + llfn, + idx, + &[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))], + ); } }; @@ -472,10 +472,14 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { ); attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]); if cx.sess().opts.optimize != config::OptLevel::No { - attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[ - llvm::AttributeKind::Writable.create_attr(cx.llcx), - llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx), - ]); + attributes::apply_to_llfn( + llfn, + llvm::AttributePlace::Argument(i), + &[ + llvm::AttributeKind::Writable.create_attr(cx.llcx), + llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx), + ], + ); } } PassMode::Cast { cast, pad_i32: _ } => { @@ -593,9 +597,11 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { bx.cx.llcx, bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()), ); - attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[ - byval, - ]); + attributes::apply_to_callsite( + callsite, + llvm::AttributePlace::Argument(i), + &[byval], + ); } PassMode::Direct(attrs) | PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => { @@ -627,9 +633,11 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { // This will probably get ignored on all targets but those supporting the TrustZone-M // extension (thumbv8m targets). let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call"); - attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &[ - cmse_nonsecure_call, - ]); + attributes::apply_to_callsite( + callsite, + llvm::AttributePlace::Function, + &[cmse_nonsecure_call], + ); } // Some intrinsics require that an elementtype attribute (with the pointee type of a diff --git a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs index 9e8e4e1c567..dd5e726160d 100644 --- a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs +++ b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs @@ -291,20 +291,26 @@ pub(crate) fn differentiate<'ll>( let name = item.source.clone(); let fn_def: Option<&llvm::Value> = cx.get_function(&name); let Some(fn_def) = fn_def else { - return Err(llvm_err(diag_handler.handle(), LlvmError::PrepareAutoDiff { - src: item.source.clone(), - target: item.target.clone(), - error: "could not find source function".to_owned(), - })); + return Err(llvm_err( + diag_handler.handle(), + LlvmError::PrepareAutoDiff { + src: item.source.clone(), + target: item.target.clone(), + error: "could not find source function".to_owned(), + }, + )); }; debug!(?item.target); let fn_target: Option<&llvm::Value> = cx.get_function(&item.target); let Some(fn_target) = fn_target else { - return Err(llvm_err(diag_handler.handle(), LlvmError::PrepareAutoDiff { - src: item.source.clone(), - target: item.target.clone(), - error: "could not find target function".to_owned(), - })); + return Err(llvm_err( + diag_handler.handle(), + LlvmError::PrepareAutoDiff { + src: item.source.clone(), + target: item.target.clone(), + error: "could not find target function".to_owned(), + }, + )); }; generate_enzyme_call(&cx, fn_def, fn_target, item.attrs.clone()); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index 19fb2754571..51a17ed3d3f 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -544,14 +544,17 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { } } - let scope = namespace::item_namespace(cx, DefId { - krate: instance.def_id().krate, - index: cx - .tcx - .def_key(instance.def_id()) - .parent - .expect("get_containing_scope: missing parent?"), - }); + let scope = namespace::item_namespace( + cx, + DefId { + krate: instance.def_id().krate, + index: cx + .tcx + .def_key(instance.def_id()) + .parent + .expect("get_containing_scope: missing parent?"), + }, + ); (scope, false) } } diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 43d6ccfcb4a..3200c94d977 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -333,12 +333,15 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { sym::prefetch_write_instruction => (1, 0), _ => bug!(), }; - self.call_intrinsic("llvm.prefetch", &[ - args[0].immediate(), - self.const_i32(rw), - args[1].immediate(), - self.const_i32(cache_type), - ]) + self.call_intrinsic( + "llvm.prefetch", + &[ + args[0].immediate(), + self.const_i32(rw), + args[1].immediate(), + self.const_i32(cache_type), + ], + ) } sym::carrying_mul_add => { let (size, signed) = fn_args.type_at(0).int_size_and_signed(self.tcx); @@ -396,10 +399,10 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { match name { sym::ctlz | sym::cttz => { let y = self.const_bool(false); - let ret = self.call_intrinsic(&format!("llvm.{name}.i{width}"), &[ - args[0].immediate(), - y, - ]); + let ret = self.call_intrinsic( + &format!("llvm.{name}.i{width}"), + &[args[0].immediate(), y], + ); self.intcast(ret, llret_ty, false) } @@ -416,24 +419,26 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { self.intcast(ret, llret_ty, false) } sym::ctpop => { - let ret = self.call_intrinsic(&format!("llvm.ctpop.i{width}"), &[ - args[0].immediate() - ]); + let ret = self.call_intrinsic( + &format!("llvm.ctpop.i{width}"), + &[args[0].immediate()], + ); self.intcast(ret, llret_ty, false) } sym::bswap => { if width == 8 { args[0].immediate() // byte swap a u8/i8 is just a no-op } else { - self.call_intrinsic(&format!("llvm.bswap.i{width}"), &[ - args[0].immediate() - ]) + self.call_intrinsic( + &format!("llvm.bswap.i{width}"), + &[args[0].immediate()], + ) } } - sym::bitreverse => self - .call_intrinsic(&format!("llvm.bitreverse.i{width}"), &[ - args[0].immediate() - ]), + sym::bitreverse => self.call_intrinsic( + &format!("llvm.bitreverse.i{width}"), + &[args[0].immediate()], + ), sym::rotate_left | sym::rotate_right => { let is_left = name == sym::rotate_left; let val = args[0].immediate(); @@ -500,11 +505,10 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { sym::compare_bytes => { // Here we assume that the `memcmp` provided by the target is a NOP for size 0. - let cmp = self.call_intrinsic("memcmp", &[ - args[0].immediate(), - args[1].immediate(), - args[2].immediate(), - ]); + let cmp = self.call_intrinsic( + "memcmp", + &[args[0].immediate(), args[1].immediate(), args[2].immediate()], + ); // Some targets have `memcmp` returning `i16`, but the intrinsic is always `i32`. self.sext(cmp, self.type_ix(32)) } @@ -1305,14 +1309,17 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if let Some(cmp_op) = comparison { let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); require!( bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer, InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty } @@ -1333,21 +1340,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let n = idx.len() as u64; let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn); - require!(out_len == n, InvalidMonomorphization::ReturnLength { - span, - name, - in_len: n, - ret_ty, - out_len - }); - require!(in_elem == out_ty, InvalidMonomorphization::ReturnElement { - span, - name, - in_elem, - in_ty, - ret_ty, - out_ty - }); + require!( + out_len == n, + InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len } + ); + require!( + in_elem == out_ty, + InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty } + ); let total_len = in_len * 2; @@ -1392,21 +1392,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>( }; let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn); - require!(out_len == n, InvalidMonomorphization::ReturnLength { - span, - name, - in_len: n, - ret_ty, - out_len - }); - require!(in_elem == out_ty, InvalidMonomorphization::ReturnElement { - span, - name, - in_elem, - in_ty, - ret_ty, - out_ty - }); + require!( + out_len == n, + InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len } + ); + require!( + in_elem == out_ty, + InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty } + ); let total_len = u128::from(in_len) * 2; @@ -1431,13 +1424,16 @@ fn generic_simd_intrinsic<'ll, 'tcx>( } if name == sym::simd_insert { - require!(in_elem == arg_tys[2], InvalidMonomorphization::InsertedType { - span, - name, - in_elem, - in_ty, - out_ty: arg_tys[2] - }); + require!( + in_elem == arg_tys[2], + InvalidMonomorphization::InsertedType { + span, + name, + in_elem, + in_ty, + out_ty: arg_tys[2] + } + ); let idx = bx .const_to_opt_u128(args[1].immediate(), false) .expect("typeck should have ensure that this is a const"); @@ -1456,13 +1452,10 @@ fn generic_simd_intrinsic<'ll, 'tcx>( )); } if name == sym::simd_extract { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); let idx = bx .const_to_opt_u128(args[1].immediate(), false) .expect("typeck should have ensure that this is a const"); @@ -1481,18 +1474,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let m_elem_ty = in_elem; let m_len = in_len; let (v_len, _) = require_simd!(arg_tys[1], SimdArgument); - require!(m_len == v_len, InvalidMonomorphization::MismatchedLengths { - span, - name, - m_len, - v_len - }); - let in_elem_bitwidth = - require_int_ty!(m_elem_ty.kind(), InvalidMonomorphization::MaskType { - span, - name, - ty: m_elem_ty - }); + require!( + m_len == v_len, + InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len } + ); + let in_elem_bitwidth = require_int_ty!( + m_elem_ty.kind(), + InvalidMonomorphization::MaskType { span, name, ty: m_elem_ty } + ); let m_i1s = vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, m_len); return Ok(bx.select(m_i1s, args[1].immediate(), args[2].immediate())); } @@ -1510,13 +1499,10 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let expected_bytes = in_len.div_ceil(8); // Integer vector : - let in_elem_bitwidth = - require_int_or_uint_ty!(in_elem.kind(), InvalidMonomorphization::VectorArgument { - span, - name, - in_ty, - in_elem - }); + let in_elem_bitwidth = require_int_or_uint_ty!( + in_elem.kind(), + InvalidMonomorphization::VectorArgument { span, name, in_ty, in_elem } + ); let i1xn = vector_mask_to_bitmask(bx, args[0].immediate(), in_elem_bitwidth, in_len); // Bitcast to iN: @@ -1698,30 +1684,34 @@ fn generic_simd_intrinsic<'ll, 'tcx>( require_simd!(ret_ty, SimdReturn); // Of the same length: - require!(in_len == out_len, InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len - }); - require!(in_len == out_len2, InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: out_len2 - }); + require!( + in_len == out_len, + InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len + } + ); + require!( + in_len == out_len2, + InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: out_len2 + } + ); // The return type must match the first argument type - require!(ret_ty == in_ty, InvalidMonomorphization::ExpectedReturnType { - span, - name, - in_ty, - ret_ty - }); + require!( + ret_ty == in_ty, + InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty } + ); require!( matches!( @@ -1739,13 +1729,15 @@ fn generic_simd_intrinsic<'ll, 'tcx>( } ); - let mask_elem_bitwidth = - require_int_ty!(element_ty2.kind(), InvalidMonomorphization::ThirdArgElementType { + let mask_elem_bitwidth = require_int_ty!( + element_ty2.kind(), + InvalidMonomorphization::ThirdArgElementType { span, name, expected_element: element_ty2, third_arg: arg_tys[2] - }); + } + ); // Alignment of T, must be a constant integer value: let alignment_ty = bx.type_i32(); @@ -1805,22 +1797,23 @@ fn generic_simd_intrinsic<'ll, 'tcx>( require_simd!(ret_ty, SimdReturn); // Of the same length: - require!(values_len == mask_len, InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len: mask_len, - in_ty: mask_ty, - arg_ty: values_ty, - out_len: values_len - }); + require!( + values_len == mask_len, + InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len: mask_len, + in_ty: mask_ty, + arg_ty: values_ty, + out_len: values_len + } + ); // The return type must match the last argument type - require!(ret_ty == values_ty, InvalidMonomorphization::ExpectedReturnType { - span, - name, - in_ty: values_ty, - ret_ty - }); + require!( + ret_ty == values_ty, + InvalidMonomorphization::ExpectedReturnType { span, name, in_ty: values_ty, ret_ty } + ); require!( matches!( @@ -1838,13 +1831,15 @@ fn generic_simd_intrinsic<'ll, 'tcx>( } ); - let m_elem_bitwidth = - require_int_ty!(mask_elem.kind(), InvalidMonomorphization::ThirdArgElementType { + let m_elem_bitwidth = require_int_ty!( + mask_elem.kind(), + InvalidMonomorphization::ThirdArgElementType { span, name, expected_element: values_elem, third_arg: mask_ty, - }); + } + ); let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len); let mask_ty = bx.type_vector(bx.type_i1(), mask_len); @@ -1896,14 +1891,17 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let (values_len, values_elem) = require_simd!(values_ty, SimdThird); // Of the same length: - require!(values_len == mask_len, InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len: mask_len, - in_ty: mask_ty, - arg_ty: values_ty, - out_len: values_len - }); + require!( + values_len == mask_len, + InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len: mask_len, + in_ty: mask_ty, + arg_ty: values_ty, + out_len: values_len + } + ); // The second argument must be a mutable pointer type matching the element type require!( @@ -1923,13 +1921,15 @@ fn generic_simd_intrinsic<'ll, 'tcx>( } ); - let m_elem_bitwidth = - require_int_ty!(mask_elem.kind(), InvalidMonomorphization::ThirdArgElementType { + let m_elem_bitwidth = require_int_ty!( + mask_elem.kind(), + InvalidMonomorphization::ThirdArgElementType { span, name, expected_element: values_elem, third_arg: mask_ty, - }); + } + ); let mask = vector_mask_to_bitmask(bx, args[0].immediate(), m_elem_bitwidth, mask_len); let mask_ty = bx.type_vector(bx.type_i1(), mask_len); @@ -1976,22 +1976,28 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let (element_len2, element_ty2) = require_simd!(arg_tys[2], SimdThird); // Of the same length: - require!(in_len == element_len1, InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len: element_len1 - }); - require!(in_len == element_len2, InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: element_len2 - }); + require!( + in_len == element_len1, + InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len: element_len1 + } + ); + require!( + in_len == element_len2, + InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: element_len2 + } + ); require!( matches!( @@ -2011,13 +2017,15 @@ fn generic_simd_intrinsic<'ll, 'tcx>( ); // The element type of the third argument must be a signed integer type of any width: - let mask_elem_bitwidth = - require_int_ty!(element_ty2.kind(), InvalidMonomorphization::ThirdArgElementType { + let mask_elem_bitwidth = require_int_ty!( + element_ty2.kind(), + InvalidMonomorphization::ThirdArgElementType { span, name, expected_element: element_ty2, third_arg: arg_tys[2] - }); + } + ); // Alignment of T, must be a constant integer value: let alignment_ty = bx.type_i32(); @@ -2058,13 +2066,10 @@ fn generic_simd_intrinsic<'ll, 'tcx>( ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident, $identity:expr) => { if name == sym::$name { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); return match in_elem.kind() { ty::Int(_) | ty::Uint(_) => { let r = bx.$integer_reduce(args[0].immediate()); @@ -2133,13 +2138,10 @@ fn generic_simd_intrinsic<'ll, 'tcx>( macro_rules! minmax_red { ($name:ident: $int_red:ident, $float_red:ident) => { if name == sym::$name { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); return match in_elem.kind() { ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)), ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)), @@ -2164,13 +2166,10 @@ fn generic_simd_intrinsic<'ll, 'tcx>( ($name:ident : $red:ident, $boolean:expr) => { if name == sym::$name { let input = if !$boolean { - require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { - span, - name, - in_elem, - in_ty, - ret_ty - }); + require!( + ret_ty == in_elem, + InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } + ); args[0].immediate() } else { let bitwidth = match in_elem.kind() { @@ -2218,25 +2217,27 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if name == sym::simd_cast_ptr { let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); match in_elem.kind() { ty::RawPtr(p_ty, _) => { let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(bx.typing_env(), ty) }); - require!(metadata.is_unit(), InvalidMonomorphization::CastWidePointer { - span, - name, - ty: in_elem - }); + require!( + metadata.is_unit(), + InvalidMonomorphization::CastWidePointer { span, name, ty: in_elem } + ); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem }) @@ -2247,11 +2248,10 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(bx.typing_env(), ty) }); - require!(metadata.is_unit(), InvalidMonomorphization::CastWidePointer { - span, - name, - ty: out_elem - }); + require!( + metadata.is_unit(), + InvalidMonomorphization::CastWidePointer { span, name, ty: out_elem } + ); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem }) @@ -2263,14 +2263,17 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if name == sym::simd_expose_provenance { let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); match in_elem.kind() { ty::RawPtr(_, _) => {} @@ -2288,14 +2291,17 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if name == sym::simd_with_exposed_provenance { let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); match in_elem.kind() { ty::Uint(ty::UintTy::Usize) => {} @@ -2313,14 +2319,17 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if name == sym::simd_cast || name == sym::simd_as { let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn); - require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - }); + require!( + in_len == out_len, + InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + } + ); // casting cares about nominal type, not just structural type if in_elem == out_elem { return Ok(args[0].immediate()); diff --git a/compiler/rustc_codegen_ssa/src/back/archive.rs b/compiler/rustc_codegen_ssa/src/back/archive.rs index 58eb137c068..60af462b6b6 100644 --- a/compiler/rustc_codegen_ssa/src/back/archive.rs +++ b/compiler/rustc_codegen_ssa/src/back/archive.rs @@ -414,10 +414,10 @@ impl<'a> ArchiveBuilder for ArArchiveBuilder<'a> { let member_path = archive_path.parent().unwrap().join(Path::new(&file_name)); self.entries.push((file_name.into_bytes(), ArchiveEntry::File(member_path))); } else { - self.entries.push((file_name.into_bytes(), ArchiveEntry::FromArchive { - archive_index, - file_range: entry.file_range(), - })); + self.entries.push(( + file_name.into_bytes(), + ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() }, + )); } } } diff --git a/compiler/rustc_codegen_ssa/src/back/linker/tests.rs b/compiler/rustc_codegen_ssa/src/back/linker/tests.rs index bf3e8c90200..143df085dbf 100644 --- a/compiler/rustc_codegen_ssa/src/back/linker/tests.rs +++ b/compiler/rustc_codegen_ssa/src/back/linker/tests.rs @@ -10,23 +10,22 @@ fn test_rpaths_to_args() { #[test] fn test_xlinker() { let mut cmd = Command::new("foo"); - convert_link_args_to_cc_args(&mut cmd, &[ - "arg1", - "arg2", - "arg3,with,comma", - "arg4,with,comma", - "arg5", - "arg6,with,comma", - ]); + convert_link_args_to_cc_args( + &mut cmd, + &["arg1", "arg2", "arg3,with,comma", "arg4,with,comma", "arg5", "arg6,with,comma"], + ); - assert_eq!(cmd.get_args(), [ - OsStr::new("-Wl,arg1,arg2"), - OsStr::new("-Xlinker"), - OsStr::new("arg3,with,comma"), - OsStr::new("-Xlinker"), - OsStr::new("arg4,with,comma"), - OsStr::new("-Wl,arg5"), - OsStr::new("-Xlinker"), - OsStr::new("arg6,with,comma"), - ]); + assert_eq!( + cmd.get_args(), + [ + OsStr::new("-Wl,arg1,arg2"), + OsStr::new("-Xlinker"), + OsStr::new("arg3,with,comma"), + OsStr::new("-Xlinker"), + OsStr::new("arg4,with,comma"), + OsStr::new("-Wl,arg5"), + OsStr::new("-Xlinker"), + OsStr::new("arg6,with,comma"), + ] + ); } diff --git a/compiler/rustc_codegen_ssa/src/back/metadata.rs b/compiler/rustc_codegen_ssa/src/back/metadata.rs index ba7b53321a8..d70413b8a47 100644 --- a/compiler/rustc_codegen_ssa/src/back/metadata.rs +++ b/compiler/rustc_codegen_ssa/src/back/metadata.rs @@ -704,13 +704,17 @@ pub fn create_metadata_file_for_wasm(sess: &Session, data: &[u8], section_name: let mut imports = wasm_encoder::ImportSection::new(); if sess.target.pointer_width == 64 { - imports.import("env", "__linear_memory", wasm_encoder::MemoryType { - minimum: 0, - maximum: None, - memory64: true, - shared: false, - page_size_log2: None, - }); + imports.import( + "env", + "__linear_memory", + wasm_encoder::MemoryType { + minimum: 0, + maximum: None, + memory64: true, + shared: false, + page_size_log2: None, + }, + ); } if imports.len() > 0 { diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index f8f7bb2dbc6..1dbaffaa577 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -140,11 +140,14 @@ fn reachable_non_generics_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> DefIdMap { if args.non_erasable_generics().next().is_some() { let symbol = ExportedSymbol::Generic(def, args); - symbols.push((symbol, SymbolExportInfo { - level: SymbolExportLevel::Rust, - kind: SymbolExportKind::Text, - used: false, - })); + symbols.push(( + symbol, + SymbolExportInfo { + level: SymbolExportLevel::Rust, + kind: SymbolExportKind::Text, + used: false, + }, + )); } } MonoItem::Fn(Instance { def: InstanceKind::DropGlue(_, Some(ty)), args }) => { // A little sanity-check assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty))); - symbols.push((ExportedSymbol::DropGlue(ty), SymbolExportInfo { - level: SymbolExportLevel::Rust, - kind: SymbolExportKind::Text, - used: false, - })); + symbols.push(( + ExportedSymbol::DropGlue(ty), + SymbolExportInfo { + level: SymbolExportLevel::Rust, + kind: SymbolExportKind::Text, + used: false, + }, + )); } MonoItem::Fn(Instance { def: InstanceKind::AsyncDropGlueCtorShim(_, Some(ty)), @@ -347,11 +377,14 @@ fn exported_symbols_provider_local( }) => { // A little sanity-check assert_eq!(args.non_erasable_generics().next(), Some(GenericArgKind::Type(ty))); - symbols.push((ExportedSymbol::AsyncDropGlueCtorShim(ty), SymbolExportInfo { - level: SymbolExportLevel::Rust, - kind: SymbolExportKind::Text, - used: false, - })); + symbols.push(( + ExportedSymbol::AsyncDropGlueCtorShim(ty), + SymbolExportInfo { + level: SymbolExportLevel::Rust, + kind: SymbolExportKind::Text, + used: false, + }, + )); } _ => { // Any other symbols don't qualify for sharing diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index 4be363ca9a2..a64cee4aa4b 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -1604,10 +1604,10 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { if let Some(slot) = self.personality_slot { slot } else { - let layout = cx.layout_of(Ty::new_tup(cx.tcx(), &[ - Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), - cx.tcx().types.i32, - ])); + let layout = cx.layout_of(Ty::new_tup( + cx.tcx(), + &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32], + )); let slot = PlaceRef::alloca(bx, layout); self.personality_slot = Some(slot); slot diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index 73a41676802..eb4270ffe80 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -474,10 +474,10 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { LocalRef::Operand(..) => { if place_ref.is_indirect_first_projection() { base = 1; - let cg_base = self.codegen_consume(bx, mir::PlaceRef { - projection: &place_ref.projection[..0], - ..place_ref - }); + let cg_base = self.codegen_consume( + bx, + mir::PlaceRef { projection: &place_ref.projection[..0], ..place_ref }, + ); cg_base.deref(bx.cx()) } else { bug!("using operand local {:?} as place", place_ref); diff --git a/compiler/rustc_const_eval/src/check_consts/qualifs.rs b/compiler/rustc_const_eval/src/check_consts/qualifs.rs index 9c99782d223..dfcd1969a73 100644 --- a/compiler/rustc_const_eval/src/check_consts/qualifs.rs +++ b/compiler/rustc_const_eval/src/check_consts/qualifs.rs @@ -188,12 +188,14 @@ impl Qualif for NeedsNonConstDrop { ObligationCause::misc(cx.body.span, cx.def_id()), param_env, ty::Binder::dummy(ty::TraitRef::new(cx.tcx, destruct_def_id, [ty])) - .to_host_effect_clause(cx.tcx, match cx.const_kind() { - rustc_hir::ConstContext::ConstFn => ty::BoundConstness::Maybe, - rustc_hir::ConstContext::Static(_) | rustc_hir::ConstContext::Const { .. } => { - ty::BoundConstness::Const - } - }), + .to_host_effect_clause( + cx.tcx, + match cx.const_kind() { + rustc_hir::ConstContext::ConstFn => ty::BoundConstness::Maybe, + rustc_hir::ConstContext::Static(_) + | rustc_hir::ConstContext::Const { .. } => ty::BoundConstness::Const, + }, + ), )); !ocx.select_all_or_error().is_empty() } diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index a2635885098..8df9877cabc 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -578,10 +578,13 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { } ShiftOverflow { intrinsic, shift_amount } => { diag.arg("intrinsic", intrinsic); - diag.arg("shift_amount", match shift_amount { - Either::Left(v) => v.to_string(), - Either::Right(v) => v.to_string(), - }); + diag.arg( + "shift_amount", + match shift_amount { + Either::Left(v) => v.to_string(), + Either::Right(v) => v.to_string(), + }, + ); } BoundsCheckFailed { len, index } => { diag.arg("len", len); diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index e2e6e16d8a7..cdf706f3752 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -381,10 +381,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { "caller ABI: {:#?}, args: {:#?}", caller_fn_abi, args.iter() - .map(|arg| (arg.layout().ty, match arg { - FnArg::Copy(op) => format!("copy({op:?})"), - FnArg::InPlace(mplace) => format!("in-place({mplace:?})"), - })) + .map(|arg| ( + arg.layout().ty, + match arg { + FnArg::Copy(op) => format!("copy({op:?})"), + FnArg::InPlace(mplace) => format!("in-place({mplace:?})"), + } + )) .collect::>() ); trace!( @@ -874,10 +877,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ); // Check `unwinding`. - assert_eq!(unwinding, match self.frame().loc { - Left(loc) => self.body().basic_blocks[loc.block].is_cleanup, - Right(_) => true, - }); + assert_eq!( + unwinding, + match self.frame().loc { + Left(loc) => self.body().basic_blocks[loc.block].is_cleanup, + Right(_) => true, + } + ); if unwinding && self.frame_idx() == 0 { throw_ub_custom!(fluent::const_eval_unwind_past_top); } diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index 0cbb3b157f3..e14cc1dad36 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -102,11 +102,11 @@ fn intern_as_new_static<'tcx>( alloc_id: AllocId, alloc: ConstAllocation<'tcx>, ) { - let feed = tcx.create_def(static_id, sym::nested, DefKind::Static { - safety: hir::Safety::Safe, - mutability: alloc.0.mutability, - nested: true, - }); + let feed = tcx.create_def( + static_id, + sym::nested, + DefKind::Static { safety: hir::Safety::Safe, mutability: alloc.0.mutability, nested: true }, + ); tcx.set_nested_alloc_id_static(alloc_id, feed.def_id()); if tcx.is_thread_local_static(static_id.into()) { diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 8e544798742..0ac34f4633b 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -812,10 +812,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { if start == 1 && end == max_value { // Only null is the niche. So make sure the ptr is NOT null. if self.ecx.scalar_may_be_null(scalar)? { - throw_validation_failure!(self.path, NullablePtrOutOfRange { - range: valid_range, - max_value - }) + throw_validation_failure!( + self.path, + NullablePtrOutOfRange { range: valid_range, max_value } + ) } else { return interp_ok(()); } @@ -825,10 +825,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { } else { // Conservatively, we reject, because the pointer *could* have a bad // value. - throw_validation_failure!(self.path, PtrOutOfRange { - range: valid_range, - max_value - }) + throw_validation_failure!( + self.path, + PtrOutOfRange { range: valid_range, max_value } + ) } } }; @@ -836,11 +836,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { if valid_range.contains(bits) { interp_ok(()) } else { - throw_validation_failure!(self.path, OutOfRange { - value: format!("{bits}"), - range: valid_range, - max_value - }) + throw_validation_failure!( + self.path, + OutOfRange { value: format!("{bits}"), range: valid_range, max_value } + ) } } diff --git a/compiler/rustc_data_structures/src/graph/dominators/tests.rs b/compiler/rustc_data_structures/src/graph/dominators/tests.rs index ef82193a4b9..6c078ca7c6e 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/tests.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/tests.rs @@ -15,17 +15,10 @@ fn diamond() { #[test] fn paper() { // example from the paper: - let graph = TestGraph::new(6, &[ - (6, 5), - (6, 4), - (5, 1), - (4, 2), - (4, 3), - (1, 2), - (2, 3), - (3, 2), - (2, 1), - ]); + let graph = TestGraph::new( + 6, + &[(6, 5), (6, 4), (5, 1), (4, 2), (4, 3), (1, 2), (2, 3), (3, 2), (2, 1)], + ); let d = dominators(&graph); assert_eq!(d.immediate_dominator(0), None); // <-- note that 0 is not in graph @@ -40,19 +33,10 @@ fn paper() { #[test] fn paper_slt() { // example from the paper: - let graph = TestGraph::new(1, &[ - (1, 2), - (1, 3), - (2, 3), - (2, 7), - (3, 4), - (3, 6), - (4, 5), - (5, 4), - (6, 7), - (7, 8), - (8, 5), - ]); + let graph = TestGraph::new( + 1, + &[(1, 2), (1, 3), (2, 3), (2, 7), (3, 4), (3, 6), (4, 5), (5, 4), (6, 7), (7, 8), (8, 5)], + ); dominators(&graph); } @@ -69,21 +53,24 @@ fn immediate_dominator() { #[test] fn transitive_dominator() { - let graph = TestGraph::new(0, &[ - // First tree branch. - (0, 1), - (1, 2), - (2, 3), - (3, 4), - // Second tree branch. - (1, 5), - (5, 6), - // Third tree branch. - (0, 7), - // These links make 0 the dominator for 2 and 3. - (7, 2), - (5, 3), - ]); + let graph = TestGraph::new( + 0, + &[ + // First tree branch. + (0, 1), + (1, 2), + (2, 3), + (3, 4), + // Second tree branch. + (1, 5), + (5, 6), + // Third tree branch. + (0, 7), + // These links make 0 the dominator for 2 and 3. + (7, 2), + (5, 3), + ], + ); let d = dominators(&graph); assert_eq!(d.immediate_dominator(2), Some(0)); diff --git a/compiler/rustc_data_structures/src/graph/implementation/tests.rs b/compiler/rustc_data_structures/src/graph/implementation/tests.rs index 7a240f4e58b..32a6d9ec881 100644 --- a/compiler/rustc_data_structures/src/graph/implementation/tests.rs +++ b/compiler/rustc_data_structures/src/graph/implementation/tests.rs @@ -110,10 +110,13 @@ fn each_adjacent_from_a() { #[test] fn each_adjacent_from_b() { let graph = create_graph(); - test_adjacent_edges(&graph, NodeIndex(1), "B", &[("FB", "F"), ("AB", "A")], &[ - ("BD", "D"), - ("BC", "C"), - ]); + test_adjacent_edges( + &graph, + NodeIndex(1), + "B", + &[("FB", "F"), ("AB", "A")], + &[("BD", "D"), ("BC", "C")], + ); } #[test] diff --git a/compiler/rustc_data_structures/src/graph/scc/tests.rs b/compiler/rustc_data_structures/src/graph/scc/tests.rs index 7c876c82af2..373f87bfdbc 100644 --- a/compiler/rustc_data_structures/src/graph/scc/tests.rs +++ b/compiler/rustc_data_structures/src/graph/scc/tests.rs @@ -326,46 +326,49 @@ fn test_bug_max_leak_minimised() { #[test] fn test_bug_max_leak() { - let graph = TestGraph::new(8, &[ - (0, 0), - (0, 18), - (0, 19), - (0, 1), - (0, 2), - (0, 7), - (0, 8), - (0, 23), - (18, 0), - (18, 12), - (19, 0), - (19, 25), - (12, 18), - (12, 3), - (12, 5), - (3, 12), - (3, 21), - (3, 22), - (5, 13), - (21, 3), - (22, 3), - (13, 5), - (13, 4), - (4, 13), - (4, 0), - (2, 11), - (7, 6), - (6, 20), - (20, 6), - (8, 17), - (17, 9), - (9, 16), - (16, 26), - (26, 15), - (15, 10), - (10, 14), - (14, 27), - (23, 24), - ]); + let graph = TestGraph::new( + 8, + &[ + (0, 0), + (0, 18), + (0, 19), + (0, 1), + (0, 2), + (0, 7), + (0, 8), + (0, 23), + (18, 0), + (18, 12), + (19, 0), + (19, 25), + (12, 18), + (12, 3), + (12, 5), + (3, 12), + (3, 21), + (3, 22), + (5, 13), + (21, 3), + (22, 3), + (13, 5), + (13, 4), + (4, 13), + (4, 0), + (2, 11), + (7, 6), + (6, 20), + (20, 6), + (8, 17), + (17, 9), + (9, 16), + (16, 26), + (26, 15), + (15, 10), + (10, 14), + (14, 27), + (23, 24), + ], + ); let sccs: MaxReachedSccs = Sccs::new_with_annotation(&graph, |w| match w { 22 => MaxReached(1), 24 => MaxReached(2), diff --git a/compiler/rustc_data_structures/src/obligation_forest/tests.rs b/compiler/rustc_data_structures/src/obligation_forest/tests.rs index 739ef74e3f7..1916a8e2b6b 100644 --- a/compiler/rustc_data_structures/src/obligation_forest/tests.rs +++ b/compiler/rustc_data_structures/src/obligation_forest/tests.rs @@ -349,10 +349,10 @@ fn diamond() { )); assert_eq!(d_count, 1); assert_eq!(ok.len(), 0); - assert_eq!(err, vec![super::Error { - error: "operation failed", - backtrace: vec!["D'", "A'.1", "A'"] - }]); + assert_eq!( + err, + vec![super::Error { error: "operation failed", backtrace: vec!["D'", "A'.1", "A'"] }] + ); let errors = forest.to_errors(()); assert_eq!(errors.len(), 0); diff --git a/compiler/rustc_data_structures/src/vec_cache/tests.rs b/compiler/rustc_data_structures/src/vec_cache/tests.rs index a05f2741362..3b65c14162e 100644 --- a/compiler/rustc_data_structures/src/vec_cache/tests.rs +++ b/compiler/rustc_data_structures/src/vec_cache/tests.rs @@ -58,11 +58,14 @@ fn concurrent_stress_check() { #[test] fn slot_entries_table() { - assert_eq!(ENTRIES_BY_BUCKET, [ - 4096, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304, - 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824, - 2147483648 - ]); + assert_eq!( + ENTRIES_BY_BUCKET, + [ + 4096, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, + 4194304, 8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, + 1073741824, 2147483648 + ] + ); } #[test] diff --git a/compiler/rustc_errors/src/json/tests.rs b/compiler/rustc_errors/src/json/tests.rs index f7892db2961..40973e8e5d8 100644 --- a/compiler/rustc_errors/src/json/tests.rs +++ b/compiler/rustc_errors/src/json/tests.rs @@ -69,96 +69,128 @@ fn test_positions(code: &str, span: (u32, u32), expected_output: SpanTestData) { #[test] fn empty() { - test_positions(" ", (0, 1), SpanTestData { - byte_start: 0, - byte_end: 1, - line_start: 1, - column_start: 1, - line_end: 1, - column_end: 2, - }) + test_positions( + " ", + (0, 1), + SpanTestData { + byte_start: 0, + byte_end: 1, + line_start: 1, + column_start: 1, + line_end: 1, + column_end: 2, + }, + ) } #[test] fn bom() { - test_positions("\u{feff} ", (0, 1), SpanTestData { - byte_start: 3, - byte_end: 4, - line_start: 1, - column_start: 1, - line_end: 1, - column_end: 2, - }) + test_positions( + "\u{feff} ", + (0, 1), + SpanTestData { + byte_start: 3, + byte_end: 4, + line_start: 1, + column_start: 1, + line_end: 1, + column_end: 2, + }, + ) } #[test] fn lf_newlines() { - test_positions("\nmod foo;\nmod bar;\n", (5, 12), SpanTestData { - byte_start: 5, - byte_end: 12, - line_start: 2, - column_start: 5, - line_end: 3, - column_end: 3, - }) + test_positions( + "\nmod foo;\nmod bar;\n", + (5, 12), + SpanTestData { + byte_start: 5, + byte_end: 12, + line_start: 2, + column_start: 5, + line_end: 3, + column_end: 3, + }, + ) } #[test] fn crlf_newlines() { - test_positions("\r\nmod foo;\r\nmod bar;\r\n", (5, 12), SpanTestData { - byte_start: 6, - byte_end: 14, - line_start: 2, - column_start: 5, - line_end: 3, - column_end: 3, - }) + test_positions( + "\r\nmod foo;\r\nmod bar;\r\n", + (5, 12), + SpanTestData { + byte_start: 6, + byte_end: 14, + line_start: 2, + column_start: 5, + line_end: 3, + column_end: 3, + }, + ) } #[test] fn crlf_newlines_with_bom() { - test_positions("\u{feff}\r\nmod foo;\r\nmod bar;\r\n", (5, 12), SpanTestData { - byte_start: 9, - byte_end: 17, - line_start: 2, - column_start: 5, - line_end: 3, - column_end: 3, - }) + test_positions( + "\u{feff}\r\nmod foo;\r\nmod bar;\r\n", + (5, 12), + SpanTestData { + byte_start: 9, + byte_end: 17, + line_start: 2, + column_start: 5, + line_end: 3, + column_end: 3, + }, + ) } #[test] fn span_before_crlf() { - test_positions("foo\r\nbar", (2, 3), SpanTestData { - byte_start: 2, - byte_end: 3, - line_start: 1, - column_start: 3, - line_end: 1, - column_end: 4, - }) + test_positions( + "foo\r\nbar", + (2, 3), + SpanTestData { + byte_start: 2, + byte_end: 3, + line_start: 1, + column_start: 3, + line_end: 1, + column_end: 4, + }, + ) } #[test] fn span_on_crlf() { - test_positions("foo\r\nbar", (3, 4), SpanTestData { - byte_start: 3, - byte_end: 5, - line_start: 1, - column_start: 4, - line_end: 2, - column_end: 1, - }) + test_positions( + "foo\r\nbar", + (3, 4), + SpanTestData { + byte_start: 3, + byte_end: 5, + line_start: 1, + column_start: 4, + line_end: 2, + column_end: 1, + }, + ) } #[test] fn span_after_crlf() { - test_positions("foo\r\nbar", (4, 5), SpanTestData { - byte_start: 5, - byte_end: 6, - line_start: 2, - column_start: 1, - line_end: 2, - column_end: 2, - }) + test_positions( + "foo\r\nbar", + (4, 5), + SpanTestData { + byte_start: 5, + byte_end: 6, + line_start: 2, + column_start: 1, + line_end: 2, + column_end: 2, + }, + ) } diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 8bf09cf96b3..046213b5a6a 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -233,11 +233,14 @@ impl<'a> ExtCtxt<'a> { } pub fn block_expr(&self, expr: P) -> P { - self.block(expr.span, thin_vec![ast::Stmt { - id: ast::DUMMY_NODE_ID, - span: expr.span, - kind: ast::StmtKind::Expr(expr), - }]) + self.block( + expr.span, + thin_vec![ast::Stmt { + id: ast::DUMMY_NODE_ID, + span: expr.span, + kind: ast::StmtKind::Expr(expr), + }], + ) } pub fn block(&self, span: Span, stmts: ThinVec) -> P { P(ast::Block { diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 7ac9f453bae..b02a9b93c8a 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -405,26 +405,35 @@ pub fn compile_declarative_macro( // ...quasiquoting this would be nice. // These spans won't matter, anyways let argument_gram = vec![ - mbe::TokenTree::Sequence(DelimSpan::dummy(), mbe::SequenceRepetition { - tts: vec![ - mbe::TokenTree::MetaVarDecl(span, lhs_nm, tt_spec), - mbe::TokenTree::token(token::FatArrow, span), - mbe::TokenTree::MetaVarDecl(span, rhs_nm, tt_spec), - ], - separator: Some(Token::new(if macro_rules { token::Semi } else { token::Comma }, span)), - kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, span), - num_captures: 2, - }), + mbe::TokenTree::Sequence( + DelimSpan::dummy(), + mbe::SequenceRepetition { + tts: vec![ + mbe::TokenTree::MetaVarDecl(span, lhs_nm, tt_spec), + mbe::TokenTree::token(token::FatArrow, span), + mbe::TokenTree::MetaVarDecl(span, rhs_nm, tt_spec), + ], + separator: Some(Token::new( + if macro_rules { token::Semi } else { token::Comma }, + span, + )), + kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, span), + num_captures: 2, + }, + ), // to phase into semicolon-termination instead of semicolon-separation - mbe::TokenTree::Sequence(DelimSpan::dummy(), mbe::SequenceRepetition { - tts: vec![mbe::TokenTree::token( - if macro_rules { token::Semi } else { token::Comma }, - span, - )], - separator: None, - kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, span), - num_captures: 0, - }), + mbe::TokenTree::Sequence( + DelimSpan::dummy(), + mbe::SequenceRepetition { + tts: vec![mbe::TokenTree::token( + if macro_rules { token::Semi } else { token::Comma }, + span, + )], + separator: None, + kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, span), + num_captures: 0, + }, + ), ]; // Convert it into `MatcherLoc` form. let argument_gram = mbe::macro_parser::compute_locs(&argument_gram); diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index a27d47892e4..b9a06157907 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -179,10 +179,10 @@ fn parse_tree<'a>( Some(&tokenstream::TokenTree::Delimited(delim_span, _, delim, ref tts)) => { if parsing_patterns { if delim != Delimiter::Parenthesis { - span_dollar_dollar_or_metavar_in_the_lhs_err(sess, &Token { - kind: token::OpenDelim(delim), - span: delim_span.entire(), - }); + span_dollar_dollar_or_metavar_in_the_lhs_err( + sess, + &Token { kind: token::OpenDelim(delim), span: delim_span.entire() }, + ); } } else { match delim { @@ -235,12 +235,10 @@ fn parse_tree<'a>( // Count the number of captured "names" (i.e., named metavars) let num_captures = if parsing_patterns { count_metavar_decls(&sequence) } else { 0 }; - TokenTree::Sequence(delim_span, SequenceRepetition { - tts: sequence, - separator, - kleene, - num_captures, - }) + TokenTree::Sequence( + delim_span, + SequenceRepetition { tts: sequence, separator, kleene, num_captures }, + ) } // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` @@ -261,10 +259,10 @@ fn parse_tree<'a>( _, )) => { if parsing_patterns { - span_dollar_dollar_or_metavar_in_the_lhs_err(sess, &Token { - kind: token::Dollar, - span: dollar_span2, - }); + span_dollar_dollar_or_metavar_in_the_lhs_err( + sess, + &Token { kind: token::Dollar, span: dollar_span2 }, + ); } else { maybe_emit_macro_metavar_expr_feature(features, sess, dollar_span2); } @@ -289,12 +287,14 @@ fn parse_tree<'a>( // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to // descend into the delimited set and further parse it. - &tokenstream::TokenTree::Delimited(span, spacing, delim, ref tts) => { - TokenTree::Delimited(span, spacing, Delimited { + &tokenstream::TokenTree::Delimited(span, spacing, delim, ref tts) => TokenTree::Delimited( + span, + spacing, + Delimited { delim, tts: parse(tts, parsing_patterns, sess, node_id, features, edition), - }) - } + }, + ), } } diff --git a/compiler/rustc_graphviz/src/tests.rs b/compiler/rustc_graphviz/src/tests.rs index 712620a2000..bf2f43fde2e 100644 --- a/compiler/rustc_graphviz/src/tests.rs +++ b/compiler/rustc_graphviz/src/tests.rs @@ -360,12 +360,16 @@ fn left_aligned_text() { let mut writer = Vec::new(); - let g = LabelledGraphWithEscStrs::new("syntax_tree", labels, vec![ - edge(0, 1, "then", Style::None), - edge(0, 2, "else", Style::None), - edge(1, 3, ";", Style::None), - edge(2, 3, ";", Style::None), - ]); + let g = LabelledGraphWithEscStrs::new( + "syntax_tree", + labels, + vec![ + edge(0, 1, "then", Style::None), + edge(0, 2, "else", Style::None), + edge(1, 3, ";", Style::None), + edge(2, 3, ";", Style::None), + ], + ); render(&g, &mut writer).unwrap(); let mut r = String::new(); diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index e7b6a97c9d9..eafc60f9d72 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -3101,10 +3101,10 @@ impl<'hir> Ty<'hir> { fn visit_ty(&mut self, t: &'v Ty<'v, AmbigArg>) { if matches!( &t.kind, - TyKind::Path(QPath::Resolved(_, Path { - res: crate::def::Res::SelfTyAlias { .. }, - .. - },)) + TyKind::Path(QPath::Resolved( + _, + Path { res: crate::def::Res::SelfTyAlias { .. }, .. }, + )) ) { self.0.push(t.span); return; @@ -3446,11 +3446,10 @@ impl<'hir> InlineAsmOperand<'hir> { } pub fn is_clobber(&self) -> bool { - matches!(self, InlineAsmOperand::Out { - reg: InlineAsmRegOrRegClass::Reg(_), - late: _, - expr: None - }) + matches!( + self, + InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None } + ) } } diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index a91d72e9225..bb5087e864c 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -182,12 +182,15 @@ fn compare_method_predicate_entailment<'tcx>( // obligations. let impl_m_def_id = impl_m.def_id.expect_local(); let impl_m_span = tcx.def_span(impl_m_def_id); - let cause = - ObligationCause::new(impl_m_span, impl_m_def_id, ObligationCauseCode::CompareImplItem { + let cause = ObligationCause::new( + impl_m_span, + impl_m_def_id, + ObligationCauseCode::CompareImplItem { impl_item_def_id: impl_m_def_id, trait_item_def_id: trait_m.def_id, kind: impl_m.kind, - }); + }, + ); // Create mapping from trait method to impl method. let impl_def_id = impl_m.container_id(tcx); @@ -248,12 +251,15 @@ fn compare_method_predicate_entailment<'tcx>( let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id); let predicate = ocx.normalize(&normalize_cause, param_env, predicate); - let cause = - ObligationCause::new(span, impl_m_def_id, ObligationCauseCode::CompareImplItem { + let cause = ObligationCause::new( + span, + impl_m_def_id, + ObligationCauseCode::CompareImplItem { impl_item_def_id: impl_m_def_id, trait_item_def_id: trait_m.def_id, kind: impl_m.kind, - }); + }, + ); ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate)); } @@ -270,12 +276,15 @@ fn compare_method_predicate_entailment<'tcx>( let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id); let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition); - let cause = - ObligationCause::new(span, impl_m_def_id, ObligationCauseCode::CompareImplItem { + let cause = ObligationCause::new( + span, + impl_m_def_id, + ObligationCauseCode::CompareImplItem { impl_item_def_id: impl_m_def_id, trait_item_def_id: trait_m.def_id, kind: impl_m.kind, - }); + }, + ); ocx.register_obligation(traits::Obligation::new( tcx, cause, @@ -493,12 +502,15 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( let impl_m_hir_id = tcx.local_def_id_to_hir_id(impl_m_def_id); let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span(); - let cause = - ObligationCause::new(return_span, impl_m_def_id, ObligationCauseCode::CompareImplItem { + let cause = ObligationCause::new( + return_span, + impl_m_def_id, + ObligationCauseCode::CompareImplItem { impl_item_def_id: impl_m_def_id, trait_item_def_id: trait_m.def_id, kind: impl_m.kind, - }); + }, + ); // Create mapping from trait to impl (i.e. impl trait header + impl method identity args). let trait_to_impl_args = GenericArgs::identity_for_item(tcx, impl_m.def_id).rebase_onto( @@ -534,12 +546,15 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id); let predicate = ocx.normalize(&normalize_cause, param_env, predicate); - let cause = - ObligationCause::new(span, impl_m_def_id, ObligationCauseCode::CompareImplItem { + let cause = ObligationCause::new( + span, + impl_m_def_id, + ObligationCauseCode::CompareImplItem { impl_item_def_id: impl_m_def_id, trait_item_def_id: trait_m.def_id, kind: impl_m.kind, - }); + }, + ); ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate)); } @@ -606,13 +621,16 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( idx += 1; ( ty, - Ty::new_placeholder(tcx, ty::Placeholder { - universe, - bound: ty::BoundTy { - var: ty::BoundVar::from_usize(idx), - kind: ty::BoundTyKind::Anon, + Ty::new_placeholder( + tcx, + ty::Placeholder { + universe, + bound: ty::BoundTy { + var: ty::BoundVar::from_usize(idx), + kind: ty::BoundTyKind::Anon, + }, }, - }), + ), ) }) .collect(); @@ -969,10 +987,13 @@ impl<'tcx> ty::FallibleTypeFolder> for RemapHiddenTyRegions<'tcx> { return Err(guar); }; - Ok(ty::Region::new_early_param(self.tcx, ty::EarlyParamRegion { - name: e.name, - index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32, - })) + Ok(ty::Region::new_early_param( + self.tcx, + ty::EarlyParamRegion { + name: e.name, + index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32, + }, + )) } } @@ -1967,12 +1988,15 @@ fn compare_type_predicate_entailment<'tcx>( let cause = ObligationCause::misc(span, impl_ty_def_id); let predicate = ocx.normalize(&cause, param_env, predicate); - let cause = - ObligationCause::new(span, impl_ty_def_id, ObligationCauseCode::CompareImplItem { + let cause = ObligationCause::new( + span, + impl_ty_def_id, + ObligationCauseCode::CompareImplItem { impl_item_def_id: impl_ty.def_id.expect_local(), trait_item_def_id: trait_ty.def_id, kind: impl_ty.kind, - }); + }, + ); ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate)); } @@ -1984,12 +2008,15 @@ fn compare_type_predicate_entailment<'tcx>( let normalize_cause = traits::ObligationCause::misc(span, impl_ty_def_id); let const_condition = ocx.normalize(&normalize_cause, param_env, const_condition); - let cause = - ObligationCause::new(span, impl_ty_def_id, ObligationCauseCode::CompareImplItem { + let cause = ObligationCause::new( + span, + impl_ty_def_id, + ObligationCauseCode::CompareImplItem { impl_item_def_id: impl_ty_def_id, trait_item_def_id: trait_ty.def_id, kind: impl_ty.kind, - }); + }, + ); ocx.register_obligation(traits::Obligation::new( tcx, cause, @@ -2244,20 +2271,25 @@ fn param_env_with_gat_bounds<'tcx>( let kind = ty::BoundTyKind::Param(param.def_id, param.name); let bound_var = ty::BoundVariableKind::Ty(kind); bound_vars.push(bound_var); - Ty::new_bound(tcx, ty::INNERMOST, ty::BoundTy { - var: ty::BoundVar::from_usize(bound_vars.len() - 1), - kind, - }) + Ty::new_bound( + tcx, + ty::INNERMOST, + ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind }, + ) .into() } GenericParamDefKind::Lifetime => { let kind = ty::BoundRegionKind::Named(param.def_id, param.name); let bound_var = ty::BoundVariableKind::Region(kind); bound_vars.push(bound_var); - ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { - var: ty::BoundVar::from_usize(bound_vars.len() - 1), - kind, - }) + ty::Region::new_bound( + tcx, + ty::INNERMOST, + ty::BoundRegion { + var: ty::BoundVar::from_usize(bound_vars.len() - 1), + kind, + }, + ) .into() } GenericParamDefKind::Const { .. } => { diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 40769ef7536..08e0e52a492 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -185,14 +185,19 @@ pub fn check_intrinsic_type( ]); let mk_va_list_ty = |mutbl| { tcx.lang_items().va_list().map(|did| { - let region = ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { - var: ty::BoundVar::ZERO, - kind: ty::BoundRegionKind::Anon, - }); - let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { - var: ty::BoundVar::from_u32(2), - kind: ty::BoundRegionKind::ClosureEnv, - }); + let region = ty::Region::new_bound( + tcx, + ty::INNERMOST, + ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::Anon }, + ); + let env_region = ty::Region::new_bound( + tcx, + ty::INNERMOST, + ty::BoundRegion { + var: ty::BoundVar::from_u32(2), + kind: ty::BoundRegionKind::ClosureEnv, + }, + ); let va_list_ty = tcx.type_of(did).instantiate(tcx, &[region.into()]); (Ty::new_ref(tcx, env_region, va_list_ty, mutbl), va_list_ty) }) diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 20eb96f3ab1..1689437ffb0 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -675,10 +675,10 @@ fn gather_gat_bounds<'tcx, T: TypeFoldable>>( // Same for the region. In our example, 'a corresponds // to the 'me parameter. let region_param = gat_generics.param_at(*region_a_idx, tcx); - let region_param = ty::Region::new_early_param(tcx, ty::EarlyParamRegion { - index: region_param.index, - name: region_param.name, - }); + let region_param = ty::Region::new_early_param( + tcx, + ty::EarlyParamRegion { index: region_param.index, name: region_param.name }, + ); // The predicate we expect to see. (In our example, // `Self: 'me`.) bounds.insert( @@ -704,16 +704,16 @@ fn gather_gat_bounds<'tcx, T: TypeFoldable>>( debug!("required clause: {region_a} must outlive {region_b}"); // Translate into the generic parameters of the GAT. let region_a_param = gat_generics.param_at(*region_a_idx, tcx); - let region_a_param = ty::Region::new_early_param(tcx, ty::EarlyParamRegion { - index: region_a_param.index, - name: region_a_param.name, - }); + let region_a_param = ty::Region::new_early_param( + tcx, + ty::EarlyParamRegion { index: region_a_param.index, name: region_a_param.name }, + ); // Same for the region. let region_b_param = gat_generics.param_at(*region_b_idx, tcx); - let region_b_param = ty::Region::new_early_param(tcx, ty::EarlyParamRegion { - index: region_b_param.index, - name: region_b_param.name, - }); + let region_b_param = ty::Region::new_early_param( + tcx, + ty::EarlyParamRegion { index: region_b_param.index, name: region_b_param.name }, + ); // The predicate we expect to see. bounds.insert( ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate( @@ -1647,10 +1647,15 @@ fn check_fn_or_method<'tcx>( } // If the function has a body, additionally require that the return type is sized. - check_sized_if_body(wfcx, def_id, sig.output(), match hir_decl.output { - hir::FnRetTy::Return(ty) => Some(ty.span), - hir::FnRetTy::DefaultReturn(_) => None, - }); + check_sized_if_body( + wfcx, + def_id, + sig.output(), + match hir_decl.output { + hir::FnRetTy::Return(ty) => Some(ty.span), + hir::FnRetTy::DefaultReturn(_) => None, + }, + ); } fn check_sized_if_body<'tcx>( diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 3511dbc6252..66082f4c282 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -333,10 +333,11 @@ fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<() tcx, cause.clone(), param_env, - ty::TraitRef::new(tcx, dispatch_from_dyn_trait, [ - field.ty(tcx, args_a), - field.ty(tcx, args_b), - ]), + ty::TraitRef::new( + tcx, + dispatch_from_dyn_trait, + [field.ty(tcx, args_a), field.ty(tcx, args_b)], + ), )); } let errors = ocx.select_all_or_error(); diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs index 5127e73d978..c72f6201831 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs @@ -251,10 +251,13 @@ impl<'tcx> InherentOverlapChecker<'tcx> { for ident in &idents_to_add { connected_region_ids.insert(*ident, id_to_set); } - connected_regions.insert(id_to_set, ConnectedRegion { - idents: idents_to_add, - impl_blocks: std::iter::once(i).collect(), - }); + connected_regions.insert( + id_to_set, + ConnectedRegion { + idents: idents_to_add, + impl_blocks: std::iter::once(i).collect(), + }, + ); } // Take the only id inside the list &[id_to_set] => { diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index e37a11b6844..d2e2ab1da77 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -242,10 +242,11 @@ impl<'tcx> TypeFolder> for MapAndCompressBoundVars<'tcx> { // Allocate a new var idx, and insert a new bound ty. let var = ty::BoundVar::from_usize(self.still_bound_vars.len()); self.still_bound_vars.push(ty::BoundVariableKind::Ty(old_bound.kind)); - let mapped = Ty::new_bound(self.tcx, ty::INNERMOST, ty::BoundTy { - var, - kind: old_bound.kind, - }); + let mapped = Ty::new_bound( + self.tcx, + ty::INNERMOST, + ty::BoundTy { var, kind: old_bound.kind }, + ); self.mapping.insert(old_bound.var, mapped.into()); mapped }; @@ -265,10 +266,11 @@ impl<'tcx> TypeFolder> for MapAndCompressBoundVars<'tcx> { } else { let var = ty::BoundVar::from_usize(self.still_bound_vars.len()); self.still_bound_vars.push(ty::BoundVariableKind::Region(old_bound.kind)); - let mapped = ty::Region::new_bound(self.tcx, ty::INNERMOST, ty::BoundRegion { - var, - kind: old_bound.kind, - }); + let mapped = ty::Region::new_bound( + self.tcx, + ty::INNERMOST, + ty::BoundRegion { var, kind: old_bound.kind }, + ); self.mapping.insert(old_bound.var, mapped.into()); mapped }; diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 8a975786a92..d94383d6f3d 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -350,10 +350,10 @@ fn compute_bidirectional_outlives_predicates<'tcx>( for param in opaque_own_params { let orig_lifetime = tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()); if let ty::ReEarlyParam(..) = *orig_lifetime { - let dup_lifetime = ty::Region::new_early_param(tcx, ty::EarlyParamRegion { - index: param.index, - name: param.name, - }); + let dup_lifetime = ty::Region::new_early_param( + tcx, + ty::EarlyParamRegion { index: param.index, name: param.name }, + ); let span = tcx.def_span(param.def_id); predicates.push(( ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(orig_lifetime, dup_lifetime)) diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index 76006354717..c03a1f6240f 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -1143,20 +1143,23 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { .params .iter() .map(|param| { - (param.def_id, match param.kind { - GenericParamKind::Lifetime { .. } => { - if self.tcx.is_late_bound(param.hir_id) { - let late_bound_idx = named_late_bound_vars; - named_late_bound_vars += 1; - ResolvedArg::late(late_bound_idx, param) - } else { + ( + param.def_id, + match param.kind { + GenericParamKind::Lifetime { .. } => { + if self.tcx.is_late_bound(param.hir_id) { + let late_bound_idx = named_late_bound_vars; + named_late_bound_vars += 1; + ResolvedArg::late(late_bound_idx, param) + } else { + ResolvedArg::early(param) + } + } + GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { ResolvedArg::early(param) } - } - GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { - ResolvedArg::early(param) - } - }) + }, + ) }) .collect(); diff --git a/compiler/rustc_hir_analysis/src/delegation.rs b/compiler/rustc_hir_analysis/src/delegation.rs index ed45833b614..4dbdfa3d85a 100644 --- a/compiler/rustc_hir_analysis/src/delegation.rs +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -41,10 +41,10 @@ impl<'tcx> TypeFolder> for ParamIndexRemapper<'tcx> { if let ty::ReEarlyParam(param) = r.kind() && let Some(index) = self.remap_table.get(¶m.index).copied() { - return ty::Region::new_early_param(self.tcx, ty::EarlyParamRegion { - index, - name: param.name, - }); + return ty::Region::new_early_param( + self.tcx, + ty::EarlyParamRegion { index, name: param.name }, + ); } r } diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs index e949d4a1126..2834d497694 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -640,13 +640,15 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let mut num_bound_vars = candidate.bound_vars().len(); let args = candidate.skip_binder().args.extend_to(tcx, item_def_id, |param, _| { let arg = match param.kind { - ty::GenericParamDefKind::Lifetime => { - ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { + ty::GenericParamDefKind::Lifetime => ty::Region::new_bound( + tcx, + ty::INNERMOST, + ty::BoundRegion { var: ty::BoundVar::from_usize(num_bound_vars), kind: ty::BoundRegionKind::Named(param.def_id, param.name), - }) - .into() - } + }, + ) + .into(), ty::GenericParamDefKind::Type { .. } => { let guar = *emitted_bad_param_err.get_or_insert_with(|| { self.dcx().emit_err(crate::errors::ReturnTypeNotationIllegalParam::Type { diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs index e59ff02642c..a8b37fa5054 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs @@ -107,12 +107,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let mut needed_associated_types = FxIndexSet::default(); if let Some((principal_trait, spans)) = &principal_trait { let pred: ty::Predicate<'tcx> = (*principal_trait).upcast(tcx); - for ClauseWithSupertraitSpan { pred, supertrait_span } in - traits::elaborate(tcx, [ClauseWithSupertraitSpan::new( - pred, - *spans.last().unwrap(), - )]) - .filter_only_self() + for ClauseWithSupertraitSpan { pred, supertrait_span } in traits::elaborate( + tcx, + [ClauseWithSupertraitSpan::new(pred, *spans.last().unwrap())], + ) + .filter_only_self() { debug!("observing object predicate `{pred:?}`"); diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 079e8921627..ffddf6f73aa 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -2219,10 +2219,13 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { match self.try_lower_anon_const_lit(ty, expr) { Some(v) => v, - None => ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst { - def: anon.def_id.to_def_id(), - args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()), - }), + None => ty::Const::new_unevaluated( + tcx, + ty::UnevaluatedConst { + def: anon.def_id.to_def_id(), + args: ty::GenericArgs::identity_for_item(tcx, anon.def_id.to_def_id()), + }, + ), } } diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index fb1df518a88..57df3127a02 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -2226,10 +2226,13 @@ impl<'a> State<'a> { let generic_params = generic_params .iter() .filter(|p| { - matches!(p, GenericParam { - kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit }, - .. - }) + matches!( + p, + GenericParam { + kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit }, + .. + } + ) }) .collect::>(); diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index edc3702d90b..f2d0b911731 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -153,13 +153,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { closure_sig, ); let adjustments = self.adjust_steps(autoderef); - self.record_deferred_call_resolution(def_id, DeferredCallResolution { - call_expr, - callee_expr, - closure_ty: adjusted_ty, - adjustments, - fn_sig: closure_sig, - }); + self.record_deferred_call_resolution( + def_id, + DeferredCallResolution { + call_expr, + callee_expr, + closure_ty: adjusted_ty, + adjustments, + fn_sig: closure_sig, + }, + ); return Some(CallStep::DeferredClosure(def_id, closure_sig)); } @@ -196,13 +199,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { coroutine_closure_sig.abi, ); let adjustments = self.adjust_steps(autoderef); - self.record_deferred_call_resolution(def_id, DeferredCallResolution { - call_expr, - callee_expr, - closure_ty: adjusted_ty, - adjustments, - fn_sig: call_sig, - }); + self.record_deferred_call_resolution( + def_id, + DeferredCallResolution { + call_expr, + callee_expr, + closure_ty: adjusted_ty, + adjustments, + fn_sig: call_sig, + }, + ); return Some(CallStep::DeferredClosure(def_id, call_sig)); } diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 65021a0cd11..d8015bcc914 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -666,11 +666,12 @@ impl<'a, 'tcx> CastCheck<'tcx> { }; let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty); let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty); - fcx.tcx.emit_node_span_lint(lint, self.expr.hir_id, self.span, errors::TrivialCast { - numeric, - expr_ty, - cast_ty, - }); + fcx.tcx.emit_node_span_lint( + lint, + self.expr.hir_id, + self.span, + errors::TrivialCast { numeric, expr_ty, cast_ty }, + ); } #[instrument(skip(fcx), level = "debug")] diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index 9fdc5a0ae4e..6fb5f6af091 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -186,18 +186,21 @@ fn check_panic_info_fn(tcx: TyCtxt<'_>, fn_id: LocalDefId, fn_sig: ty::FnSig<'_> let panic_info_did = tcx.require_lang_item(hir::LangItem::PanicInfo, Some(span)); // build type `for<'a, 'b> fn(&'a PanicInfo<'b>) -> !` - let panic_info_ty = tcx.type_of(panic_info_did).instantiate(tcx, &[ty::GenericArg::from( - ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { - var: ty::BoundVar::from_u32(1), - kind: ty::BoundRegionKind::Anon, - }), - )]); + let panic_info_ty = tcx.type_of(panic_info_did).instantiate( + tcx, + &[ty::GenericArg::from(ty::Region::new_bound( + tcx, + ty::INNERMOST, + ty::BoundRegion { var: ty::BoundVar::from_u32(1), kind: ty::BoundRegionKind::Anon }, + ))], + ); let panic_info_ref_ty = Ty::new_imm_ref( tcx, - ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { - var: ty::BoundVar::ZERO, - kind: ty::BoundRegionKind::Anon, - }), + ty::Region::new_bound( + tcx, + ty::INNERMOST, + ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::Anon }, + ), panic_info_ty, ); diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 62dfffb560b..43124f44ca6 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -103,12 +103,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => self.next_ty_var(expr_span), }; - let closure_args = ty::ClosureArgs::new(tcx, ty::ClosureArgsParts { - parent_args, - closure_kind_ty, - closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig), - tupled_upvars_ty, - }); + let closure_args = ty::ClosureArgs::new( + tcx, + ty::ClosureArgsParts { + parent_args, + closure_kind_ty, + closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig), + tupled_upvars_ty, + }, + ); (Ty::new_closure(tcx, expr_def_id.to_def_id(), closure_args.args), None) } @@ -177,15 +180,18 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => tcx.types.unit, }; - let coroutine_args = ty::CoroutineArgs::new(tcx, ty::CoroutineArgsParts { - parent_args, - kind_ty, - resume_ty, - yield_ty, - return_ty: liberated_sig.output(), - witness: interior, - tupled_upvars_ty, - }); + let coroutine_args = ty::CoroutineArgs::new( + tcx, + ty::CoroutineArgsParts { + parent_args, + kind_ty, + resume_ty, + yield_ty, + return_ty: liberated_sig.output(), + witness: interior, + tupled_upvars_ty, + }, + ); ( Ty::new_coroutine(tcx, expr_def_id.to_def_id(), coroutine_args.args), @@ -216,8 +222,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let coroutine_captures_by_ref_ty = self.next_ty_var(expr_span); - let closure_args = - ty::CoroutineClosureArgs::new(tcx, ty::CoroutineClosureArgsParts { + let closure_args = ty::CoroutineClosureArgs::new( + tcx, + ty::CoroutineClosureArgsParts { parent_args, closure_kind_ty, signature_parts_ty: Ty::new_fn_ptr( @@ -238,7 +245,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { tupled_upvars_ty, coroutine_captures_by_ref_ty, coroutine_witness_ty: interior, - }); + }, + ); let coroutine_kind_ty = match expected_kind { Some(kind) => Ty::from_coroutine_closure_kind(tcx, kind), diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 56cc9b6d551..14dd0f32d82 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -555,18 +555,24 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // the reborrow in coerce_borrowed_ptr will pick it up. let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No); - Some((Adjustment { kind: Adjust::Deref(None), target: ty_a }, Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), - target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b), - })) + Some(( + Adjustment { kind: Adjust::Deref(None), target: ty_a }, + Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(mutbl)), + target: Ty::new_ref(self.tcx, r_borrow, ty_a, mutbl_b), + }, + )) } (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(_, mt_b)) => { coerce_mutbls(mt_a, mt_b)?; - Some((Adjustment { kind: Adjust::Deref(None), target: ty_a }, Adjustment { - kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)), - target: Ty::new_ptr(self.tcx, ty_a, mt_b), - })) + Some(( + Adjustment { kind: Adjust::Deref(None), target: ty_a }, + Adjustment { + kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)), + target: Ty::new_ptr(self.tcx, ty_a, mt_b), + }, + )) } _ => None, }; @@ -1033,10 +1039,10 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // regionck knows that the region for `a` must be valid here. if is_ref { self.unify_and(a_unsafe, b, |target| { - vec![Adjustment { kind: Adjust::Deref(None), target: mt_a.ty }, Adjustment { - kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), - target, - }] + vec![ + Adjustment { kind: Adjust::Deref(None), target: mt_a.ty }, + Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target }, + ] }) } else if mt_a.mutbl != mutbl_b { self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCoercion::MutToConstPointer))) @@ -1288,10 +1294,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"), }; for expr in exprs.iter().map(|e| e.as_coercion_site()) { - self.apply_adjustments(expr, vec![Adjustment { - kind: prev_adjustment.clone(), - target: fn_ptr, - }]); + self.apply_adjustments( + expr, + vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }], + ); } self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]); return Ok(fn_ptr); diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 49f712090f0..9dd965a4dcb 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -84,10 +84,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let adj_ty = self.next_ty_var(expr.span); - self.apply_adjustments(expr, vec![Adjustment { - kind: Adjust::NeverToAny, - target: adj_ty, - }]); + self.apply_adjustments( + expr, + vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }], + ); ty = adj_ty; } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 9277d71234f..6bb8cf5f331 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -290,10 +290,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let autoborrow_mut = adj.iter().any(|adj| { - matches!(adj, &Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Mut { .. })), - .. - }) + matches!( + adj, + &Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Mut { .. })), + .. + } + ) }); match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) { @@ -972,11 +975,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut sp = MultiSpan::from_span(path_segment.ident.span); sp.push_span_label( path_segment.ident.span, - format!("this call modifies {} in-place", match rcvr.kind { - ExprKind::Path(QPath::Resolved(None, hir::Path { segments: [segment], .. })) => - format!("`{}`", segment.ident), - _ => "its receiver".to_string(), - }), + format!( + "this call modifies {} in-place", + match rcvr.kind { + ExprKind::Path(QPath::Resolved( + None, + hir::Path { segments: [segment], .. }, + )) => format!("`{}`", segment.ident), + _ => "its receiver".to_string(), + } + ), ); let modifies_rcvr_note = diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 217ebd9cd2b..4ec8d0b1f60 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -1988,17 +1988,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr.kind, hir::ExprKind::Call( hir::Expr { - kind: hir::ExprKind::Path(hir::QPath::Resolved(None, hir::Path { - res: Res::Def(hir::def::DefKind::Ctor(_, _), _), - .. - },)), + kind: hir::ExprKind::Path(hir::QPath::Resolved( + None, + hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. }, + )), .. }, .., - ) | hir::ExprKind::Path(hir::QPath::Resolved(None, hir::Path { - res: Res::Def(hir::def::DefKind::Ctor(_, _), _), - .. - },)), + ) | hir::ExprKind::Path(hir::QPath::Resolved( + None, + hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. }, + )), ); let (article, kind, variant, sugg_operator) = diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index cbbda0b6cbc..6c4ad65be6a 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -3922,11 +3922,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let all_suggs = candidate_strs.iter().map(|cand| { - let suggestion = format!("{} {cand}", match introducer { - Introducer::Plus => " +", - Introducer::Colon => ":", - Introducer::Nothing => "", - },); + let suggestion = format!( + "{} {cand}", + match introducer { + Introducer::Plus => " +", + Introducer::Colon => ":", + Introducer::Nothing => "", + }, + ); let mut suggs = vec![]; diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index 47c1f784448..fc07c985849 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -918,13 +918,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let opname = Ident::with_dummy_span(opname); let (opt_rhs_expr, opt_rhs_ty) = opt_rhs.unzip(); - let cause = self.cause(span, ObligationCauseCode::BinOp { - lhs_hir_id: lhs_expr.hir_id, - rhs_hir_id: opt_rhs_expr.map(|expr| expr.hir_id), - rhs_span: opt_rhs_expr.map(|expr| expr.span), - rhs_is_lit: opt_rhs_expr.is_some_and(|expr| matches!(expr.kind, hir::ExprKind::Lit(_))), - output_ty: expected.only_has_type(self), - }); + let cause = self.cause( + span, + ObligationCauseCode::BinOp { + lhs_hir_id: lhs_expr.hir_id, + rhs_hir_id: opt_rhs_expr.map(|expr| expr.hir_id), + rhs_span: opt_rhs_expr.map(|expr| expr.span), + rhs_is_lit: opt_rhs_expr + .is_some_and(|expr| matches!(expr.kind, hir::ExprKind::Lit(_))), + output_ty: expected.only_has_type(self), + }, + ); let method = self.lookup_method_in_trait(cause.clone(), opname, trait_did, lhs_ty, opt_rhs_ty); diff --git a/compiler/rustc_hir_typeck/src/place_op.rs b/compiler/rustc_hir_typeck/src/place_op.rs index e1bd9ae2e67..4fc903cf68b 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -30,10 +30,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ok = self.try_overloaded_deref(expr.span, oprnd_ty)?; let method = self.register_infer_ok_obligations(ok); if let ty::Ref(_, _, hir::Mutability::Not) = method.sig.inputs()[0].kind() { - self.apply_adjustments(oprnd_expr, vec![Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Not)), - target: method.sig.inputs()[0], - }]); + self.apply_adjustments( + oprnd_expr, + vec![Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::Not)), + target: method.sig.inputs()[0], + }], + ); } else { span_bug!(expr.span, "input to deref is not a ref?"); } diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index cac891c4e4c..c986429c1b2 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -288,11 +288,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { bug!(); }; let place = self.place_for_root_variable(closure_def_id, local_id); - delegate.capture_information.push((place, ty::CaptureInfo { - capture_kind_expr_id: Some(init.hir_id), - path_expr_id: Some(init.hir_id), - capture_kind: UpvarCapture::ByValue, - })); + delegate.capture_information.push(( + place, + ty::CaptureInfo { + capture_kind_expr_id: Some(init.hir_id), + path_expr_id: Some(init.hir_id), + capture_kind: UpvarCapture::ByValue, + }, + )); } } @@ -379,11 +382,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let UpvarArgs::CoroutineClosure(args) = args && !args.references_error() { - let closure_env_region: ty::Region<'_> = - ty::Region::new_bound(self.tcx, ty::INNERMOST, ty::BoundRegion { - var: ty::BoundVar::ZERO, - kind: ty::BoundRegionKind::ClosureEnv, - }); + let closure_env_region: ty::Region<'_> = ty::Region::new_bound( + self.tcx, + ty::INNERMOST, + ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::ClosureEnv }, + ); let num_args = args .as_coroutine_closure() @@ -2009,11 +2012,14 @@ impl<'tcx> euv::Delegate<'tcx> for InferBorrowKind<'tcx> { let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return }; assert_eq!(self.closure_def_id, upvar_id.closure_expr_id); - self.capture_information.push((place_with_id.place.clone(), ty::CaptureInfo { - capture_kind_expr_id: Some(diag_expr_id), - path_expr_id: Some(diag_expr_id), - capture_kind: ty::UpvarCapture::ByValue, - })); + self.capture_information.push(( + place_with_id.place.clone(), + ty::CaptureInfo { + capture_kind_expr_id: Some(diag_expr_id), + path_expr_id: Some(diag_expr_id), + capture_kind: ty::UpvarCapture::ByValue, + }, + )); } #[instrument(skip(self), level = "debug")] @@ -2040,11 +2046,14 @@ impl<'tcx> euv::Delegate<'tcx> for InferBorrowKind<'tcx> { capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::Immutable); } - self.capture_information.push((place, ty::CaptureInfo { - capture_kind_expr_id: Some(diag_expr_id), - path_expr_id: Some(diag_expr_id), - capture_kind, - })); + self.capture_information.push(( + place, + ty::CaptureInfo { + capture_kind_expr_id: Some(diag_expr_id), + path_expr_id: Some(diag_expr_id), + capture_kind, + }, + )); } #[instrument(skip(self), level = "debug")] diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 35e5c250f78..30590bf5d3c 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -107,11 +107,10 @@ const LABELS_FN_IN_TRAIT: &[&[&str]] = const LABELS_HIR_ONLY: &[&[&str]] = &[BASE_HIR]; /// Impl `DepNode`s. -const LABELS_TRAIT: &[&[&str]] = &[BASE_HIR, &[ - label_strs::associated_item_def_ids, - label_strs::predicates_of, - label_strs::generics_of, -]]; +const LABELS_TRAIT: &[&[&str]] = &[ + BASE_HIR, + &[label_strs::associated_item_def_ids, label_strs::predicates_of, label_strs::generics_of], +]; /// Impl `DepNode`s. const LABELS_IMPL: &[&[&str]] = &[BASE_HIR, BASE_IMPL]; diff --git a/compiler/rustc_index/src/bit_set/tests.rs b/compiler/rustc_index/src/bit_set/tests.rs index eaa4aafe721..323a66ddc6f 100644 --- a/compiler/rustc_index/src/bit_set/tests.rs +++ b/compiler/rustc_index/src/bit_set/tests.rs @@ -118,11 +118,10 @@ fn chunked_bitset() { //----------------------------------------------------------------------- let mut b1 = ChunkedBitSet::::new_empty(1); - assert_eq!(b1, ChunkedBitSet { - domain_size: 1, - chunks: Box::new([Zeros(1)]), - marker: PhantomData - }); + assert_eq!( + b1, + ChunkedBitSet { domain_size: 1, chunks: Box::new([Zeros(1)]), marker: PhantomData } + ); b1.assert_valid(); assert!(!b1.contains(0)); @@ -141,11 +140,10 @@ fn chunked_bitset() { //----------------------------------------------------------------------- let mut b100 = ChunkedBitSet::::new_filled(100); - assert_eq!(b100, ChunkedBitSet { - domain_size: 100, - chunks: Box::new([Ones(100)]), - marker: PhantomData - }); + assert_eq!( + b100, + ChunkedBitSet { domain_size: 100, chunks: Box::new([Ones(100)]), marker: PhantomData } + ); b100.assert_valid(); for i in 0..100 { @@ -160,17 +158,20 @@ fn chunked_bitset() { ); assert_eq!(b100.count(), 97); assert!(!b100.contains(20) && b100.contains(30) && !b100.contains(99) && b100.contains(50)); - assert_eq!(b100.chunks(), vec![Mixed( - 100, - 97, - #[rustfmt::skip] + assert_eq!( + b100.chunks(), + vec![Mixed( + 100, + 97, + #[rustfmt::skip] Rc::new([ 0b11111111_11111111_11111110_11111111_11111111_11101111_11111111_11111111, 0b00000000_00000000_00000000_00000111_11111111_11111111_11111111_11111111, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ]) - )],); + )], + ); b100.assert_valid(); let mut num_removed = 0; for i in 0..100 { @@ -185,11 +186,14 @@ fn chunked_bitset() { //----------------------------------------------------------------------- let mut b2548 = ChunkedBitSet::::new_empty(2548); - assert_eq!(b2548, ChunkedBitSet { - domain_size: 2548, - chunks: Box::new([Zeros(2048), Zeros(500)]), - marker: PhantomData, - }); + assert_eq!( + b2548, + ChunkedBitSet { + domain_size: 2548, + chunks: Box::new([Zeros(2048), Zeros(500)]), + marker: PhantomData, + } + ); b2548.assert_valid(); b2548.insert(14); @@ -206,11 +210,14 @@ fn chunked_bitset() { //----------------------------------------------------------------------- let mut b4096 = ChunkedBitSet::::new_empty(4096); - assert_eq!(b4096, ChunkedBitSet { - domain_size: 4096, - chunks: Box::new([Zeros(2048), Zeros(2048)]), - marker: PhantomData, - }); + assert_eq!( + b4096, + ChunkedBitSet { + domain_size: 4096, + chunks: Box::new([Zeros(2048), Zeros(2048)]), + marker: PhantomData, + } + ); b4096.assert_valid(); for i in 0..4096 { @@ -240,11 +247,14 @@ fn chunked_bitset() { //----------------------------------------------------------------------- let mut b10000 = ChunkedBitSet::::new_empty(10000); - assert_eq!(b10000, ChunkedBitSet { - domain_size: 10000, - chunks: Box::new([Zeros(2048), Zeros(2048), Zeros(2048), Zeros(2048), Zeros(1808),]), - marker: PhantomData, - }); + assert_eq!( + b10000, + ChunkedBitSet { + domain_size: 10000, + chunks: Box::new([Zeros(2048), Zeros(2048), Zeros(2048), Zeros(2048), Zeros(1808),]), + marker: PhantomData, + } + ); b10000.assert_valid(); assert!(b10000.insert(3000) && b10000.insert(5000)); diff --git a/compiler/rustc_index/src/vec/tests.rs b/compiler/rustc_index/src/vec/tests.rs index 9cee2f2f5b2..381d79c24fc 100644 --- a/compiler/rustc_index/src/vec/tests.rs +++ b/compiler/rustc_index/src/vec/tests.rs @@ -29,21 +29,19 @@ fn index_size_is_optimized() { #[test] fn range_iterator_iterates_forwards() { let range = MyIdx::from_u32(1)..MyIdx::from_u32(4); - assert_eq!(range.collect::>(), [ - MyIdx::from_u32(1), - MyIdx::from_u32(2), - MyIdx::from_u32(3) - ]); + assert_eq!( + range.collect::>(), + [MyIdx::from_u32(1), MyIdx::from_u32(2), MyIdx::from_u32(3)] + ); } #[test] fn range_iterator_iterates_backwards() { let range = MyIdx::from_u32(1)..MyIdx::from_u32(4); - assert_eq!(range.rev().collect::>(), [ - MyIdx::from_u32(3), - MyIdx::from_u32(2), - MyIdx::from_u32(1) - ]); + assert_eq!( + range.rev().collect::>(), + [MyIdx::from_u32(3), MyIdx::from_u32(2), MyIdx::from_u32(1)] + ); } #[test] diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index 86a47426049..a89cef50c9b 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -100,16 +100,20 @@ impl<'tcx> InferCtxt<'tcx> { ) { debug!(?sup_type, ?sub_region, ?cause); let origin = SubregionOrigin::from_obligation_cause(cause, || { - infer::RelateParamBound(cause.span, sup_type, match cause.code().peel_derives() { - ObligationCauseCode::WhereClause(_, span) - | ObligationCauseCode::WhereClauseInExpr(_, span, ..) - | ObligationCauseCode::OpaqueTypeBound(span, _) - if !span.is_dummy() => - { - Some(*span) - } - _ => None, - }) + infer::RelateParamBound( + cause.span, + sup_type, + match cause.code().peel_derives() { + ObligationCauseCode::WhereClause(_, span) + | ObligationCauseCode::WhereClauseInExpr(_, span, ..) + | ObligationCauseCode::OpaqueTypeBound(span, _) + if !span.is_dummy() => + { + Some(*span) + } + _ => None, + }, + ) }); self.register_region_obligation(RegionObligation { sup_type, sub_region, origin }); diff --git a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs index 061f7e6c22a..0998f3c4790 100644 --- a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs +++ b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs @@ -34,22 +34,22 @@ impl<'tcx> InferCtxt<'tcx> { let delegate = FnMutDelegate { regions: &mut |br: ty::BoundRegion| { - ty::Region::new_placeholder(self.tcx, ty::PlaceholderRegion { - universe: next_universe, - bound: br, - }) + ty::Region::new_placeholder( + self.tcx, + ty::PlaceholderRegion { universe: next_universe, bound: br }, + ) }, types: &mut |bound_ty: ty::BoundTy| { - Ty::new_placeholder(self.tcx, ty::PlaceholderType { - universe: next_universe, - bound: bound_ty, - }) + Ty::new_placeholder( + self.tcx, + ty::PlaceholderType { universe: next_universe, bound: bound_ty }, + ) }, consts: &mut |bound_var: ty::BoundVar| { - ty::Const::new_placeholder(self.tcx, ty::PlaceholderConst { - universe: next_universe, - bound: bound_var, - }) + ty::Const::new_placeholder( + self.tcx, + ty::PlaceholderConst { universe: next_universe, bound: bound_var }, + ) }, }; diff --git a/compiler/rustc_infer/src/traits/engine.rs b/compiler/rustc_infer/src/traits/engine.rs index 51282b900ed..1eae10673b6 100644 --- a/compiler/rustc_infer/src/traits/engine.rs +++ b/compiler/rustc_infer/src/traits/engine.rs @@ -45,12 +45,15 @@ pub trait TraitEngine<'tcx, E: 'tcx>: 'tcx { cause: ObligationCause<'tcx>, ) { let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]); - self.register_predicate_obligation(infcx, Obligation { - cause, - recursion_depth: 0, - param_env, - predicate: trait_ref.upcast(infcx.tcx), - }); + self.register_predicate_obligation( + infcx, + Obligation { + cause, + recursion_depth: 0, + param_env, + predicate: trait_ref.upcast(infcx.tcx), + }, + ); } fn register_predicate_obligation( diff --git a/compiler/rustc_infer/src/traits/project.rs b/compiler/rustc_infer/src/traits/project.rs index cab2ce9f5a0..9082db4f448 100644 --- a/compiler/rustc_infer/src/traits/project.rs +++ b/compiler/rustc_infer/src/traits/project.rs @@ -193,10 +193,10 @@ impl<'tcx> ProjectionCache<'_, 'tcx> { if result.must_apply_considering_regions() { ty.obligations = PredicateObligations::new(); } - map.insert(key, ProjectionCacheEntry::NormalizedTerm { - ty, - complete: Some(result), - }); + map.insert( + key, + ProjectionCacheEntry::NormalizedTerm { ty, complete: Some(result) }, + ); } ref value => { // Type inference could "strand behind" old cache entries. Leave diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 46d6f37a91c..bb55756d80e 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -770,11 +770,14 @@ fn test_unstable_options_tracking_hash() { }) ); tracked!(codegen_backend, Some("abc".to_string())); - tracked!(coverage_options, CoverageOptions { - level: CoverageLevel::Mcdc, - no_mir_spans: true, - discard_all_spans_in_codegen: true - }); + tracked!( + coverage_options, + CoverageOptions { + level: CoverageLevel::Mcdc, + no_mir_spans: true, + discard_all_spans_in_codegen: true + } + ); tracked!(crate_attr, vec!["abc".to_string()]); tracked!(cross_crate_inline_threshold, InliningThreshold::Always); tracked!(debug_info_for_profiling, true); diff --git a/compiler/rustc_lexer/src/tests.rs b/compiler/rustc_lexer/src/tests.rs index db7225fc2a8..8203ae70b07 100644 --- a/compiler/rustc_lexer/src/tests.rs +++ b/compiler/rustc_lexer/src/tests.rs @@ -131,7 +131,9 @@ fn check_lexing(src: &str, expect: Expect) { #[test] fn smoke_test() { - check_lexing("/* my source file */ fn main() { println!(\"zebra\"); }\n", expect![[r#" + check_lexing( + "/* my source file */ fn main() { println!(\"zebra\"); }\n", + expect![[r#" Token { kind: BlockComment { doc_style: None, terminated: true }, len: 20 } Token { kind: Whitespace, len: 1 } Token { kind: Ident, len: 2 } @@ -151,7 +153,8 @@ fn smoke_test() { Token { kind: Whitespace, len: 1 } Token { kind: CloseBrace, len: 1 } Token { kind: Whitespace, len: 1 } - "#]]) + "#]], + ) } #[test] @@ -194,35 +197,47 @@ fn comment_flavors() { #[test] fn nested_block_comments() { - check_lexing("/* /* */ */'a'", expect![[r#" + check_lexing( + "/* /* */ */'a'", + expect![[r#" Token { kind: BlockComment { doc_style: None, terminated: true }, len: 11 } Token { kind: Literal { kind: Char { terminated: true }, suffix_start: 3 }, len: 3 } - "#]]) + "#]], + ) } #[test] fn characters() { - check_lexing("'a' ' ' '\\n'", expect![[r#" + check_lexing( + "'a' ' ' '\\n'", + expect![[r#" Token { kind: Literal { kind: Char { terminated: true }, suffix_start: 3 }, len: 3 } Token { kind: Whitespace, len: 1 } Token { kind: Literal { kind: Char { terminated: true }, suffix_start: 3 }, len: 3 } Token { kind: Whitespace, len: 1 } Token { kind: Literal { kind: Char { terminated: true }, suffix_start: 4 }, len: 4 } - "#]]); + "#]], + ); } #[test] fn lifetime() { - check_lexing("'abc", expect![[r#" + check_lexing( + "'abc", + expect![[r#" Token { kind: Lifetime { starts_with_number: false }, len: 4 } - "#]]); + "#]], + ); } #[test] fn raw_string() { - check_lexing("r###\"\"#a\\b\x00c\"\"###", expect![[r#" + check_lexing( + "r###\"\"#a\\b\x00c\"\"###", + expect![[r#" Token { kind: Literal { kind: RawStr { n_hashes: Some(3) }, suffix_start: 17 }, len: 17 } - "#]]) + "#]], + ) } #[test] diff --git a/compiler/rustc_lexer/src/unescape/tests.rs b/compiler/rustc_lexer/src/unescape/tests.rs index 6fa7a150516..5b99495f475 100644 --- a/compiler/rustc_lexer/src/unescape/tests.rs +++ b/compiler/rustc_lexer/src/unescape/tests.rs @@ -108,12 +108,15 @@ fn test_unescape_str_warn() { check("\\\n", &[]); check("\\\n ", &[]); - check("\\\n \u{a0} x", &[ - (0..5, Err(EscapeError::UnskippedWhitespaceWarning)), - (3..5, Ok('\u{a0}')), - (5..6, Ok(' ')), - (6..7, Ok('x')), - ]); + check( + "\\\n \u{a0} x", + &[ + (0..5, Err(EscapeError::UnskippedWhitespaceWarning)), + (3..5, Ok('\u{a0}')), + (5..6, Ok(' ')), + (6..7, Ok('x')), + ], + ); check("\\\n \n x", &[(0..7, Err(EscapeError::MultipleSkippedLinesWarning)), (7..8, Ok('x'))]); } diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index e2bafbed6e1..5e6b854ff52 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -102,10 +102,11 @@ impl EarlyLintPass for WhileTrue { "{}loop", label.map_or_else(String::new, |label| format!("{}: ", label.ident,)) ); - cx.emit_span_lint(WHILE_TRUE, condition_span, BuiltinWhileTrue { - suggestion: condition_span, - replace, - }); + cx.emit_span_lint( + WHILE_TRUE, + condition_span, + BuiltinWhileTrue { suggestion: condition_span, replace }, + ); } } } @@ -421,10 +422,11 @@ impl MissingDoc { let attrs = cx.tcx.hir().attrs(cx.tcx.local_def_id_to_hir_id(def_id)); let has_doc = attrs.iter().any(has_doc); if !has_doc { - cx.emit_span_lint(MISSING_DOCS, cx.tcx.def_span(def_id), BuiltinMissingDoc { - article, - desc, - }); + cx.emit_span_lint( + MISSING_DOCS, + cx.tcx.def_span(def_id), + BuiltinMissingDoc { article, desc }, + ); } } } @@ -706,10 +708,11 @@ impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { .next() .is_some(); if !has_impl { - cx.emit_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, item.span, BuiltinMissingDebugImpl { - tcx: cx.tcx, - def_id: debug, - }); + cx.emit_span_lint( + MISSING_DEBUG_IMPLEMENTATIONS, + item.span, + BuiltinMissingDebugImpl { tcx: cx.tcx, def_id: debug }, + ); } } } @@ -831,12 +834,11 @@ impl EarlyLintPass for DeprecatedAttr { BuiltinDeprecatedAttrLinkSuggestion::Default { suggestion: attr.span } } }; - cx.emit_span_lint(DEPRECATED, attr.span, BuiltinDeprecatedAttrLink { - name, - reason, - link, - suggestion, - }); + cx.emit_span_lint( + DEPRECATED, + attr.span, + BuiltinDeprecatedAttrLink { name, reason, link, suggestion }, + ); } return; } @@ -874,11 +876,11 @@ fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: & BuiltinUnusedDocCommentSub::BlockHelp } }; - cx.emit_span_lint(UNUSED_DOC_COMMENTS, span, BuiltinUnusedDocComment { - kind: node_kind, - label: node_span, - sub, - }); + cx.emit_span_lint( + UNUSED_DOC_COMMENTS, + span, + BuiltinUnusedDocComment { kind: node_kind, label: node_span, sub }, + ); } } } @@ -1008,9 +1010,11 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { match param.kind { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { - cx.emit_span_lint(NO_MANGLE_GENERIC_ITEMS, span, BuiltinNoMangleGeneric { - suggestion: no_mangle_attr.span, - }); + cx.emit_span_lint( + NO_MANGLE_GENERIC_ITEMS, + span, + BuiltinNoMangleGeneric { suggestion: no_mangle_attr.span }, + ); break; } } @@ -1037,9 +1041,11 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { // Const items do not refer to a particular location in memory, and therefore // don't have anything to attach a symbol to - cx.emit_span_lint(NO_MANGLE_CONST_ITEMS, it.span, BuiltinConstNoMangle { - suggestion, - }); + cx.emit_span_lint( + NO_MANGLE_CONST_ITEMS, + it.span, + BuiltinConstNoMangle { suggestion }, + ); } } hir::ItemKind::Impl(hir::Impl { generics, items, .. }) => { @@ -1305,12 +1311,16 @@ impl UnreachablePub { applicability = Applicability::MaybeIncorrect; } let def_span = cx.tcx.def_span(def_id); - cx.emit_span_lint(UNREACHABLE_PUB, def_span, BuiltinUnreachablePub { - what, - new_vis, - suggestion: (vis_span, applicability), - help: exportable, - }); + cx.emit_span_lint( + UNREACHABLE_PUB, + def_span, + BuiltinUnreachablePub { + what, + new_vis, + suggestion: (vis_span, applicability), + help: exportable, + }, + ); } } } @@ -1454,24 +1464,32 @@ impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { let enable_feat_help = cx.tcx.sess.is_nightly_build(); if let [.., label_sp] = *where_spans { - cx.emit_span_lint(TYPE_ALIAS_BOUNDS, where_spans, BuiltinTypeAliasBounds { - in_where_clause: true, - label: label_sp, - enable_feat_help, - suggestions: vec![(generics.where_clause_span, String::new())], - preds: generics.predicates, - ty: ty.take(), - }); + cx.emit_span_lint( + TYPE_ALIAS_BOUNDS, + where_spans, + BuiltinTypeAliasBounds { + in_where_clause: true, + label: label_sp, + enable_feat_help, + suggestions: vec![(generics.where_clause_span, String::new())], + preds: generics.predicates, + ty: ty.take(), + }, + ); } if let [.., label_sp] = *inline_spans { - cx.emit_span_lint(TYPE_ALIAS_BOUNDS, inline_spans, BuiltinTypeAliasBounds { - in_where_clause: false, - label: label_sp, - enable_feat_help, - suggestions: inline_sugg, - preds: generics.predicates, - ty, - }); + cx.emit_span_lint( + TYPE_ALIAS_BOUNDS, + inline_spans, + BuiltinTypeAliasBounds { + in_where_clause: false, + label: label_sp, + enable_feat_help, + suggestions: inline_sugg, + preds: generics.predicates, + ty, + }, + ); } } } @@ -1559,10 +1577,11 @@ impl<'tcx> LateLintPass<'tcx> for TrivialConstraints { | ty::ClauseKind::HostEffect(..) => continue, }; if predicate.is_global() { - cx.emit_span_lint(TRIVIAL_BOUNDS, span, BuiltinTrivialBounds { - predicate_kind_name, - predicate, - }); + cx.emit_span_lint( + TRIVIAL_BOUNDS, + span, + BuiltinTrivialBounds { predicate_kind_name, predicate }, + ); } } } @@ -1611,12 +1630,16 @@ impl EarlyLintPass for DoubleNegations { && let ExprKind::Unary(UnOp::Neg, ref inner2) = inner.kind && !matches!(inner2.kind, ExprKind::Unary(UnOp::Neg, _)) { - cx.emit_span_lint(DOUBLE_NEGATIONS, expr.span, BuiltinDoubleNegations { - add_parens: BuiltinDoubleNegationsAddParens { - start_span: inner.span.shrink_to_lo(), - end_span: inner.span.shrink_to_hi(), + cx.emit_span_lint( + DOUBLE_NEGATIONS, + expr.span, + BuiltinDoubleNegations { + add_parens: BuiltinDoubleNegationsAddParens { + start_span: inner.span.shrink_to_lo(), + end_span: inner.span.shrink_to_hi(), + }, }, - }); + ); } } } @@ -1931,12 +1954,11 @@ impl KeywordIdents { return; } - cx.emit_span_lint(lint, ident.span, BuiltinKeywordIdents { - kw: ident, - next: edition, - suggestion: ident.span, - prefix, - }); + cx.emit_span_lint( + lint, + ident.span, + BuiltinKeywordIdents { kw: ident, next: edition, suggestion: ident.span, prefix }, + ); } } @@ -2357,11 +2379,11 @@ impl EarlyLintPass for IncompleteInternalFeatures { let help = HAS_MIN_FEATURES.contains(&name).then_some(BuiltinIncompleteFeaturesHelp); - cx.emit_span_lint(INCOMPLETE_FEATURES, span, BuiltinIncompleteFeatures { - name, - note, - help, - }); + cx.emit_span_lint( + INCOMPLETE_FEATURES, + span, + BuiltinIncompleteFeatures { name, note, help }, + ); } else { cx.emit_span_lint(INTERNAL_FEATURES, span, BuiltinInternalFeatures { name }); } @@ -2684,13 +2706,17 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { InitKind::Uninit => fluent::lint_builtin_unpermitted_type_init_uninit, }; let sub = BuiltinUnpermittedTypeInitSub { err }; - cx.emit_span_lint(INVALID_VALUE, expr.span, BuiltinUnpermittedTypeInit { - msg, - ty: conjured_ty, - label: expr.span, - sub, - tcx: cx.tcx, - }); + cx.emit_span_lint( + INVALID_VALUE, + expr.span, + BuiltinUnpermittedTypeInit { + msg, + ty: conjured_ty, + label: expr.span, + sub, + tcx: cx.tcx, + }, + ); } } } @@ -2776,9 +2802,11 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { { // `&raw *NULL` is ok. } else { - cx.emit_span_lint(DEREF_NULLPTR, expr.span, BuiltinDerefNullptr { - label: expr.span, - }); + cx.emit_span_lint( + DEREF_NULLPTR, + expr.span, + BuiltinDerefNullptr { label: expr.span }, + ); } } } @@ -2995,14 +3023,18 @@ impl<'tcx> LateLintPass<'tcx> for AsmLabels { let span = span.unwrap_or(*template_span); match label_kind { AsmLabelKind::Named => { - cx.emit_span_lint(NAMED_ASM_LABELS, span, InvalidAsmLabel::Named { - missing_precise_span, - }); + cx.emit_span_lint( + NAMED_ASM_LABELS, + span, + InvalidAsmLabel::Named { missing_precise_span }, + ); } AsmLabelKind::FormatArg => { - cx.emit_span_lint(NAMED_ASM_LABELS, span, InvalidAsmLabel::FormatArg { - missing_precise_span, - }); + cx.emit_span_lint( + NAMED_ASM_LABELS, + span, + InvalidAsmLabel::FormatArg { missing_precise_span }, + ); } // the binary asm issue only occurs when using intel syntax on x86 targets AsmLabelKind::Binary @@ -3012,10 +3044,11 @@ impl<'tcx> LateLintPass<'tcx> for AsmLabels { Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None ) => { - cx.emit_span_lint(BINARY_ASM_LABELS, span, InvalidAsmLabel::Binary { - missing_precise_span, + cx.emit_span_lint( + BINARY_ASM_LABELS, span, - }) + InvalidAsmLabel::Binary { missing_precise_span, span }, + ) } // No lint on anything other than x86 AsmLabelKind::Binary => (), diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index e0863aa035c..a67b404e6e1 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -233,11 +233,14 @@ impl LintStore { } pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) { - self.lint_groups.insert(alias, LintGroup { - lint_ids: vec![], - is_externally_loaded: false, - depr: Some(LintAlias { name: lint_name, silent: true }), - }); + self.lint_groups.insert( + alias, + LintGroup { + lint_ids: vec![], + is_externally_loaded: false, + depr: Some(LintAlias { name: lint_name, silent: true }), + }, + ); } pub fn register_group( @@ -252,11 +255,14 @@ impl LintStore { .insert(name, LintGroup { lint_ids: to, is_externally_loaded, depr: None }) .is_none(); if let Some(deprecated) = deprecated_name { - self.lint_groups.insert(deprecated, LintGroup { - lint_ids: vec![], - is_externally_loaded, - depr: Some(LintAlias { name, silent: false }), - }); + self.lint_groups.insert( + deprecated, + LintGroup { + lint_ids: vec![], + is_externally_loaded, + depr: Some(LintAlias { name, silent: false }), + }, + ); } if !new { diff --git a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs index 181f44fb4de..f418d6d8753 100644 --- a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs +++ b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs @@ -85,14 +85,19 @@ impl<'tcx> LateLintPass<'tcx> for DerefIntoDynSupertrait { .find_map(|i| (i.ident.name == sym::Target).then_some(i.span)) .map(|label| SupertraitAsDerefTargetLabel { label }); let span = tcx.def_span(item.owner_id.def_id); - cx.emit_span_lint(DEREF_INTO_DYN_SUPERTRAIT, span, SupertraitAsDerefTarget { - self_ty, - supertrait_principal: supertrait_principal - .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)), - target_principal, - label: span, - label2, - }); + cx.emit_span_lint( + DEREF_INTO_DYN_SUPERTRAIT, + span, + SupertraitAsDerefTarget { + self_ty, + supertrait_principal: supertrait_principal.map_bound(|trait_ref| { + ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref) + }), + target_principal, + label: span, + label2, + }, + ); } } } diff --git a/compiler/rustc_lint/src/drop_forget_useless.rs b/compiler/rustc_lint/src/drop_forget_useless.rs index ce23892508b..1ca2e4e74ea 100644 --- a/compiler/rustc_lint/src/drop_forget_useless.rs +++ b/compiler/rustc_lint/src/drop_forget_useless.rs @@ -163,32 +163,44 @@ impl<'tcx> LateLintPass<'tcx> for DropForgetUseless { }; match fn_name { sym::mem_drop if arg_ty.is_ref() && !drop_is_single_call_in_arm => { - cx.emit_span_lint(DROPPING_REFERENCES, expr.span, DropRefDiag { - arg_ty, - label: arg.span, - sugg: let_underscore_ignore_sugg(), - }); + cx.emit_span_lint( + DROPPING_REFERENCES, + expr.span, + DropRefDiag { arg_ty, label: arg.span, sugg: let_underscore_ignore_sugg() }, + ); } sym::mem_forget if arg_ty.is_ref() => { - cx.emit_span_lint(FORGETTING_REFERENCES, expr.span, ForgetRefDiag { - arg_ty, - label: arg.span, - sugg: let_underscore_ignore_sugg(), - }); + cx.emit_span_lint( + FORGETTING_REFERENCES, + expr.span, + ForgetRefDiag { + arg_ty, + label: arg.span, + sugg: let_underscore_ignore_sugg(), + }, + ); } sym::mem_drop if is_copy && !drop_is_single_call_in_arm => { - cx.emit_span_lint(DROPPING_COPY_TYPES, expr.span, DropCopyDiag { - arg_ty, - label: arg.span, - sugg: let_underscore_ignore_sugg(), - }); + cx.emit_span_lint( + DROPPING_COPY_TYPES, + expr.span, + DropCopyDiag { + arg_ty, + label: arg.span, + sugg: let_underscore_ignore_sugg(), + }, + ); } sym::mem_forget if is_copy => { - cx.emit_span_lint(FORGETTING_COPY_TYPES, expr.span, ForgetCopyDiag { - arg_ty, - label: arg.span, - sugg: let_underscore_ignore_sugg(), - }); + cx.emit_span_lint( + FORGETTING_COPY_TYPES, + expr.span, + ForgetCopyDiag { + arg_ty, + label: arg.span, + sugg: let_underscore_ignore_sugg(), + }, + ); } sym::mem_drop if let ty::Adt(adt, _) = arg_ty.kind() diff --git a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs index 6556a8d8f2d..7ead8eafbd5 100644 --- a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs +++ b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs @@ -54,10 +54,11 @@ fn enforce_mem_discriminant( ) { let ty_param = cx.typeck_results().node_args(func_expr.hir_id).type_at(0); if is_non_enum(ty_param) { - cx.emit_span_lint(ENUM_INTRINSICS_NON_ENUMS, expr_span, EnumIntrinsicsMemDiscriminate { - ty_param, - note: args_span, - }); + cx.emit_span_lint( + ENUM_INTRINSICS_NON_ENUMS, + expr_span, + EnumIntrinsicsMemDiscriminate { ty_param, note: args_span }, + ); } } diff --git a/compiler/rustc_lint/src/for_loops_over_fallibles.rs b/compiler/rustc_lint/src/for_loops_over_fallibles.rs index dbc920ea5ae..0a5c52d65ec 100644 --- a/compiler/rustc_lint/src/for_loops_over_fallibles.rs +++ b/compiler/rustc_lint/src/for_loops_over_fallibles.rs @@ -96,14 +96,11 @@ impl<'tcx> LateLintPass<'tcx> for ForLoopsOverFallibles { end_span: pat.span.between(arg.span), }; - cx.emit_span_lint(FOR_LOOPS_OVER_FALLIBLES, arg.span, ForLoopsOverFalliblesDiag { - article, - ref_prefix, - ty, - sub, - question_mark, - suggestion, - }); + cx.emit_span_lint( + FOR_LOOPS_OVER_FALLIBLES, + arg.span, + ForLoopsOverFalliblesDiag { article, ref_prefix, ty, sub, question_mark, suggestion }, + ); } } diff --git a/compiler/rustc_lint/src/hidden_unicode_codepoints.rs b/compiler/rustc_lint/src/hidden_unicode_codepoints.rs index 406aa1005df..491c2826baa 100644 --- a/compiler/rustc_lint/src/hidden_unicode_codepoints.rs +++ b/compiler/rustc_lint/src/hidden_unicode_codepoints.rs @@ -74,13 +74,11 @@ impl HiddenUnicodeCodepoints { HiddenUnicodeCodepointsDiagSub::NoEscape { spans } }; - cx.emit_span_lint(TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, HiddenUnicodeCodepointsDiag { - label, - count, - span_label: span, - labels, - sub, - }); + cx.emit_span_lint( + TEXT_DIRECTION_CODEPOINT_IN_LITERAL, + span, + HiddenUnicodeCodepointsDiag { label, count, span_label: span, labels, sub }, + ); } fn check_literal( diff --git a/compiler/rustc_lint/src/if_let_rescope.rs b/compiler/rustc_lint/src/if_let_rescope.rs index b5a6159bd0a..869dab6799d 100644 --- a/compiler/rustc_lint/src/if_let_rescope.rs +++ b/compiler/rustc_lint/src/if_let_rescope.rs @@ -221,20 +221,25 @@ impl IfLetRescope { } } if let Some((span, hir_id)) = first_if_to_lint { - tcx.emit_node_span_lint(IF_LET_RESCOPE, hir_id, span, IfLetRescopeLint { - significant_droppers, - lifetime_ends, - rewrite: first_if_to_rewrite.then_some(IfLetRescopeRewrite { - match_heads, - consequent_heads, - closing_brackets: ClosingBrackets { - span: expr_end, - count: closing_brackets, - empty_alt, - }, - alt_heads, - }), - }); + tcx.emit_node_span_lint( + IF_LET_RESCOPE, + hir_id, + span, + IfLetRescopeLint { + significant_droppers, + lifetime_ends, + rewrite: first_if_to_rewrite.then_some(IfLetRescopeRewrite { + match_heads, + consequent_heads, + closing_brackets: ClosingBrackets { + span: expr_end, + count: closing_brackets, + empty_alt, + }, + alt_heads, + }), + }, + ); } } } diff --git a/compiler/rustc_lint/src/impl_trait_overcaptures.rs b/compiler/rustc_lint/src/impl_trait_overcaptures.rs index d251b4b7459..d2956d94685 100644 --- a/compiler/rustc_lint/src/impl_trait_overcaptures.rs +++ b/compiler/rustc_lint/src/impl_trait_overcaptures.rs @@ -314,12 +314,10 @@ where // We only computed variance of lifetimes... debug_assert_matches!(self.tcx.def_kind(def_id), DefKind::LifetimeParam); let uncaptured = match *kind { - ParamKind::Early(name, index) => { - ty::Region::new_early_param(self.tcx, ty::EarlyParamRegion { - name, - index, - }) - } + ParamKind::Early(name, index) => ty::Region::new_early_param( + self.tcx, + ty::EarlyParamRegion { name, index }, + ), ParamKind::Free(def_id, name) => ty::Region::new_late_param( self.tcx, self.parent_def_id.to_def_id(), diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 546df4497ad..ddc9ae1594f 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -48,10 +48,11 @@ impl LateLintPass<'_> for DefaultHashTypes { Some(sym::HashSet) => "FxHashSet", _ => return, }; - cx.emit_span_lint(DEFAULT_HASH_TYPES, path.span, DefaultHashTypesDiag { - preferred, - used: cx.tcx.item_name(def_id), - }); + cx.emit_span_lint( + DEFAULT_HASH_TYPES, + path.span, + DefaultHashTypesDiag { preferred, used: cx.tcx.item_name(def_id) }, + ); } } @@ -107,14 +108,18 @@ impl LateLintPass<'_> for QueryStability { { let def_id = instance.def_id(); if cx.tcx.has_attr(def_id, sym::rustc_lint_query_instability) { - cx.emit_span_lint(POTENTIAL_QUERY_INSTABILITY, span, QueryInstability { - query: cx.tcx.item_name(def_id), - }); + cx.emit_span_lint( + POTENTIAL_QUERY_INSTABILITY, + span, + QueryInstability { query: cx.tcx.item_name(def_id) }, + ); } if cx.tcx.has_attr(def_id, sym::rustc_lint_untracked_query_information) { - cx.emit_span_lint(UNTRACKED_QUERY_INFORMATION, span, QueryUntracked { - method: cx.tcx.item_name(def_id), - }); + cx.emit_span_lint( + UNTRACKED_QUERY_INFORMATION, + span, + QueryUntracked { method: cx.tcx.item_name(def_id) }, + ); } } } @@ -186,9 +191,11 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { match span { Some(span) => { - cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind { - suggestion: span, - }); + cx.emit_span_lint( + USAGE_OF_TY_TYKIND, + path.span, + TykindKind { suggestion: span }, + ); } None => cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag), } @@ -196,10 +203,11 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { && path.segments.len() > 1 && let Some(ty) = is_ty_or_ty_ctxt(cx, path) { - cx.emit_span_lint(USAGE_OF_QUALIFIED_TY, path.span, TyQualified { - ty, - suggestion: path.span, - }); + cx.emit_span_lint( + USAGE_OF_QUALIFIED_TY, + path.span, + TyQualified { ty, suggestion: path.span }, + ); } } _ => {} @@ -553,9 +561,11 @@ impl LateLintPass<'_> for BadOptAccess { && let Some(lit) = item.lit() && let ast::LitKind::Str(val, _) = lit.kind { - cx.emit_span_lint(BAD_OPT_ACCESS, expr.span, BadOptAccessDiag { - msg: val.as_str(), - }); + cx.emit_span_lint( + BAD_OPT_ACCESS, + expr.span, + BadOptAccessDiag { msg: val.as_str() }, + ); } } } diff --git a/compiler/rustc_lint/src/let_underscore.rs b/compiler/rustc_lint/src/let_underscore.rs index 9e4e8333164..3e2c1af97f4 100644 --- a/compiler/rustc_lint/src/let_underscore.rs +++ b/compiler/rustc_lint/src/let_underscore.rs @@ -156,10 +156,11 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { }; if is_sync_lock { let span = MultiSpan::from_span(pat.span); - cx.emit_span_lint(LET_UNDERSCORE_LOCK, span, NonBindingLet::SyncLock { - sub, - pat: pat.span, - }); + cx.emit_span_lint( + LET_UNDERSCORE_LOCK, + span, + NonBindingLet::SyncLock { sub, pat: pat.span }, + ); // Only emit let_underscore_drop for top-level `_` patterns. } else if can_use_init.is_some() { cx.emit_span_lint(LET_UNDERSCORE_DROP, local.span, NonBindingLet::DropType { sub }); diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 3e97f4c86ba..d89e615e14a 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -627,18 +627,23 @@ fn register_internals(store: &mut LintStore) { // `DIAGNOSTIC_OUTSIDE_OF_IMPL` here because `-Wrustc::internal` is provided to every crate and // these lints will trigger all of the time - change this once migration to diagnostic structs // and translation is completed - store.register_group(false, "rustc::internal", None, vec![ - LintId::of(DEFAULT_HASH_TYPES), - LintId::of(POTENTIAL_QUERY_INSTABILITY), - LintId::of(UNTRACKED_QUERY_INFORMATION), - LintId::of(USAGE_OF_TY_TYKIND), - LintId::of(PASS_BY_VALUE), - LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO), - LintId::of(USAGE_OF_QUALIFIED_TY), - LintId::of(NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT), - LintId::of(BAD_OPT_ACCESS), - LintId::of(SPAN_USE_EQ_CTXT), - ]); + store.register_group( + false, + "rustc::internal", + None, + vec![ + LintId::of(DEFAULT_HASH_TYPES), + LintId::of(POTENTIAL_QUERY_INSTABILITY), + LintId::of(UNTRACKED_QUERY_INFORMATION), + LintId::of(USAGE_OF_TY_TYKIND), + LintId::of(PASS_BY_VALUE), + LintId::of(LINT_PASS_IMPL_WITHOUT_MACRO), + LintId::of(USAGE_OF_QUALIFIED_TY), + LintId::of(NON_GLOB_IMPORT_OF_TYPE_IR_INHERENT), + LintId::of(BAD_OPT_ACCESS), + LintId::of(SPAN_USE_EQ_CTXT), + ], + ); } #[cfg(test)] diff --git a/compiler/rustc_lint/src/map_unit_fn.rs b/compiler/rustc_lint/src/map_unit_fn.rs index 776d51a6727..3b27e456136 100644 --- a/compiler/rustc_lint/src/map_unit_fn.rs +++ b/compiler/rustc_lint/src/map_unit_fn.rs @@ -60,25 +60,39 @@ impl<'tcx> LateLintPass<'tcx> for MapUnitFn { let fn_ty = cx.tcx.fn_sig(id).skip_binder(); let ret_ty = fn_ty.output().skip_binder(); if is_unit_type(ret_ty) { - cx.emit_span_lint(MAP_UNIT_FN, span, MappingToUnit { - function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span), - argument_label: args[0].span, - map_label: arg_ty.default_span(cx.tcx), - suggestion: path.ident.span, - replace: "for_each".to_string(), - }) + cx.emit_span_lint( + MAP_UNIT_FN, + span, + MappingToUnit { + function_label: cx + .tcx + .span_of_impl(*id) + .unwrap_or(default_span), + argument_label: args[0].span, + map_label: arg_ty.default_span(cx.tcx), + suggestion: path.ident.span, + replace: "for_each".to_string(), + }, + ) } } else if let ty::Closure(id, subs) = arg_ty.kind() { let cl_ty = subs.as_closure().sig(); let ret_ty = cl_ty.output().skip_binder(); if is_unit_type(ret_ty) { - cx.emit_span_lint(MAP_UNIT_FN, span, MappingToUnit { - function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span), - argument_label: args[0].span, - map_label: arg_ty.default_span(cx.tcx), - suggestion: path.ident.span, - replace: "for_each".to_string(), - }) + cx.emit_span_lint( + MAP_UNIT_FN, + span, + MappingToUnit { + function_label: cx + .tcx + .span_of_impl(*id) + .unwrap_or(default_span), + argument_label: args[0].span, + map_label: arg_ty.default_span(cx.tcx), + suggestion: path.ident.span, + replace: "for_each".to_string(), + }, + ) } } } diff --git a/compiler/rustc_lint/src/non_ascii_idents.rs b/compiler/rustc_lint/src/non_ascii_idents.rs index 593c8616c1d..2f9cf98848e 100644 --- a/compiler/rustc_lint/src/non_ascii_idents.rs +++ b/compiler/rustc_lint/src/non_ascii_idents.rs @@ -209,22 +209,30 @@ impl EarlyLintPass for NonAsciiIdents { if codepoints.is_empty() { continue; } - cx.emit_span_lint(UNCOMMON_CODEPOINTS, sp, IdentifierUncommonCodepoints { - codepoints_len: codepoints.len(), - codepoints: codepoints.into_iter().map(|(c, _)| c).collect(), - identifier_type: id_ty_descr, - }); + cx.emit_span_lint( + UNCOMMON_CODEPOINTS, + sp, + IdentifierUncommonCodepoints { + codepoints_len: codepoints.len(), + codepoints: codepoints.into_iter().map(|(c, _)| c).collect(), + identifier_type: id_ty_descr, + }, + ); } let remaining = chars .extract_if(.., |(c, _)| !GeneralSecurityProfile::identifier_allowed(*c)) .collect::>(); if !remaining.is_empty() { - cx.emit_span_lint(UNCOMMON_CODEPOINTS, sp, IdentifierUncommonCodepoints { - codepoints_len: remaining.len(), - codepoints: remaining.into_iter().map(|(c, _)| c).collect(), - identifier_type: "Restricted", - }); + cx.emit_span_lint( + UNCOMMON_CODEPOINTS, + sp, + IdentifierUncommonCodepoints { + codepoints_len: remaining.len(), + codepoints: remaining.into_iter().map(|(c, _)| c).collect(), + identifier_type: "Restricted", + }, + ); } } } @@ -253,12 +261,16 @@ impl EarlyLintPass for NonAsciiIdents { .entry(skeleton_sym) .and_modify(|(existing_symbol, existing_span, existing_is_ascii)| { if !*existing_is_ascii || !is_ascii { - cx.emit_span_lint(CONFUSABLE_IDENTS, sp, ConfusableIdentifierPair { - existing_sym: *existing_symbol, - sym: symbol, - label: *existing_span, - main_label: sp, - }); + cx.emit_span_lint( + CONFUSABLE_IDENTS, + sp, + ConfusableIdentifierPair { + existing_sym: *existing_symbol, + sym: symbol, + label: *existing_span, + main_label: sp, + }, + ); } if *existing_is_ascii && !is_ascii { *existing_symbol = symbol; @@ -370,10 +382,11 @@ impl EarlyLintPass for NonAsciiIdents { let char_info = format!("'{}' (U+{:04X})", ch, ch as u32); includes += &char_info; } - cx.emit_span_lint(MIXED_SCRIPT_CONFUSABLES, sp, MixedScriptConfusables { - set: script_set.to_string(), - includes, - }); + cx.emit_span_lint( + MIXED_SCRIPT_CONFUSABLES, + sp, + MixedScriptConfusables { set: script_set.to_string(), includes }, + ); } } } diff --git a/compiler/rustc_lint/src/non_fmt_panic.rs b/compiler/rustc_lint/src/non_fmt_panic.rs index 648d0675627..ac9f8d92dac 100644 --- a/compiler/rustc_lint/src/non_fmt_panic.rs +++ b/compiler/rustc_lint/src/non_fmt_panic.rs @@ -256,10 +256,14 @@ fn check_panic_str<'tcx>( .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end))) .collect(), }; - cx.emit_span_lint(NON_FMT_PANICS, arg_spans, NonFmtPanicUnused { - count: n_arguments, - suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span), - }); + cx.emit_span_lint( + NON_FMT_PANICS, + arg_spans, + NonFmtPanicUnused { + count: n_arguments, + suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span), + }, + ); } else { let brace_spans: Option> = snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| { diff --git a/compiler/rustc_lint/src/non_local_def.rs b/compiler/rustc_lint/src/non_local_def.rs index 4e9d793be5b..0890890d12c 100644 --- a/compiler/rustc_lint/src/non_local_def.rs +++ b/compiler/rustc_lint/src/non_local_def.rs @@ -222,17 +222,21 @@ impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions { None }; - cx.emit_span_lint(NON_LOCAL_DEFINITIONS, ms, NonLocalDefinitionsDiag::Impl { - depth: self.body_depth, - body_kind_descr: cx.tcx.def_kind_descr(parent_def_kind, parent), - body_name: parent_opt_item_name - .map(|s| s.to_ident_string()) - .unwrap_or_else(|| "".to_string()), - cargo_update: cargo_update(), - const_anon, - doctest, - macro_to_change, - }) + cx.emit_span_lint( + NON_LOCAL_DEFINITIONS, + ms, + NonLocalDefinitionsDiag::Impl { + depth: self.body_depth, + body_kind_descr: cx.tcx.def_kind_descr(parent_def_kind, parent), + body_name: parent_opt_item_name + .map(|s| s.to_ident_string()) + .unwrap_or_else(|| "".to_string()), + cargo_update: cargo_update(), + const_anon, + doctest, + macro_to_change, + }, + ) } ItemKind::Macro(_macro, MacroKind::Bang) if cx.tcx.has_attr(item.owner_id.def_id, sym::macro_export) => diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index 0c180ab9570..5636f80d600 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -150,11 +150,11 @@ impl NonCamelCaseTypes { } else { NonCamelCaseTypeSub::Label { span: ident.span } }; - cx.emit_span_lint(NON_CAMEL_CASE_TYPES, ident.span, NonCamelCaseType { - sort, - name, - sub, - }); + cx.emit_span_lint( + NON_CAMEL_CASE_TYPES, + ident.span, + NonCamelCaseType { sort, name, sub }, + ); } } } @@ -488,11 +488,11 @@ impl NonUpperCaseGlobals { } else { NonUpperCaseGlobalSub::Label { span: ident.span } }; - cx.emit_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, NonUpperCaseGlobal { - sort, - name, - sub, - }); + cx.emit_span_lint( + NON_UPPER_CASE_GLOBALS, + ident.span, + NonUpperCaseGlobal { sort, name, sub }, + ); } } } diff --git a/compiler/rustc_lint/src/noop_method_call.rs b/compiler/rustc_lint/src/noop_method_call.rs index 790ef910b04..b7835e6c36a 100644 --- a/compiler/rustc_lint/src/noop_method_call.rs +++ b/compiler/rustc_lint/src/noop_method_call.rs @@ -128,13 +128,17 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { ty::Adt(def, _) => Some(cx.tcx.def_span(def.did()).shrink_to_lo()), _ => None, }; - cx.emit_span_lint(NOOP_METHOD_CALL, span, NoopMethodCallDiag { - method: call.ident, - orig_ty, - trait_, - label: span, - suggest_derive, - }); + cx.emit_span_lint( + NOOP_METHOD_CALL, + span, + NoopMethodCallDiag { + method: call.ident, + orig_ty, + trait_, + label: span, + suggest_derive, + }, + ); } else { match name { // If `type_of(x) == T` and `x.borrow()` is used to get `&T`, diff --git a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs index d347a8c1bc7..7eaf83f5acf 100644 --- a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs +++ b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs @@ -113,10 +113,13 @@ impl<'tcx> LateLintPass<'tcx> for OpaqueHiddenInferredBound { // return type is well-formed in traits even when `Self` isn't sized. if let ty::Param(param_ty) = *proj_term.kind() && param_ty.name == kw::SelfUpper - && matches!(opaque.origin, hir::OpaqueTyOrigin::AsyncFn { - in_trait_or_impl: Some(hir::RpitContext::Trait), - .. - }) + && matches!( + opaque.origin, + hir::OpaqueTyOrigin::AsyncFn { + in_trait_or_impl: Some(hir::RpitContext::Trait), + .. + } + ) { return; } diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index a1d66047058..d85618f664d 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -30,10 +30,11 @@ impl<'tcx> LateLintPass<'tcx> for PassByValue { } } if let Some(t) = path_for_pass_by_value(cx, inner_ty) { - cx.emit_span_lint(PASS_BY_VALUE, ty.span, PassByValueDiag { - ty: t, - suggestion: ty.span, - }); + cx.emit_span_lint( + PASS_BY_VALUE, + ty.span, + PassByValueDiag { ty: t, suggestion: ty.span }, + ); } } _ => {} diff --git a/compiler/rustc_lint/src/redundant_semicolon.rs b/compiler/rustc_lint/src/redundant_semicolon.rs index 036bfd06856..b43e4938b73 100644 --- a/compiler/rustc_lint/src/redundant_semicolon.rs +++ b/compiler/rustc_lint/src/redundant_semicolon.rs @@ -50,9 +50,10 @@ fn maybe_lint_redundant_semis(cx: &EarlyContext<'_>, seq: &mut Option<(Span, boo return; } - cx.emit_span_lint(REDUNDANT_SEMICOLONS, span, RedundantSemicolonsDiag { - multiple, - suggestion: span, - }); + cx.emit_span_lint( + REDUNDANT_SEMICOLONS, + span, + RedundantSemicolonsDiag { multiple, suggestion: span }, + ); } } diff --git a/compiler/rustc_lint/src/shadowed_into_iter.rs b/compiler/rustc_lint/src/shadowed_into_iter.rs index f5ab44d7469..7cc35e20fcb 100644 --- a/compiler/rustc_lint/src/shadowed_into_iter.rs +++ b/compiler/rustc_lint/src/shadowed_into_iter.rs @@ -147,11 +147,10 @@ impl<'tcx> LateLintPass<'tcx> for ShadowedIntoIter { None }; - cx.emit_span_lint(lint, call.ident.span, ShadowedIntoIterDiag { - target, - edition, - suggestion: call.ident.span, - sub, - }); + cx.emit_span_lint( + lint, + call.ident.span, + ShadowedIntoIterDiag { target, edition, suggestion: call.ident.span, sub }, + ); } } diff --git a/compiler/rustc_lint/src/static_mut_refs.rs b/compiler/rustc_lint/src/static_mut_refs.rs index fed5c29284b..50021157dda 100644 --- a/compiler/rustc_lint/src/static_mut_refs.rs +++ b/compiler/rustc_lint/src/static_mut_refs.rs @@ -157,11 +157,9 @@ fn emit_static_mut_refs( } }; - cx.emit_span_lint(STATIC_MUT_REFS, span, RefOfMutStatic { + cx.emit_span_lint( + STATIC_MUT_REFS, span, - sugg, - shared_label, - shared_note, - mut_note, - }); + RefOfMutStatic { span, sugg, shared_label, shared_note, mut_note }, + ); } diff --git a/compiler/rustc_lint/src/traits.rs b/compiler/rustc_lint/src/traits.rs index e0937e43c9a..99222742b65 100644 --- a/compiler/rustc_lint/src/traits.rs +++ b/compiler/rustc_lint/src/traits.rs @@ -101,11 +101,11 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { continue; } let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { return }; - cx.emit_span_lint(DROP_BOUNDS, span, DropTraitConstraintsDiag { - predicate, - tcx: cx.tcx, - def_id, - }); + cx.emit_span_lint( + DROP_BOUNDS, + span, + DropTraitConstraintsDiag { predicate, tcx: cx.tcx, def_id }, + ); } } } diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 80007f34db3..a9fffcf348b 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -599,13 +599,16 @@ impl<'tcx> LateLintPass<'tcx> for TypeLimits { } fn rev_binop(binop: hir::BinOp) -> hir::BinOp { - source_map::respan(binop.span, match binop.node { - hir::BinOpKind::Lt => hir::BinOpKind::Gt, - hir::BinOpKind::Le => hir::BinOpKind::Ge, - hir::BinOpKind::Gt => hir::BinOpKind::Lt, - hir::BinOpKind::Ge => hir::BinOpKind::Le, - _ => return binop, - }) + source_map::respan( + binop.span, + match binop.node { + hir::BinOpKind::Lt => hir::BinOpKind::Gt, + hir::BinOpKind::Le => hir::BinOpKind::Ge, + hir::BinOpKind::Gt => hir::BinOpKind::Lt, + hir::BinOpKind::Ge => hir::BinOpKind::Le, + _ => return binop, + }, + ) } fn check_limits( @@ -1386,14 +1389,11 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } else { None }; - self.cx.emit_span_lint(lint, sp, ImproperCTypes { - ty, - desc, - label: sp, - help, - note, - span_note, - }); + self.cx.emit_span_lint( + lint, + sp, + ImproperCTypes { ty, desc, label: sp, help, note, span_note }, + ); } fn check_for_opaque_ty(&mut self, sp: Span, ty: Ty<'tcx>) -> bool { @@ -1930,11 +1930,11 @@ impl InvalidAtomicOrdering { } fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { - let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[ - sym::fetch_update, - sym::compare_exchange, - sym::compare_exchange_weak, - ]) else { + let Some((method, args)) = Self::inherent_atomic_method_call( + cx, + expr, + &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak], + ) else { return; }; diff --git a/compiler/rustc_lint/src/types/literal.rs b/compiler/rustc_lint/src/types/literal.rs index 71e6e229907..da98b6461f1 100644 --- a/compiler/rustc_lint/src/types/literal.rs +++ b/compiler/rustc_lint/src/types/literal.rs @@ -77,10 +77,11 @@ fn lint_overflowing_range_endpoint<'tcx>( } }; - cx.emit_span_lint(OVERFLOWING_LITERALS, struct_expr.span, RangeEndpointOutOfRange { - ty, - sub: sub_sugg, - }); + cx.emit_span_lint( + OVERFLOWING_LITERALS, + struct_expr.span, + RangeEndpointOutOfRange { ty, sub: sub_sugg }, + ); // We've just emitted a lint, special cased for `(...)..MAX+1` ranges, // return `true` so the callers don't also emit a lint @@ -190,15 +191,19 @@ fn report_bin_hex_error( }) .flatten(); - cx.emit_span_lint(OVERFLOWING_LITERALS, span, OverflowingBinHex { - ty: t, - lit: repr_str.clone(), - dec: val, - actually, - sign, - sub, - sign_bit_sub, - }) + cx.emit_span_lint( + OVERFLOWING_LITERALS, + span, + OverflowingBinHex { + ty: t, + lit: repr_str.clone(), + dec: val, + actually, + sign, + sub, + sign_bit_sub, + }, + ) } // Find the "next" fitting integer and return a suggestion string @@ -283,13 +288,11 @@ fn lint_int_literal<'tcx>( let help = get_type_suggestion(cx.typeck_results().node_type(hir_id), v, negative) .map(|suggestion_ty| OverflowingIntHelp { suggestion_ty }); - cx.emit_span_lint(OVERFLOWING_LITERALS, span, OverflowingInt { - ty: t.name_str(), - lit, - min, - max, - help, - }); + cx.emit_span_lint( + OVERFLOWING_LITERALS, + span, + OverflowingInt { ty: t.name_str(), lit, min, max, help }, + ); } } @@ -314,10 +317,11 @@ fn lint_uint_literal<'tcx>( match par_e.kind { hir::ExprKind::Cast(..) => { if let ty::Char = cx.typeck_results().expr_ty(par_e).kind() { - cx.emit_span_lint(OVERFLOWING_LITERALS, par_e.span, OnlyCastu8ToChar { - span: par_e.span, - literal: lit_val, - }); + cx.emit_span_lint( + OVERFLOWING_LITERALS, + par_e.span, + OnlyCastu8ToChar { span: par_e.span, literal: lit_val }, + ); return; } } @@ -341,16 +345,20 @@ fn lint_uint_literal<'tcx>( ); return; } - cx.emit_span_lint(OVERFLOWING_LITERALS, span, OverflowingUInt { - ty: t.name_str(), - lit: cx - .sess() - .source_map() - .span_to_snippet(lit.span) - .unwrap_or_else(|_| lit_val.to_string()), - min, - max, - }); + cx.emit_span_lint( + OVERFLOWING_LITERALS, + span, + OverflowingUInt { + ty: t.name_str(), + lit: cx + .sess() + .source_map() + .span_to_snippet(lit.span) + .unwrap_or_else(|_| lit_val.to_string()), + min, + max, + }, + ); } } @@ -388,14 +396,18 @@ pub(crate) fn lint_literal<'tcx>( _ => bug!(), }; if is_infinite == Ok(true) { - cx.emit_span_lint(OVERFLOWING_LITERALS, span, OverflowingLiteral { - ty: t.name_str(), - lit: cx - .sess() - .source_map() - .span_to_snippet(lit.span) - .unwrap_or_else(|_| sym.to_string()), - }); + cx.emit_span_lint( + OVERFLOWING_LITERALS, + span, + OverflowingLiteral { + ty: t.name_str(), + lit: cx + .sess() + .source_map() + .span_to_snippet(lit.span) + .unwrap_or_else(|_| sym.to_string()), + }, + ); } } _ => {} diff --git a/compiler/rustc_lint/src/unit_bindings.rs b/compiler/rustc_lint/src/unit_bindings.rs index 3c2c5f8fae0..ed015908ae5 100644 --- a/compiler/rustc_lint/src/unit_bindings.rs +++ b/compiler/rustc_lint/src/unit_bindings.rs @@ -63,9 +63,11 @@ impl<'tcx> LateLintPass<'tcx> for UnitBindings { && !matches!(init.kind, hir::ExprKind::Tup([])) && !matches!(local.pat.kind, hir::PatKind::Tuple([], ..)) { - cx.emit_span_lint(UNIT_BINDINGS, local.span, UnitBindingsDiag { - label: local.pat.span, - }); + cx.emit_span_lint( + UNIT_BINDINGS, + local.span, + UnitBindingsDiag { label: local.pat.span }, + ); } } } diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index 5696fcaed13..5a00ac005db 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -184,18 +184,22 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { let mut op_warned = false; if let Some(must_use_op) = must_use_op { - cx.emit_span_lint(UNUSED_MUST_USE, expr.span, UnusedOp { - op: must_use_op, - label: expr.span, - suggestion: if expr_is_from_block { - UnusedOpSuggestion::BlockTailExpr { - before_span: expr.span.shrink_to_lo(), - after_span: expr.span.shrink_to_hi(), - } - } else { - UnusedOpSuggestion::NormalExpr { span: expr.span.shrink_to_lo() } + cx.emit_span_lint( + UNUSED_MUST_USE, + expr.span, + UnusedOp { + op: must_use_op, + label: expr.span, + suggestion: if expr_is_from_block { + UnusedOpSuggestion::BlockTailExpr { + before_span: expr.span.shrink_to_lo(), + after_span: expr.span.shrink_to_hi(), + } + } else { + UnusedOpSuggestion::NormalExpr { span: expr.span.shrink_to_lo() } + }, }, - }); + ); op_warned = true; } @@ -489,35 +493,39 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { ); } MustUsePath::Closure(span) => { - cx.emit_span_lint(UNUSED_MUST_USE, *span, UnusedClosure { - count: plural_len, - pre: descr_pre, - post: descr_post, - }); + cx.emit_span_lint( + UNUSED_MUST_USE, + *span, + UnusedClosure { count: plural_len, pre: descr_pre, post: descr_post }, + ); } MustUsePath::Coroutine(span) => { - cx.emit_span_lint(UNUSED_MUST_USE, *span, UnusedCoroutine { - count: plural_len, - pre: descr_pre, - post: descr_post, - }); + cx.emit_span_lint( + UNUSED_MUST_USE, + *span, + UnusedCoroutine { count: plural_len, pre: descr_pre, post: descr_post }, + ); } MustUsePath::Def(span, def_id, reason) => { - cx.emit_span_lint(UNUSED_MUST_USE, *span, UnusedDef { - pre: descr_pre, - post: descr_post, - cx, - def_id: *def_id, - note: *reason, - suggestion: (!is_inner).then_some(if expr_is_from_block { - UnusedDefSuggestion::BlockTailExpr { - before_span: span.shrink_to_lo(), - after_span: span.shrink_to_hi(), - } - } else { - UnusedDefSuggestion::NormalExpr { span: span.shrink_to_lo() } - }), - }); + cx.emit_span_lint( + UNUSED_MUST_USE, + *span, + UnusedDef { + pre: descr_pre, + post: descr_post, + cx, + def_id: *def_id, + note: *reason, + suggestion: (!is_inner).then_some(if expr_is_from_block { + UnusedDefSuggestion::BlockTailExpr { + before_span: span.shrink_to_lo(), + after_span: span.shrink_to_hi(), + } + } else { + UnusedDefSuggestion::NormalExpr { span: span.shrink_to_lo() } + }), + }, + ); } } } @@ -867,11 +875,11 @@ trait UnusedDelimLint { end_replace: hi_replace, } }); - cx.emit_span_lint(self.lint(), primary_span, UnusedDelim { - delim: Self::DELIM_STR, - item: msg, - suggestion, - }); + cx.emit_span_lint( + self.lint(), + primary_span, + UnusedDelim { delim: Self::DELIM_STR, item: msg, suggestion }, + ); } fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { @@ -1558,9 +1566,11 @@ impl UnusedImportBraces { ast::UseTreeKind::Nested { .. } => return, }; - cx.emit_span_lint(UNUSED_IMPORT_BRACES, item.span, UnusedImportBracesDiag { - node: node_name, - }); + cx.emit_span_lint( + UNUSED_IMPORT_BRACES, + item.span, + UnusedImportBracesDiag { node: node_name }, + ); } } } diff --git a/compiler/rustc_macros/src/serialize.rs b/compiler/rustc_macros/src/serialize.rs index ce692abfb98..2c33a0ac0aa 100644 --- a/compiler/rustc_macros/src/serialize.rs +++ b/compiler/rustc_macros/src/serialize.rs @@ -105,11 +105,14 @@ fn decodable_body( }; s.underscore_const(true); - s.bound_impl(quote!(::rustc_serialize::Decodable<#decoder_ty>), quote! { - fn decode(__decoder: &mut #decoder_ty) -> Self { - #decode_body - } - }) + s.bound_impl( + quote!(::rustc_serialize::Decodable<#decoder_ty>), + quote! { + fn decode(__decoder: &mut #decoder_ty) -> Self { + #decode_body + } + }, + ) } fn decode_field(field: &syn::Field) -> proc_macro2::TokenStream { @@ -285,13 +288,16 @@ fn encodable_body( quote! {} }; - s.bound_impl(quote!(::rustc_serialize::Encodable<#encoder_ty>), quote! { - fn encode( - &self, - __encoder: &mut #encoder_ty, - ) { - #lints - #encode_body - } - }) + s.bound_impl( + quote!(::rustc_serialize::Encodable<#encoder_ty>), + quote! { + fn encode( + &self, + __encoder: &mut #encoder_ty, + ) { + #lints + #encode_body + } + }, + ) } diff --git a/compiler/rustc_macros/src/symbols/tests.rs b/compiler/rustc_macros/src/symbols/tests.rs index b32ce60e204..9c53453df5b 100644 --- a/compiler/rustc_macros/src/symbols/tests.rs +++ b/compiler/rustc_macros/src/symbols/tests.rs @@ -94,8 +94,8 @@ fn check_symbol_order() { aardvark, } }; - test_symbols_macro(input, &[ - "Symbol `aardvark` must precede `zebra`", - "location of previous symbol `zebra`", - ]); + test_symbols_macro( + input, + &["Symbol `aardvark` must precede `zebra`", "location of previous symbol `zebra`"], + ); } diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 6bad8312790..c2dda21bb72 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -1213,12 +1213,15 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { let cnum = self.resolve_crate(name, item.span, dep_kind)?; let path_len = definitions.def_path(def_id).data.len(); - self.cstore.update_extern_crate(cnum, ExternCrate { - src: ExternCrateSource::Extern(def_id.to_def_id()), - span: item.span, - path_len, - dependency_of: LOCAL_CRATE, - }); + self.cstore.update_extern_crate( + cnum, + ExternCrate { + src: ExternCrateSource::Extern(def_id.to_def_id()), + span: item.span, + path_len, + dependency_of: LOCAL_CRATE, + }, + ); Some(cnum) } _ => bug!(), @@ -1228,13 +1231,16 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> Option { let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit)?; - self.cstore.update_extern_crate(cnum, ExternCrate { - src: ExternCrateSource::Path, - span, - // to have the least priority in `update_extern_crate` - path_len: usize::MAX, - dependency_of: LOCAL_CRATE, - }); + self.cstore.update_extern_crate( + cnum, + ExternCrate { + src: ExternCrateSource::Path, + span, + // to have the least priority in `update_extern_crate` + path_len: usize::MAX, + dependency_of: LOCAL_CRATE, + }, + ); Some(cnum) } diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index 2e4d258ffff..95bc9b71fe0 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -317,10 +317,13 @@ impl Allocation { Ok(Allocation { bytes, provenance: ProvenanceMap::new(), - init_mask: InitMask::new(size, match init { - AllocInit::Uninit => false, - AllocInit::Zero => true, - }), + init_mask: InitMask::new( + size, + match init { + AllocInit::Uninit => false, + AllocInit::Zero => true, + }, + ), align, mutability: Mutability::Mut, extra: (), diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 68d5e5f4dd2..63e20fb0d64 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -1410,10 +1410,10 @@ impl<'tcx> BasicBlockData<'tcx> { // existing elements from before the gap to the end of the gap. // For now, this is safe code, emulating a gap but initializing it. let mut gap = self.statements.len()..self.statements.len() + extra_stmts; - self.statements.resize(gap.end, Statement { - source_info: SourceInfo::outermost(DUMMY_SP), - kind: StatementKind::Nop, - }); + self.statements.resize( + gap.end, + Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop }, + ); for (splice_start, new_stmts) in splices.into_iter().rev() { let splice_end = splice_start + new_stmts.size_hint().0; while gap.end > splice_end { diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index 957b63584be..3247bdbf105 100644 --- a/compiler/rustc_middle/src/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/query/on_disk_cache.rs @@ -327,15 +327,18 @@ impl OnDiskCache { // Encode the file footer. let footer_pos = encoder.position() as u64; - encoder.encode_tagged(TAG_FILE_FOOTER, &Footer { - file_index_to_stable_id, - query_result_index, - side_effects_index, - interpret_alloc_index, - syntax_contexts, - expn_data, - foreign_expn_data, - }); + encoder.encode_tagged( + TAG_FILE_FOOTER, + &Footer { + file_index_to_stable_id, + query_result_index, + side_effects_index, + interpret_alloc_index, + syntax_contexts, + expn_data, + foreign_expn_data, + }, + ); // Encode the position of the footer as the last 8 bytes of the // file so we know where to look for it. diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 82b4fe193f0..2566081cf5d 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1094,10 +1094,13 @@ impl<'tcx> CommonLifetimes<'tcx> { .map(|i| { (0..NUM_PREINTERNED_RE_LATE_BOUNDS_V) .map(|v| { - mk(ty::ReBound(ty::DebruijnIndex::from(i), ty::BoundRegion { - var: ty::BoundVar::from(v), - kind: ty::BoundRegionKind::Anon, - })) + mk(ty::ReBound( + ty::DebruijnIndex::from(i), + ty::BoundRegion { + var: ty::BoundVar::from(v), + kind: ty::BoundRegionKind::Anon, + }, + )) }) .collect() }) @@ -3146,12 +3149,15 @@ impl<'tcx> TyCtxt<'tcx> { } let generics = self.generics_of(new_parent); - return ty::Region::new_early_param(self, ty::EarlyParamRegion { - index: generics - .param_def_id_to_index(self, ebv.to_def_id()) - .expect("early-bound var should be present in fn generics"), - name: self.item_name(ebv.to_def_id()), - }); + return ty::Region::new_early_param( + self, + ty::EarlyParamRegion { + index: generics + .param_def_id_to_index(self, ebv.to_def_id()) + .expect("early-bound var should be present in fn generics"), + name: self.item_name(ebv.to_def_id()), + }, + ); } resolve_bound_vars::ResolvedArg::LateBound(_, _, lbv) => { let new_parent = self.local_parent(lbv); diff --git a/compiler/rustc_middle/src/ty/fold.rs b/compiler/rustc_middle/src/ty/fold.rs index 067516917ef..4ea4050ed8b 100644 --- a/compiler/rustc_middle/src/ty/fold.rs +++ b/compiler/rustc_middle/src/ty/fold.rs @@ -280,21 +280,26 @@ impl<'tcx> TyCtxt<'tcx> { T: TypeFoldable>, { let shift_bv = |bv: ty::BoundVar| ty::BoundVar::from_usize(bv.as_usize() + bound_vars); - self.replace_escaping_bound_vars_uncached(value, FnMutDelegate { - regions: &mut |r: ty::BoundRegion| { - ty::Region::new_bound(self, ty::INNERMOST, ty::BoundRegion { - var: shift_bv(r.var), - kind: r.kind, - }) + self.replace_escaping_bound_vars_uncached( + value, + FnMutDelegate { + regions: &mut |r: ty::BoundRegion| { + ty::Region::new_bound( + self, + ty::INNERMOST, + ty::BoundRegion { var: shift_bv(r.var), kind: r.kind }, + ) + }, + types: &mut |t: ty::BoundTy| { + Ty::new_bound( + self, + ty::INNERMOST, + ty::BoundTy { var: shift_bv(t.var), kind: t.kind }, + ) + }, + consts: &mut |c| ty::Const::new_bound(self, ty::INNERMOST, shift_bv(c)), }, - types: &mut |t: ty::BoundTy| { - Ty::new_bound(self, ty::INNERMOST, ty::BoundTy { - var: shift_bv(t.var), - kind: t.kind, - }) - }, - consts: &mut |c| ty::Const::new_bound(self, ty::INNERMOST, shift_bv(c)), - }) + ) } /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 3ced64b5b80..e5015ea3c3d 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -1369,10 +1369,11 @@ pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> { // `def_span` unconditionally (which may have a perf penalty). let span = if !span.is_dummy() { span } else { tcx.def_span(instance.def_id()) }; - self.handle_fn_abi_err(*err, span, FnAbiRequest::OfInstance { - instance, - extra_args, - }) + self.handle_fn_abi_err( + *err, + span, + FnAbiRequest::OfInstance { instance, extra_args }, + ) }), ) } diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 398ed57faeb..94bd359f6eb 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -759,10 +759,11 @@ impl<'tcx> TyCtxt<'tcx> { assert_eq!(re, self.lifetimes.re_erased); let var = ty::BoundVar::from_usize(vars.len()); vars.push(ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon)); - ty::Region::new_bound(self, debruijn, ty::BoundRegion { - var, - kind: ty::BoundRegionKind::Anon, - }) + ty::Region::new_bound( + self, + debruijn, + ty::BoundRegion { var, kind: ty::BoundRegionKind::Anon }, + ) }); ty::EarlyBinder::bind(ty::Binder::bind_with_vars( ty, diff --git a/compiler/rustc_mir_build/src/builder/cfg.rs b/compiler/rustc_mir_build/src/builder/cfg.rs index 42212f2518b..082cdc2e2a4 100644 --- a/compiler/rustc_mir_build/src/builder/cfg.rs +++ b/compiler/rustc_mir_build/src/builder/cfg.rs @@ -40,10 +40,10 @@ impl<'tcx> CFG<'tcx> { place: Place<'tcx>, rvalue: Rvalue<'tcx>, ) { - self.push(block, Statement { - source_info, - kind: StatementKind::Assign(Box::new((place, rvalue))), - }); + self.push( + block, + Statement { source_info, kind: StatementKind::Assign(Box::new((place, rvalue))) }, + ); } pub(crate) fn push_assign_constant( diff --git a/compiler/rustc_mir_build/src/builder/expr/as_place.rs b/compiler/rustc_mir_build/src/builder/expr/as_place.rs index 482f1e3840b..308ca442b40 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_place.rs @@ -484,16 +484,19 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { }); let place = place_builder.to_place(this); - this.cfg.push(block, Statement { - source_info: ty_source_info, - kind: StatementKind::AscribeUserType( - Box::new((place, UserTypeProjection { - base: annotation_index, - projs: vec![], - })), - Variance::Invariant, - ), - }); + this.cfg.push( + block, + Statement { + source_info: ty_source_info, + kind: StatementKind::AscribeUserType( + Box::new(( + place, + UserTypeProjection { base: annotation_index, projs: vec![] }, + )), + Variance::Invariant, + ), + }, + ); } block.and(place_builder) } @@ -510,16 +513,19 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { user_ty: user_ty.clone(), inferred_ty: expr.ty, }); - this.cfg.push(block, Statement { - source_info: ty_source_info, - kind: StatementKind::AscribeUserType( - Box::new((Place::from(temp), UserTypeProjection { - base: annotation_index, - projs: vec![], - })), - Variance::Invariant, - ), - }); + this.cfg.push( + block, + Statement { + source_info: ty_source_info, + kind: StatementKind::AscribeUserType( + Box::new(( + Place::from(temp), + UserTypeProjection { base: annotation_index, projs: vec![] }, + )), + Variance::Invariant, + ), + }, + ); } block.and(PlaceBuilder::from(temp)) } diff --git a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs index e7713f0a1d6..2c9a1de7f99 100644 --- a/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/builder/expr/as_rvalue.rs @@ -151,19 +151,23 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); let storage = this.temp(Ty::new_mut_ptr(tcx, tcx.types.u8), expr_span); let success = this.cfg.start_new_block(); - this.cfg.terminate(block, source_info, TerminatorKind::Call { - func: exchange_malloc, - args: [Spanned { node: Operand::Move(size), span: DUMMY_SP }, Spanned { - node: Operand::Move(align), - span: DUMMY_SP, - }] - .into(), - destination: storage, - target: Some(success), - unwind: UnwindAction::Continue, - call_source: CallSource::Misc, - fn_span: expr_span, - }); + this.cfg.terminate( + block, + source_info, + TerminatorKind::Call { + func: exchange_malloc, + args: [ + Spanned { node: Operand::Move(size), span: DUMMY_SP }, + Spanned { node: Operand::Move(align), span: DUMMY_SP }, + ] + .into(), + destination: storage, + target: Some(success), + unwind: UnwindAction::Continue, + call_source: CallSource::Misc, + fn_span: expr_span, + }, + ); this.diverge_from(block); block = success; @@ -171,10 +175,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // and therefore is not considered during coroutine auto-trait // determination. See the comment about `box` at `yield_in_scope`. let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span)); - this.cfg.push(block, Statement { - source_info, - kind: StatementKind::StorageLive(result), - }); + this.cfg.push( + block, + Statement { source_info, kind: StatementKind::StorageLive(result) }, + ); if let Some(scope) = scope.temp_lifetime { // schedule a shallow free of that memory, lest we unwind: this.schedule_drop_storage_and_value(expr_span, scope, result); @@ -272,12 +276,15 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); merge_place }; - this.cfg.push(block, Statement { - source_info, - kind: StatementKind::Intrinsic(Box::new( - NonDivergingIntrinsic::Assume(Operand::Move(assert_place)), - )), - }); + this.cfg.push( + block, + Statement { + source_info, + kind: StatementKind::Intrinsic(Box::new( + NonDivergingIntrinsic::Assume(Operand::Move(assert_place)), + )), + }, + ); } (op, ty) @@ -739,12 +746,16 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); if let Operand::Move(to_drop) = value_operand { let success = this.cfg.start_new_block(); - this.cfg.terminate(block, outer_source_info, TerminatorKind::Drop { - place: to_drop, - target: success, - unwind: UnwindAction::Continue, - replace: false, - }); + this.cfg.terminate( + block, + outer_source_info, + TerminatorKind::Drop { + place: to_drop, + target: success, + unwind: UnwindAction::Continue, + replace: false, + }, + ); this.diverge_from(block); block = success; } diff --git a/compiler/rustc_mir_build/src/builder/expr/into.rs b/compiler/rustc_mir_build/src/builder/expr/into.rs index b25cd0f4426..65dd061003d 100644 --- a/compiler/rustc_mir_build/src/builder/expr/into.rs +++ b/compiler/rustc_mir_build/src/builder/expr/into.rs @@ -220,10 +220,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { this.in_breakable_scope(Some(loop_block), destination, expr_span, move |this| { // conduct the test, if necessary let body_block = this.cfg.start_new_block(); - this.cfg.terminate(loop_block, source_info, TerminatorKind::FalseUnwind { - real_target: body_block, - unwind: UnwindAction::Continue, - }); + this.cfg.terminate( + loop_block, + source_info, + TerminatorKind::FalseUnwind { + real_target: body_block, + unwind: UnwindAction::Continue, + }, + ); this.diverge_from(loop_block); // The “return” value of the loop body must always be a unit. We therefore @@ -254,30 +258,34 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { debug!("expr_into_dest: fn_span={:?}", fn_span); - this.cfg.terminate(block, source_info, TerminatorKind::Call { - func: fun, - args, - unwind: UnwindAction::Continue, - destination, - // The presence or absence of a return edge affects control-flow sensitive - // MIR checks and ultimately whether code is accepted or not. We can only - // omit the return edge if a return type is visibly uninhabited to a module - // that makes the call. - target: expr - .ty - .is_inhabited_from( - this.tcx, - this.parent_module, - this.infcx.typing_env(this.param_env), - ) - .then_some(success), - call_source: if from_hir_call { - CallSource::Normal - } else { - CallSource::OverloadedOperator + this.cfg.terminate( + block, + source_info, + TerminatorKind::Call { + func: fun, + args, + unwind: UnwindAction::Continue, + destination, + // The presence or absence of a return edge affects control-flow sensitive + // MIR checks and ultimately whether code is accepted or not. We can only + // omit the return edge if a return type is visibly uninhabited to a module + // that makes the call. + target: expr + .ty + .is_inhabited_from( + this.tcx, + this.parent_module, + this.infcx.typing_env(this.param_env), + ) + .then_some(success), + call_source: if from_hir_call { + CallSource::Normal + } else { + CallSource::OverloadedOperator + }, + fn_span, }, - fn_span, - }); + ); this.diverge_from(block); success.unit() } @@ -494,9 +502,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let tmp = this.get_unit_temp(); let target = this.ast_block(tmp, target, block, source_info).into_block(); - this.cfg.terminate(target, source_info, TerminatorKind::Goto { - target: destination_block, - }); + this.cfg.terminate( + target, + source_info, + TerminatorKind::Goto { target: destination_block }, + ); mir::InlineAsmOperand::Label { target_index } } @@ -515,19 +525,23 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { AsmMacro::NakedAsm => InlineAsmMacro::NakedAsm, }; - this.cfg.terminate(block, source_info, TerminatorKind::InlineAsm { - asm_macro, - template, - operands, - options, - line_spans, - targets: targets.into_boxed_slice(), - unwind: if options.contains(InlineAsmOptions::MAY_UNWIND) { - UnwindAction::Continue - } else { - UnwindAction::Unreachable + this.cfg.terminate( + block, + source_info, + TerminatorKind::InlineAsm { + asm_macro, + template, + operands, + options, + line_spans, + targets: targets.into_boxed_slice(), + unwind: if options.contains(InlineAsmOptions::MAY_UNWIND) { + UnwindAction::Continue + } else { + UnwindAction::Unreachable + }, }, - }); + ); if options.contains(InlineAsmOptions::MAY_UNWIND) { this.diverge_from(block); } @@ -587,12 +601,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { this.as_operand(block, scope, value, LocalInfo::Boring, NeedsTemporary::No) ); let resume = this.cfg.start_new_block(); - this.cfg.terminate(block, source_info, TerminatorKind::Yield { - value, - resume, - resume_arg: destination, - drop: None, - }); + this.cfg.terminate( + block, + source_info, + TerminatorKind::Yield { value, resume, resume_arg: destination, drop: None }, + ); this.coroutine_drop_cleanup(block); resume.unit() } diff --git a/compiler/rustc_mir_build/src/builder/expr/stmt.rs b/compiler/rustc_mir_build/src/builder/expr/stmt.rs index 4ae3536d9c2..58090d3748b 100644 --- a/compiler/rustc_mir_build/src/builder/expr/stmt.rs +++ b/compiler/rustc_mir_build/src/builder/expr/stmt.rs @@ -123,11 +123,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { unpack!(block = this.break_for_tail_call(block, &args, source_info)); - this.cfg.terminate(block, source_info, TerminatorKind::TailCall { - func: fun, - args, - fn_span, - }); + this.cfg.terminate( + block, + source_info, + TerminatorKind::TailCall { func: fun, args, fn_span }, + ); this.cfg.start_new_block().unit() }) diff --git a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs index bca57817d66..ee331713736 100644 --- a/compiler/rustc_mir_build/src/builder/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/builder/matches/match_pair.rs @@ -173,10 +173,13 @@ impl<'tcx> MatchPairTree<'tcx> { let ascription = place.map(|source| { let span = pattern.span; let parent_id = cx.tcx.typeck_root_def_id(cx.def_id.to_def_id()); - let args = ty::InlineConstArgs::new(cx.tcx, ty::InlineConstArgsParts { - parent_args: ty::GenericArgs::identity_for_item(cx.tcx, parent_id), - ty: cx.infcx.next_ty_var(span), - }) + let args = ty::InlineConstArgs::new( + cx.tcx, + ty::InlineConstArgsParts { + parent_args: ty::GenericArgs::identity_for_item(cx.tcx, parent_id), + ty: cx.infcx.next_ty_var(span), + }, + ) .args; let user_ty = cx.infcx.canonicalize_user_type_annotation(ty::UserType::new( ty::UserTypeKind::TypeOf(def_id, ty::UserArgs { args, user_self_ty: None }), diff --git a/compiler/rustc_mir_build/src/builder/matches/mod.rs b/compiler/rustc_mir_build/src/builder/matches/mod.rs index a2f92a93ec5..ed577f7adeb 100644 --- a/compiler/rustc_mir_build/src/builder/matches/mod.rs +++ b/compiler/rustc_mir_build/src/builder/matches/mod.rs @@ -104,11 +104,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { variable_source_info: SourceInfo, declare_let_bindings: DeclareLetBindings, ) -> BlockAnd<()> { - self.then_else_break_inner(block, expr_id, ThenElseArgs { - temp_scope_override, - variable_source_info, - declare_let_bindings, - }) + self.then_else_break_inner( + block, + expr_id, + ThenElseArgs { temp_scope_override, variable_source_info, declare_let_bindings }, + ) } fn then_else_break_inner( @@ -134,16 +134,24 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let local_scope = this.local_scope(); let (lhs_success_block, failure_block) = this.in_if_then_scope(local_scope, expr_span, |this| { - this.then_else_break_inner(block, lhs, ThenElseArgs { - declare_let_bindings: DeclareLetBindings::LetNotPermitted, - ..args - }) + this.then_else_break_inner( + block, + lhs, + ThenElseArgs { + declare_let_bindings: DeclareLetBindings::LetNotPermitted, + ..args + }, + ) }); let rhs_success_block = this - .then_else_break_inner(failure_block, rhs, ThenElseArgs { - declare_let_bindings: DeclareLetBindings::LetNotPermitted, - ..args - }) + .then_else_break_inner( + failure_block, + rhs, + ThenElseArgs { + declare_let_bindings: DeclareLetBindings::LetNotPermitted, + ..args + }, + ) .into_block(); // Make the LHS and RHS success arms converge to a common block. @@ -170,10 +178,14 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { if this.tcx.sess.instrument_coverage() { this.cfg.push_coverage_span_marker(block, this.source_info(expr_span)); } - this.then_else_break_inner(block, arg, ThenElseArgs { - declare_let_bindings: DeclareLetBindings::LetNotPermitted, - ..args - }) + this.then_else_break_inner( + block, + arg, + ThenElseArgs { + declare_let_bindings: DeclareLetBindings::LetNotPermitted, + ..args + }, + ) }); this.break_for_else(success_block, args.variable_source_info); failure_block.unit() @@ -629,27 +641,30 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let ty_source_info = self.source_info(annotation.span); let base = self.canonical_user_type_annotations.push(annotation.clone()); - self.cfg.push(block, Statement { - source_info: ty_source_info, - kind: StatementKind::AscribeUserType( - Box::new((place, UserTypeProjection { base, projs: Vec::new() })), - // We always use invariant as the variance here. This is because the - // variance field from the ascription refers to the variance to use - // when applying the type to the value being matched, but this - // ascription applies rather to the type of the binding. e.g., in this - // example: - // - // ``` - // let x: T = - // ``` - // - // We are creating an ascription that defines the type of `x` to be - // exactly `T` (i.e., with invariance). The variance field, in - // contrast, is intended to be used to relate `T` to the type of - // ``. - ty::Invariant, - ), - }); + self.cfg.push( + block, + Statement { + source_info: ty_source_info, + kind: StatementKind::AscribeUserType( + Box::new((place, UserTypeProjection { base, projs: Vec::new() })), + // We always use invariant as the variance here. This is because the + // variance field from the ascription refers to the variance to use + // when applying the type to the value being matched, but this + // ascription applies rather to the type of the binding. e.g., in this + // example: + // + // ``` + // let x: T = + // ``` + // + // We are creating an ascription that defines the type of `x` to be + // exactly `T` (i.e., with invariance). The variance field, in + // contrast, is intended to be used to relate `T` to the type of + // ``. + ty::Invariant, + ), + }, + ); self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard); block.unit() @@ -2549,13 +2564,19 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let source_info = self.source_info(ascription.annotation.span); let base = self.canonical_user_type_annotations.push(ascription.annotation); - self.cfg.push(block, Statement { - source_info, - kind: StatementKind::AscribeUserType( - Box::new((ascription.source, UserTypeProjection { base, projs: Vec::new() })), - ascription.variance, - ), - }); + self.cfg.push( + block, + Statement { + source_info, + kind: StatementKind::AscribeUserType( + Box::new(( + ascription.source, + UserTypeProjection { base, projs: Vec::new() }, + )), + ascription.variance, + ), + }, + ); } } diff --git a/compiler/rustc_mir_build/src/builder/matches/test.rs b/compiler/rustc_mir_build/src/builder/matches/test.rs index 834f8be0d00..a7a028bff97 100644 --- a/compiler/rustc_mir_build/src/builder/matches/test.rs +++ b/compiler/rustc_mir_build/src/builder/matches/test.rs @@ -327,15 +327,23 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); // `let temp = ::deref(ref_src);` // or `let temp = ::deref_mut(ref_src);` - self.cfg.terminate(block, source_info, TerminatorKind::Call { - func: Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_: method })), - args: [Spanned { node: Operand::Move(ref_src), span }].into(), - destination: temp, - target: Some(target_block), - unwind: UnwindAction::Continue, - call_source: CallSource::Misc, - fn_span: source_info.span, - }); + self.cfg.terminate( + block, + source_info, + TerminatorKind::Call { + func: Operand::Constant(Box::new(ConstOperand { + span, + user_ty: None, + const_: method, + })), + args: [Spanned { node: Operand::Move(ref_src), span }].into(), + destination: temp, + target: Some(target_block), + unwind: UnwindAction::Continue, + call_source: CallSource::Misc, + fn_span: source_info.span, + }, + ); } /// Compare using the provided built-in comparison operator @@ -463,26 +471,33 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let bool_ty = self.tcx.types.bool; let eq_result = self.temp(bool_ty, source_info.span); let eq_block = self.cfg.start_new_block(); - self.cfg.terminate(block, source_info, TerminatorKind::Call { - func: Operand::Constant(Box::new(ConstOperand { - span: source_info.span, + self.cfg.terminate( + block, + source_info, + TerminatorKind::Call { + func: Operand::Constant(Box::new(ConstOperand { + span: source_info.span, - // FIXME(#54571): This constant comes from user input (a - // constant in a pattern). Are there forms where users can add - // type annotations here? For example, an associated constant? - // Need to experiment. - user_ty: None, + // FIXME(#54571): This constant comes from user input (a + // constant in a pattern). Are there forms where users can add + // type annotations here? For example, an associated constant? + // Need to experiment. + user_ty: None, - const_: method, - })), - args: [Spanned { node: val, span: DUMMY_SP }, Spanned { node: expect, span: DUMMY_SP }] + const_: method, + })), + args: [ + Spanned { node: val, span: DUMMY_SP }, + Spanned { node: expect, span: DUMMY_SP }, + ] .into(), - destination: eq_result, - target: Some(eq_block), - unwind: UnwindAction::Continue, - call_source: CallSource::MatchCmp, - fn_span: source_info.span, - }); + destination: eq_result, + target: Some(eq_block), + unwind: UnwindAction::Continue, + call_source: CallSource::MatchCmp, + fn_span: source_info.span, + }, + ); self.diverge_from(block); // check the result diff --git a/compiler/rustc_mir_build/src/builder/matches/util.rs b/compiler/rustc_mir_build/src/builder/matches/util.rs index 83e79572b2a..589e350a03f 100644 --- a/compiler/rustc_mir_build/src/builder/matches/util.rs +++ b/compiler/rustc_mir_build/src/builder/matches/util.rs @@ -20,10 +20,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { source_info: SourceInfo, ) { if imaginary_target != real_target { - self.cfg.terminate(from_block, source_info, TerminatorKind::FalseEdge { - real_target, - imaginary_target, - }); + self.cfg.terminate( + from_block, + source_info, + TerminatorKind::FalseEdge { real_target, imaginary_target }, + ); } else { self.cfg.goto(from_block, source_info, real_target) } diff --git a/compiler/rustc_mir_build/src/builder/misc.rs b/compiler/rustc_mir_build/src/builder/misc.rs index 9ea56a9574f..6e8e74fd4fc 100644 --- a/compiler/rustc_mir_build/src/builder/misc.rs +++ b/compiler/rustc_mir_build/src/builder/misc.rs @@ -45,11 +45,16 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ) -> Place<'tcx> { let usize_ty = self.tcx.types.usize; let temp = self.temp(usize_ty, source_info.span); - self.cfg.push_assign_constant(block, source_info, temp, ConstOperand { - span: source_info.span, - user_ty: None, - const_: Const::from_usize(self.tcx, value), - }); + self.cfg.push_assign_constant( + block, + source_info, + temp, + ConstOperand { + span: source_info.span, + user_ty: None, + const_: Const::from_usize(self.tcx, value), + }, + ); temp } diff --git a/compiler/rustc_mir_build/src/builder/scope.rs b/compiler/rustc_mir_build/src/builder/scope.rs index 945f02821d9..d3551ea3a97 100644 --- a/compiler/rustc_mir_build/src/builder/scope.rs +++ b/compiler/rustc_mir_build/src/builder/scope.rs @@ -532,12 +532,16 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { (Some(normal_block), Some(exit_block)) => { let target = self.cfg.start_new_block(); let source_info = self.source_info(span); - self.cfg.terminate(normal_block.into_block(), source_info, TerminatorKind::Goto { - target, - }); - self.cfg.terminate(exit_block.into_block(), source_info, TerminatorKind::Goto { - target, - }); + self.cfg.terminate( + normal_block.into_block(), + source_info, + TerminatorKind::Goto { target }, + ); + self.cfg.terminate( + exit_block.into_block(), + source_info, + TerminatorKind::Goto { target }, + ); target.unit() } } @@ -833,30 +837,37 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { unwind_drops.add_entry_point(block, unwind_entry_point); let next = self.cfg.start_new_block(); - self.cfg.terminate(block, source_info, TerminatorKind::Drop { - place: local.into(), - target: next, - unwind: UnwindAction::Continue, - replace: false, - }); + self.cfg.terminate( + block, + source_info, + TerminatorKind::Drop { + place: local.into(), + target: next, + unwind: UnwindAction::Continue, + replace: false, + }, + ); block = next; } DropKind::ForLint => { - self.cfg.push(block, Statement { - source_info, - kind: StatementKind::BackwardIncompatibleDropHint { - place: Box::new(local.into()), - reason: BackwardIncompatibleDropReason::Edition2024, + self.cfg.push( + block, + Statement { + source_info, + kind: StatementKind::BackwardIncompatibleDropHint { + place: Box::new(local.into()), + reason: BackwardIncompatibleDropReason::Edition2024, + }, }, - }); + ); } DropKind::Storage => { // Only temps and vars need their storage dead. assert!(local.index() > self.arg_count); - self.cfg.push(block, Statement { - source_info, - kind: StatementKind::StorageDead(local), - }); + self.cfg.push( + block, + Statement { source_info, kind: StatementKind::StorageDead(local) }, + ); } } } @@ -1350,12 +1361,16 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let assign_unwind = self.cfg.start_new_cleanup_block(); self.cfg.push_assign(assign_unwind, source_info, place, value.clone()); - self.cfg.terminate(block, source_info, TerminatorKind::Drop { - place, - target: assign, - unwind: UnwindAction::Cleanup(assign_unwind), - replace: true, - }); + self.cfg.terminate( + block, + source_info, + TerminatorKind::Drop { + place, + target: assign, + unwind: UnwindAction::Cleanup(assign_unwind), + replace: true, + }, + ); self.diverge_from(block); assign.unit() @@ -1375,13 +1390,17 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let source_info = self.source_info(span); let success_block = self.cfg.start_new_block(); - self.cfg.terminate(block, source_info, TerminatorKind::Assert { - cond, - expected, - msg: Box::new(msg), - target: success_block, - unwind: UnwindAction::Continue, - }); + self.cfg.terminate( + block, + source_info, + TerminatorKind::Assert { + cond, + expected, + msg: Box::new(msg), + target: success_block, + unwind: UnwindAction::Continue, + }, + ); self.diverge_from(block); success_block @@ -1481,12 +1500,16 @@ fn build_scope_drops<'tcx>( unwind_drops.add_entry_point(block, unwind_to); let next = cfg.start_new_block(); - cfg.terminate(block, source_info, TerminatorKind::Drop { - place: local.into(), - target: next, - unwind: UnwindAction::Continue, - replace: false, - }); + cfg.terminate( + block, + source_info, + TerminatorKind::Drop { + place: local.into(), + target: next, + unwind: UnwindAction::Continue, + replace: false, + }, + ); block = next; } DropKind::ForLint => { @@ -1509,13 +1532,16 @@ fn build_scope_drops<'tcx>( continue; } - cfg.push(block, Statement { - source_info, - kind: StatementKind::BackwardIncompatibleDropHint { - place: Box::new(local.into()), - reason: BackwardIncompatibleDropReason::Edition2024, + cfg.push( + block, + Statement { + source_info, + kind: StatementKind::BackwardIncompatibleDropHint { + place: Box::new(local.into()), + reason: BackwardIncompatibleDropReason::Edition2024, + }, }, - }); + ); } DropKind::Storage => { // Ordinarily, storage-dead nodes are not emitted on unwind, so we don't diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index b6494173b0f..2b9b948763f 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -525,11 +525,10 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { .copied() .filter(|feature| missing.contains(feature)) .collect(); - self.requires_unsafe(expr.span, CallToFunctionWith { - function: func_did, - missing, - build_enabled, - }); + self.requires_unsafe( + expr.span, + CallToFunctionWith { function: func_did, missing, build_enabled }, + ); } } } @@ -1186,9 +1185,11 @@ pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) { warnings.sort_by_key(|w| w.block_span); for UnusedUnsafeWarning { hir_id, block_span, enclosing_unsafe } in warnings { let block_span = tcx.sess.source_map().guess_head_span(block_span); - tcx.emit_node_span_lint(UNUSED_UNSAFE, hir_id, block_span, UnusedUnsafe { - span: block_span, - enclosing: enclosing_unsafe, - }); + tcx.emit_node_span_lint( + UNUSED_UNSAFE, + hir_id, + block_span, + UnusedUnsafe { span: block_span, enclosing: enclosing_unsafe }, + ); } } diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index 9d114e67559..a01609012b8 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -186,11 +186,9 @@ impl<'tcx> ThirBuildCx<'tcx> { let ty = if fn_decl.c_variadic && index == fn_decl.inputs.len() { let va_list_did = self.tcx.require_lang_item(LangItem::VaList, Some(param.span)); - self.tcx.type_of(va_list_did).instantiate(self.tcx, &[self - .tcx - .lifetimes - .re_erased - .into()]) + self.tcx + .type_of(va_list_did) + .instantiate(self.tcx, &[self.tcx.lifetimes.re_erased.into()]) } else { fn_sig.inputs()[index] }; diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index 74b0e84068c..c1c47ecccf3 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -233,12 +233,15 @@ where .patch_terminator(bb, TerminatorKind::Goto { target: self.succ }); } DropStyle::Static => { - self.elaborator.patch().patch_terminator(bb, TerminatorKind::Drop { - place: self.place, - target: self.succ, - unwind: self.unwind.into_action(), - replace: false, - }); + self.elaborator.patch().patch_terminator( + bb, + TerminatorKind::Drop { + place: self.place, + target: self.succ, + unwind: self.unwind.into_action(), + replace: false, + }, + ); } DropStyle::Conditional => { let drop_bb = self.complete_drop(self.succ, self.unwind); @@ -729,12 +732,15 @@ where }; let loop_block = self.elaborator.patch().new_block(loop_block); - self.elaborator.patch().patch_terminator(drop_block, TerminatorKind::Drop { - place: tcx.mk_place_deref(ptr), - target: loop_block, - unwind: unwind.into_action(), - replace: false, - }); + self.elaborator.patch().patch_terminator( + drop_block, + TerminatorKind::Drop { + place: tcx.mk_place_deref(ptr), + target: loop_block, + unwind: unwind.into_action(), + replace: false, + }, + ); loop_block } diff --git a/compiler/rustc_mir_dataflow/src/framework/direction.rs b/compiler/rustc_mir_dataflow/src/framework/direction.rs index 6427fd0fd29..07517d7edab 100644 --- a/compiler/rustc_mir_dataflow/src/framework/direction.rs +++ b/compiler/rustc_mir_dataflow/src/framework/direction.rs @@ -305,10 +305,11 @@ impl Direction for Forward { // `exit_state`, so pass it directly to `apply_switch_int_edge_effect` to save // a clone of the dataflow state. let otherwise = targets.otherwise(); - analysis.apply_switch_int_edge_effect(&mut data, exit_state, SwitchIntTarget { - value: None, - target: otherwise, - }); + analysis.apply_switch_int_edge_effect( + &mut data, + exit_state, + SwitchIntTarget { value: None, target: otherwise }, + ); propagate(otherwise, exit_state); } else { for target in targets.all_targets() { diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs index 9ccabb46c63..448fad2dc3e 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -670,10 +670,10 @@ where r#"{state}"#, colspan = this.style.num_state_columns(), fmt = fmt, - state = dot::escape_html(&format!("{:?}", DebugWithAdapter { - this: state, - ctxt: analysis - })), + state = dot::escape_html(&format!( + "{:?}", + DebugWithAdapter { this: state, ctxt: analysis } + )), ) }) } diff --git a/compiler/rustc_mir_dataflow/src/framework/tests.rs b/compiler/rustc_mir_dataflow/src/framework/tests.rs index 5b3a9ccba69..ae0f1179e6f 100644 --- a/compiler/rustc_mir_dataflow/src/framework/tests.rs +++ b/compiler/rustc_mir_dataflow/src/framework/tests.rs @@ -30,26 +30,32 @@ fn mock_body<'tcx>() -> mir::Body<'tcx> { block(4, mir::TerminatorKind::Return); block(1, mir::TerminatorKind::Return); - block(2, mir::TerminatorKind::Call { - func: mir::Operand::Copy(dummy_place.clone()), - args: [].into(), - destination: dummy_place.clone(), - target: Some(mir::START_BLOCK), - unwind: mir::UnwindAction::Continue, - call_source: mir::CallSource::Misc, - fn_span: DUMMY_SP, - }); + block( + 2, + mir::TerminatorKind::Call { + func: mir::Operand::Copy(dummy_place.clone()), + args: [].into(), + destination: dummy_place.clone(), + target: Some(mir::START_BLOCK), + unwind: mir::UnwindAction::Continue, + call_source: mir::CallSource::Misc, + fn_span: DUMMY_SP, + }, + ); block(3, mir::TerminatorKind::Return); block(0, mir::TerminatorKind::Return); - block(4, mir::TerminatorKind::Call { - func: mir::Operand::Copy(dummy_place.clone()), - args: [].into(), - destination: dummy_place.clone(), - target: Some(mir::START_BLOCK), - unwind: mir::UnwindAction::Continue, - call_source: mir::CallSource::Misc, - fn_span: DUMMY_SP, - }); + block( + 4, + mir::TerminatorKind::Call { + func: mir::Operand::Copy(dummy_place.clone()), + args: [].into(), + destination: dummy_place.clone(), + target: Some(mir::START_BLOCK), + unwind: mir::UnwindAction::Continue, + call_source: mir::CallSource::Misc, + fn_span: DUMMY_SP, + }, + ); mir::Body::new_cfg_only(blocks) } diff --git a/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs index 87ae2b71654..8716fd1c098 100644 --- a/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs +++ b/compiler/rustc_mir_transform/src/add_moves_for_packed_drops.rs @@ -99,10 +99,13 @@ fn add_move_for_packed_drop<'tcx>( patch.add_statement(loc, StatementKind::StorageLive(temp)); patch.add_assign(loc, Place::from(temp), Rvalue::Use(Operand::Move(*place))); - patch.patch_terminator(loc.block, TerminatorKind::Drop { - place: Place::from(temp), - target: storage_dead_block, - unwind, - replace, - }); + patch.patch_terminator( + loc.block, + TerminatorKind::Drop { + place: Place::from(temp), + target: storage_dead_block, + unwind, + replace, + }, + ); } diff --git a/compiler/rustc_mir_transform/src/add_retag.rs b/compiler/rustc_mir_transform/src/add_retag.rs index 1fc788a2dad..e5a28d1b66c 100644 --- a/compiler/rustc_mir_transform/src/add_retag.rs +++ b/compiler/rustc_mir_transform/src/add_retag.rs @@ -111,10 +111,13 @@ impl<'tcx> crate::MirPass<'tcx> for AddRetag { .collect::>(); // Now we go over the returns we collected to retag the return values. for (source_info, dest_place, dest_block) in returns { - basic_blocks[dest_block].statements.insert(0, Statement { - source_info, - kind: StatementKind::Retag(RetagKind::Default, Box::new(dest_place)), - }); + basic_blocks[dest_block].statements.insert( + 0, + Statement { + source_info, + kind: StatementKind::Retag(RetagKind::Default, Box::new(dest_place)), + }, + ); } // PART 3 @@ -169,10 +172,13 @@ impl<'tcx> crate::MirPass<'tcx> for AddRetag { }; // Insert a retag after the statement. let source_info = block_data.statements[i].source_info; - block_data.statements.insert(i + 1, Statement { - source_info, - kind: StatementKind::Retag(retag_kind, Box::new(place)), - }); + block_data.statements.insert( + i + 1, + Statement { + source_info, + kind: StatementKind::Retag(retag_kind, Box::new(place)), + }, + ); } } } diff --git a/compiler/rustc_mir_transform/src/check_call_recursion.rs b/compiler/rustc_mir_transform/src/check_call_recursion.rs index 51fd3c6512e..e49723a6c39 100644 --- a/compiler/rustc_mir_transform/src/check_call_recursion.rs +++ b/compiler/rustc_mir_transform/src/check_call_recursion.rs @@ -83,10 +83,12 @@ fn check_recursion<'tcx>( let sp = tcx.def_span(def_id); let hir_id = tcx.local_def_id_to_hir_id(def_id); - tcx.emit_node_span_lint(UNCONDITIONAL_RECURSION, hir_id, sp, UnconditionalRecursion { - span: sp, - call_sites: vis.reachable_recursive_calls, - }); + tcx.emit_node_span_lint( + UNCONDITIONAL_RECURSION, + hir_id, + sp, + UnconditionalRecursion { span: sp, call_sites: vis.reachable_recursive_calls }, + ); } } diff --git a/compiler/rustc_mir_transform/src/coroutine.rs b/compiler/rustc_mir_transform/src/coroutine.rs index 3b75be58e43..a9bdbeb9cb8 100644 --- a/compiler/rustc_mir_transform/src/coroutine.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -1044,11 +1044,14 @@ fn insert_switch<'tcx>( let switch = TerminatorKind::SwitchInt { discr: Operand::Move(discr), targets: switch_targets }; let source_info = SourceInfo::outermost(body.span); - body.basic_blocks_mut().raw.insert(0, BasicBlockData { - statements: vec![assign], - terminator: Some(Terminator { source_info, kind: switch }), - is_cleanup: false, - }); + body.basic_blocks_mut().raw.insert( + 0, + BasicBlockData { + statements: vec![assign], + terminator: Some(Terminator { source_info, kind: switch }), + is_cleanup: false, + }, + ); let blocks = body.basic_blocks_mut().iter_mut(); @@ -1594,13 +1597,16 @@ impl<'tcx> crate::MirPass<'tcx> for StateTransform { // (which is now a generator interior). let source_info = SourceInfo::outermost(body.span); let stmts = &mut body.basic_blocks_mut()[START_BLOCK].statements; - stmts.insert(0, Statement { - source_info, - kind: StatementKind::Assign(Box::new(( - old_resume_local.into(), - Rvalue::Use(Operand::Move(resume_local.into())), - ))), - }); + stmts.insert( + 0, + Statement { + source_info, + kind: StatementKind::Assign(Box::new(( + old_resume_local.into(), + Rvalue::Use(Operand::Move(resume_local.into())), + ))), + }, + ); let always_live_locals = always_storage_live_locals(body); @@ -1839,12 +1845,17 @@ fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &CoroutineLayout<'tcx>, bo continue; }; - check_must_not_suspend_ty(tcx, decl.ty, hir_id, SuspendCheckData { - source_span: decl.source_info.span, - yield_span: yield_source_info.span, - plural_len: 1, - ..Default::default() - }); + check_must_not_suspend_ty( + tcx, + decl.ty, + hir_id, + SuspendCheckData { + source_span: decl.source_info.span, + yield_span: yield_source_info.span, + plural_len: 1, + ..Default::default() + }, + ); } } } @@ -1883,13 +1894,17 @@ fn check_must_not_suspend_ty<'tcx>( ty::Adt(_, args) if ty.is_box() => { let boxed_ty = args.type_at(0); let allocator_ty = args.type_at(1); - check_must_not_suspend_ty(tcx, boxed_ty, hir_id, SuspendCheckData { - descr_pre: &format!("{}boxed ", data.descr_pre), - ..data - }) || check_must_not_suspend_ty(tcx, allocator_ty, hir_id, SuspendCheckData { - descr_pre: &format!("{}allocator ", data.descr_pre), - ..data - }) + check_must_not_suspend_ty( + tcx, + boxed_ty, + hir_id, + SuspendCheckData { descr_pre: &format!("{}boxed ", data.descr_pre), ..data }, + ) || check_must_not_suspend_ty( + tcx, + allocator_ty, + hir_id, + SuspendCheckData { descr_pre: &format!("{}allocator ", data.descr_pre), ..data }, + ) } ty::Adt(def, _) => check_must_not_suspend_def(tcx, def.did(), hir_id, data), // FIXME: support adding the attribute to TAITs @@ -1902,10 +1917,12 @@ fn check_must_not_suspend_ty<'tcx>( { let def_id = poly_trait_predicate.trait_ref.def_id; let descr_pre = &format!("{}implementer{} of ", data.descr_pre, plural_suffix); - if check_must_not_suspend_def(tcx, def_id, hir_id, SuspendCheckData { - descr_pre, - ..data - }) { + if check_must_not_suspend_def( + tcx, + def_id, + hir_id, + SuspendCheckData { descr_pre, ..data }, + ) { has_emitted = true; break; } @@ -1919,10 +1936,12 @@ fn check_must_not_suspend_ty<'tcx>( if let ty::ExistentialPredicate::Trait(ref trait_ref) = predicate.skip_binder() { let def_id = trait_ref.def_id; let descr_post = &format!(" trait object{}{}", plural_suffix, data.descr_post); - if check_must_not_suspend_def(tcx, def_id, hir_id, SuspendCheckData { - descr_post, - ..data - }) { + if check_must_not_suspend_def( + tcx, + def_id, + hir_id, + SuspendCheckData { descr_post, ..data }, + ) { has_emitted = true; break; } @@ -1934,10 +1953,12 @@ fn check_must_not_suspend_ty<'tcx>( let mut has_emitted = false; for (i, ty) in fields.iter().enumerate() { let descr_post = &format!(" in tuple element {i}"); - if check_must_not_suspend_ty(tcx, ty, hir_id, SuspendCheckData { - descr_post, - ..data - }) { + if check_must_not_suspend_ty( + tcx, + ty, + hir_id, + SuspendCheckData { descr_post, ..data }, + ) { has_emitted = true; } } @@ -1945,12 +1966,17 @@ fn check_must_not_suspend_ty<'tcx>( } ty::Array(ty, len) => { let descr_pre = &format!("{}array{} of ", data.descr_pre, plural_suffix); - check_must_not_suspend_ty(tcx, ty, hir_id, SuspendCheckData { - descr_pre, - // FIXME(must_not_suspend): This is wrong. We should handle printing unevaluated consts. - plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1, - ..data - }) + check_must_not_suspend_ty( + tcx, + ty, + hir_id, + SuspendCheckData { + descr_pre, + // FIXME(must_not_suspend): This is wrong. We should handle printing unevaluated consts. + plural_len: len.try_to_target_usize(tcx).unwrap_or(0) as usize + 1, + ..data + }, + ) } // If drop tracking is enabled, we want to look through references, since the referent // may not be considered live across the await point. diff --git a/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs b/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs index 9f5bb015fa3..0f5fcb0d8eb 100644 --- a/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs +++ b/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs @@ -138,10 +138,10 @@ pub(crate) fn coroutine_by_move_body_def_id<'tcx>( // If the parent capture is by-ref, then we need to apply an additional // deref before applying any further projections to this place. if parent_capture.is_by_ref() { - child_precise_captures.insert(0, Projection { - ty: parent_capture.place.ty(), - kind: ProjectionKind::Deref, - }); + child_precise_captures.insert( + 0, + Projection { ty: parent_capture.place.ty(), kind: ProjectionKind::Deref }, + ); } // If the child capture is by-ref, then we need to apply a "ref" // projection (i.e. `&`) at the end. But wait! We don't have that diff --git a/compiler/rustc_mir_transform/src/coverage/counters/node_flow/tests.rs b/compiler/rustc_mir_transform/src/coverage/counters/node_flow/tests.rs index b509a14514b..46c46c743c2 100644 --- a/compiler/rustc_mir_transform/src/coverage/counters/node_flow/tests.rs +++ b/compiler/rustc_mir_transform/src/coverage/counters/node_flow/tests.rs @@ -20,29 +20,25 @@ fn make_graph(num_nodes: usize, edge_pairs: Vec<(Node, Node)>) /// (Knuth & Stevenson, 1973), but with 0-based node IDs. #[test] fn example_driver() { - let graph = make_graph::(5, vec![ - (0, 1), - (0, 3), - (1, 0), - (1, 2), - (2, 1), - (2, 4), - (3, 3), - (3, 4), - (4, 0), - ]); + let graph = make_graph::( + 5, + vec![(0, 1), (0, 3), (1, 0), (1, 2), (2, 1), (2, 4), (3, 3), (3, 4), (4, 0)], + ); let node_flow_data = node_flow_data(&graph); let counters = make_node_counters(&node_flow_data, &[3, 1, 2, 0, 4]); - assert_eq!(format_counter_expressions(&counters), &[ - // (comment to force vertical formatting for clarity) - "[0]: +c0", - "[1]: +c0 +c2 -c4", - "[2]: +c2", - "[3]: +c3", - "[4]: +c4", - ]); + assert_eq!( + format_counter_expressions(&counters), + &[ + // (comment to force vertical formatting for clarity) + "[0]: +c0", + "[1]: +c0 +c2 -c4", + "[2]: +c2", + "[3]: +c3", + "[4]: +c4", + ] + ); } fn format_counter_expressions(counters: &NodeCounters) -> Vec { diff --git a/compiler/rustc_mir_transform/src/coverage/tests.rs b/compiler/rustc_mir_transform/src/coverage/tests.rs index b2ee50de50a..3c0053c610d 100644 --- a/compiler/rustc_mir_transform/src/coverage/tests.rs +++ b/compiler/rustc_mir_transform/src/coverage/tests.rs @@ -129,15 +129,18 @@ impl<'tcx> MockBlocks<'tcx> { } fn call(&mut self, some_from_block: Option) -> BasicBlock { - self.add_block_from(some_from_block, TerminatorKind::Call { - func: Operand::Copy(self.dummy_place.clone()), - args: [].into(), - destination: self.dummy_place.clone(), - target: Some(TEMP_BLOCK), - unwind: UnwindAction::Continue, - call_source: CallSource::Misc, - fn_span: DUMMY_SP, - }) + self.add_block_from( + some_from_block, + TerminatorKind::Call { + func: Operand::Copy(self.dummy_place.clone()), + args: [].into(), + destination: self.dummy_place.clone(), + target: Some(TEMP_BLOCK), + unwind: UnwindAction::Continue, + call_source: CallSource::Misc, + fn_span: DUMMY_SP, + }, + ) } fn goto(&mut self, some_from_block: Option) -> BasicBlock { diff --git a/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs b/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs index 3d560bdf75c..9a6a153c7ba 100644 --- a/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs +++ b/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs @@ -90,10 +90,12 @@ fn has_ffi_unwind_calls(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> bool { let span = terminator.source_info.span; let foreign = fn_def_id.is_some(); - tcx.emit_node_span_lint(FFI_UNWIND_CALLS, lint_root, span, errors::FfiUnwindCall { + tcx.emit_node_span_lint( + FFI_UNWIND_CALLS, + lint_root, span, - foreign, - }); + errors::FfiUnwindCall { span, foreign }, + ); tainted = true; } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index f8b0688dfdc..07c031e852d 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -1111,10 +1111,13 @@ fn new_call_temp<'tcx>( }); if let Some(block) = return_block { - caller_body[block].statements.insert(0, Statement { - source_info: callsite.source_info, - kind: StatementKind::StorageDead(local), - }); + caller_body[block].statements.insert( + 0, + Statement { + source_info: callsite.source_info, + kind: StatementKind::StorageDead(local), + }, + ); } local diff --git a/compiler/rustc_mir_transform/src/known_panics_lint.rs b/compiler/rustc_mir_transform/src/known_panics_lint.rs index e43254ba089..59de6ca84a7 100644 --- a/compiler/rustc_mir_transform/src/known_panics_lint.rs +++ b/compiler/rustc_mir_transform/src/known_panics_lint.rs @@ -296,11 +296,12 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { let source_info = self.body.source_info(location); if let Some(lint_root) = self.lint_root(*source_info) { let span = source_info.span; - self.tcx.emit_node_span_lint(lint_kind.lint(), lint_root, span, AssertLint { + self.tcx.emit_node_span_lint( + lint_kind.lint(), + lint_root, span, - assert_kind, - lint_kind, - }); + AssertLint { span, assert_kind, lint_kind }, + ); } } diff --git a/compiler/rustc_mir_transform/src/promote_consts.rs b/compiler/rustc_mir_transform/src/promote_consts.rs index 4dbbcae1756..c8d8dc147e9 100644 --- a/compiler/rustc_mir_transform/src/promote_consts.rs +++ b/compiler/rustc_mir_transform/src/promote_consts.rs @@ -920,19 +920,23 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { self.extra_statements.push((loc, promoted_ref_statement)); ( - Rvalue::Ref(tcx.lifetimes.re_erased, *borrow_kind, Place { - local: mem::replace(&mut place.local, promoted_ref), - projection: List::empty(), - }), + Rvalue::Ref( + tcx.lifetimes.re_erased, + *borrow_kind, + Place { + local: mem::replace(&mut place.local, promoted_ref), + projection: List::empty(), + }, + ), promoted_operand, ) }; assert_eq!(self.new_block(), START_BLOCK); - self.visit_rvalue(&mut rvalue, Location { - block: START_BLOCK, - statement_index: usize::MAX, - }); + self.visit_rvalue( + &mut rvalue, + Location { block: START_BLOCK, statement_index: usize::MAX }, + ); let span = self.promoted.span; self.assign(RETURN_PLACE, rvalue, span); diff --git a/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs b/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs index 1d53440cf0b..94b1b4b1855 100644 --- a/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs +++ b/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs @@ -447,17 +447,19 @@ impl<'tcx> AsyncDestructorCtorShimBuilder<'tcx> { } fn combine_sync_surface(&mut self) -> Ty<'tcx> { - self.apply_combinator(1, LangItem::AsyncDropSurfaceDropInPlace, &[self - .self_ty - .unwrap() - .into()]) + self.apply_combinator( + 1, + LangItem::AsyncDropSurfaceDropInPlace, + &[self.self_ty.unwrap().into()], + ) } fn combine_deferred_drop_in_place(&mut self) -> Ty<'tcx> { - self.apply_combinator(1, LangItem::AsyncDropDeferredDropInPlace, &[self - .self_ty - .unwrap() - .into()]) + self.apply_combinator( + 1, + LangItem::AsyncDropDeferredDropInPlace, + &[self.self_ty.unwrap().into()], + ) } fn combine_fuse(&mut self, inner_future_ty: Ty<'tcx>) -> Ty<'tcx> { @@ -477,11 +479,11 @@ impl<'tcx> AsyncDestructorCtorShimBuilder<'tcx> { } fn combine_either(&mut self, other: Ty<'tcx>, matched: Ty<'tcx>) -> Ty<'tcx> { - self.apply_combinator(4, LangItem::AsyncDropEither, &[ - other.into(), - matched.into(), - self.self_ty.unwrap().into(), - ]) + self.apply_combinator( + 4, + LangItem::AsyncDropEither, + &[other.into(), matched.into(), self.self_ty.unwrap().into()], + ) } fn return_(mut self) -> Body<'tcx> { diff --git a/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs index c0f25c7ecfe..21bc51ecca1 100644 --- a/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs +++ b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs @@ -113,10 +113,13 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyComparisonIntegral { // if we have StorageDeads to remove then make sure to insert them at the top of // each target for bb_idx in new_targets.all_targets() { - storage_deads_to_insert.push((*bb_idx, Statement { - source_info: terminator.source_info, - kind: StatementKind::StorageDead(opt.to_switch_on.local), - })); + storage_deads_to_insert.push(( + *bb_idx, + Statement { + source_info: terminator.source_info, + kind: StatementKind::StorageDead(opt.to_switch_on.local), + }, + )); } } diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index a24b3b2e80f..9f769077e77 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -159,10 +159,11 @@ impl SsaLocals { ) { for &local in &self.assignment_order { match self.assignments[local] { - Set1::One(DefLocation::Argument) => f(local, AssignedValue::Arg, Location { - block: START_BLOCK, - statement_index: 0, - }), + Set1::One(DefLocation::Argument) => f( + local, + AssignedValue::Arg, + Location { block: START_BLOCK, statement_index: 0 }, + ), Set1::One(DefLocation::Assignment(loc)) => { let bb = &mut basic_blocks[loc.block]; // `loc` must point to a direct assignment to `local`. diff --git a/compiler/rustc_monomorphize/src/mono_checks/move_check.rs b/compiler/rustc_monomorphize/src/mono_checks/move_check.rs index 02b9397f9a9..838bfdab1ea 100644 --- a/compiler/rustc_monomorphize/src/mono_checks/move_check.rs +++ b/compiler/rustc_monomorphize/src/mono_checks/move_check.rs @@ -162,11 +162,12 @@ impl<'tcx> MoveCheckVisitor<'tcx> { // but correct span? This would make the lint at least accept crate-level lint attributes. return; }; - self.tcx.emit_node_span_lint(LARGE_ASSIGNMENTS, lint_root, span, LargeAssignmentsLint { + self.tcx.emit_node_span_lint( + LARGE_ASSIGNMENTS, + lint_root, span, - size: too_large_size.bytes(), - limit: limit as u64, - }); + LargeAssignmentsLint { span, size: too_large_size.bytes(), limit: limit as u64 }, + ); self.move_size_spans.push(span); } } diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index e7d7cd25c85..d826d03918e 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -268,12 +268,8 @@ where } let size_estimate = mono_item.size_estimate(cx.tcx); - cgu.items_mut().insert(mono_item, MonoItemData { - inlined: false, - linkage, - visibility, - size_estimate, - }); + cgu.items_mut() + .insert(mono_item, MonoItemData { inlined: false, linkage, visibility, size_estimate }); // Get all inlined items that are reachable from `mono_item` without // going via another root item. This includes drop-glue, functions from diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs index 3c5d9b95e77..082c356cc5f 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs @@ -514,10 +514,11 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_async_callable( sig: ty::CoroutineClosureSignature, ) -> I::Ty { let upvars_projection_def_id = cx.require_lang_item(TraitSolverLangItem::AsyncFnKindUpvars); - let tupled_upvars_ty = Ty::new_projection(cx, upvars_projection_def_id, [ - I::GenericArg::from(args.kind_ty()), - Ty::from_closure_kind(cx, goal_kind).into(), - goal_region.into(), - sig.tupled_inputs_ty.into(), - args.tupled_upvars_ty().into(), - args.coroutine_captures_by_ref_ty().into(), - ]); + let tupled_upvars_ty = Ty::new_projection( + cx, + upvars_projection_def_id, + [ + I::GenericArg::from(args.kind_ty()), + Ty::from_closure_kind(cx, goal_kind).into(), + goal_region.into(), + sig.tupled_inputs_ty.into(), + args.tupled_upvars_ty().into(), + args.coroutine_captures_by_ref_ty().into(), + ], + ); sig.to_coroutine( cx, args.parent_args(), diff --git a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs index 7669a305d58..fb53e778e60 100644 --- a/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/effect_goals.rs @@ -248,10 +248,11 @@ where let pred = inputs_and_output .map_bound(|(inputs, _)| { - ty::TraitRef::new(cx, goal.predicate.def_id(), [ - goal.predicate.self_ty(), - Ty::new_tup(cx, inputs.as_slice()), - ]) + ty::TraitRef::new( + cx, + goal.predicate.def_id(), + [goal.predicate.self_ty(), Ty::new_tup(cx, inputs.as_slice())], + ) }) .to_host_effect_clause(cx, goal.predicate.constness); diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs index 0bfd72c6848..2491f09a0e2 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs @@ -60,13 +60,16 @@ where (goal, opaque_types).fold_with(&mut EagerResolver::new(self.delegate)); let mut orig_values = Default::default(); - let canonical = - Canonicalizer::canonicalize_input(self.delegate, &mut orig_values, QueryInput { + let canonical = Canonicalizer::canonicalize_input( + self.delegate, + &mut orig_values, + QueryInput { goal, predefined_opaques_in_body: self .cx() .mk_predefined_opaques_in_body(PredefinedOpaquesData { opaque_types }), - }); + }, + ); let query_input = ty::CanonicalQueryInput { canonical, typing_mode: self.typing_mode() }; (orig_values, query_input) } diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index 48a05488148..b0a34b9ce75 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -548,10 +548,10 @@ where // Replace the goal with an unconstrained infer var, so the // RHS does not affect projection candidate assembly. let unconstrained_rhs = self.next_term_infer_of_kind(goal.predicate.term); - let unconstrained_goal = goal.with(cx, ty::NormalizesTo { - alias: goal.predicate.alias, - term: unconstrained_rhs, - }); + let unconstrained_goal = goal.with( + cx, + ty::NormalizesTo { alias: goal.predicate.alias, term: unconstrained_rhs }, + ); let (NestedNormalizationGoals(nested_goals), _, certainty) = self.evaluate_goal_raw( GoalEvaluationKind::Nested, diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs index 76cbe5758b2..c8ea0b119ff 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs @@ -398,10 +398,11 @@ where let pred = tupled_inputs_and_output .map_bound(|(inputs, output)| ty::ProjectionPredicate { - projection_term: ty::AliasTerm::new(cx, goal.predicate.def_id(), [ - goal.predicate.self_ty(), - inputs, - ]), + projection_term: ty::AliasTerm::new( + cx, + goal.predicate.def_id(), + [goal.predicate.self_ty(), inputs], + ), term: output.into(), }) .upcast(cx); @@ -454,21 +455,26 @@ where .is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CallOnceFuture) { ( - ty::AliasTerm::new(cx, goal.predicate.def_id(), [ - goal.predicate.self_ty(), - tupled_inputs_ty, - ]), + ty::AliasTerm::new( + cx, + goal.predicate.def_id(), + [goal.predicate.self_ty(), tupled_inputs_ty], + ), output_coroutine_ty.into(), ) } else if cx .is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CallRefFuture) { ( - ty::AliasTerm::new(cx, goal.predicate.def_id(), [ - I::GenericArg::from(goal.predicate.self_ty()), - tupled_inputs_ty.into(), - env_region.into(), - ]), + ty::AliasTerm::new( + cx, + goal.predicate.def_id(), + [ + I::GenericArg::from(goal.predicate.self_ty()), + tupled_inputs_ty.into(), + env_region.into(), + ], + ), output_coroutine_ty.into(), ) } else if cx.is_lang_item( @@ -476,10 +482,14 @@ where TraitSolverLangItem::AsyncFnOnceOutput, ) { ( - ty::AliasTerm::new(cx, goal.predicate.def_id(), [ - I::GenericArg::from(goal.predicate.self_ty()), - tupled_inputs_ty.into(), - ]), + ty::AliasTerm::new( + cx, + goal.predicate.def_id(), + [ + I::GenericArg::from(goal.predicate.self_ty()), + tupled_inputs_ty.into(), + ], + ), coroutine_return_ty.into(), ) } else { @@ -603,10 +613,11 @@ where // and opaque types: If the `self_ty` is `Sized`, then the metadata is `()`. // FIXME(ptr_metadata): This impl overlaps with the other impls and shouldn't // exist. Instead, `Pointee` should be a supertrait of `Sized`. - let sized_predicate = - ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Sized), [ - I::GenericArg::from(goal.predicate.self_ty()), - ]); + let sized_predicate = ty::TraitRef::new( + cx, + cx.require_lang_item(TraitSolverLangItem::Sized), + [I::GenericArg::from(goal.predicate.self_ty())], + ); // FIXME(-Znext-solver=coinductive): Should this be `GoalSource::ImplWhereBound`? ecx.add_goal(GoalSource::Misc, goal.with(cx, sized_predicate)); Ty::new_unit(cx) @@ -782,10 +793,11 @@ where CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, ty::ProjectionPredicate { - projection_term: ty::AliasTerm::new(ecx.cx(), goal.predicate.def_id(), [ - self_ty, - coroutine.resume_ty(), - ]), + projection_term: ty::AliasTerm::new( + ecx.cx(), + goal.predicate.def_id(), + [self_ty, coroutine.resume_ty()], + ), term, } .upcast(cx), diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index 513fc9355c8..46fae5c6fa4 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -342,18 +342,21 @@ where // (FIXME: technically we only need to check this if the type is a fn ptr...) let output_is_sized_pred = tupled_inputs_and_output_and_coroutine.map_bound( |AsyncCallableRelevantTypes { output_coroutine_ty, .. }| { - ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Sized), [ - output_coroutine_ty, - ]) + ty::TraitRef::new( + cx, + cx.require_lang_item(TraitSolverLangItem::Sized), + [output_coroutine_ty], + ) }, ); let pred = tupled_inputs_and_output_and_coroutine .map_bound(|AsyncCallableRelevantTypes { tupled_inputs_ty, .. }| { - ty::TraitRef::new(cx, goal.predicate.def_id(), [ - goal.predicate.self_ty(), - tupled_inputs_ty, - ]) + ty::TraitRef::new( + cx, + goal.predicate.def_id(), + [goal.predicate.self_ty(), tupled_inputs_ty], + ) }) .upcast(cx); Self::probe_and_consider_implied_clause( @@ -975,9 +978,11 @@ where GoalSource::ImplWhereBound, goal.with( cx, - ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Unsize), [ - a_tail_ty, b_tail_ty, - ]), + ty::TraitRef::new( + cx, + cx.require_lang_item(TraitSolverLangItem::Unsize), + [a_tail_ty, b_tail_ty], + ), ), ); self.probe_builtin_trait_candidate(BuiltinImplSource::Misc) @@ -1015,9 +1020,11 @@ where GoalSource::ImplWhereBound, goal.with( cx, - ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Unsize), [ - a_last_ty, b_last_ty, - ]), + ty::TraitRef::new( + cx, + cx.require_lang_item(TraitSolverLangItem::Unsize), + [a_last_ty, b_last_ty], + ), ), ); self.probe_builtin_trait_candidate(BuiltinImplSource::TupleUnsizing) diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index 2373ab67d42..8f0e29c2769 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -1121,23 +1121,29 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for ExpectedIdentifier { let token_descr = TokenDescription::from_token(&self.token); let mut add_token = true; - let mut diag = Diag::new(dcx, level, match token_descr { - Some(TokenDescription::ReservedIdentifier) => { - fluent::parse_expected_identifier_found_reserved_identifier_str - } - Some(TokenDescription::Keyword) => fluent::parse_expected_identifier_found_keyword_str, - Some(TokenDescription::ReservedKeyword) => { - fluent::parse_expected_identifier_found_reserved_keyword_str - } - Some(TokenDescription::DocComment) => { - fluent::parse_expected_identifier_found_doc_comment_str - } - Some(TokenDescription::MetaVar(_)) => { - add_token = false; - fluent::parse_expected_identifier_found_metavar_str - } - None => fluent::parse_expected_identifier_found_str, - }); + let mut diag = Diag::new( + dcx, + level, + match token_descr { + Some(TokenDescription::ReservedIdentifier) => { + fluent::parse_expected_identifier_found_reserved_identifier_str + } + Some(TokenDescription::Keyword) => { + fluent::parse_expected_identifier_found_keyword_str + } + Some(TokenDescription::ReservedKeyword) => { + fluent::parse_expected_identifier_found_reserved_keyword_str + } + Some(TokenDescription::DocComment) => { + fluent::parse_expected_identifier_found_doc_comment_str + } + Some(TokenDescription::MetaVar(_)) => { + add_token = false; + fluent::parse_expected_identifier_found_metavar_str + } + None => fluent::parse_expected_identifier_found_str, + }, + ); diag.span(self.span); if add_token { diag.arg("token", self.token); @@ -1182,21 +1188,27 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for ExpectedSemi { let token_descr = TokenDescription::from_token(&self.token); let mut add_token = true; - let mut diag = Diag::new(dcx, level, match token_descr { - Some(TokenDescription::ReservedIdentifier) => { - fluent::parse_expected_semi_found_reserved_identifier_str - } - Some(TokenDescription::Keyword) => fluent::parse_expected_semi_found_keyword_str, - Some(TokenDescription::ReservedKeyword) => { - fluent::parse_expected_semi_found_reserved_keyword_str - } - Some(TokenDescription::DocComment) => fluent::parse_expected_semi_found_doc_comment_str, - Some(TokenDescription::MetaVar(_)) => { - add_token = false; - fluent::parse_expected_semi_found_metavar_str - } - None => fluent::parse_expected_semi_found_str, - }); + let mut diag = Diag::new( + dcx, + level, + match token_descr { + Some(TokenDescription::ReservedIdentifier) => { + fluent::parse_expected_semi_found_reserved_identifier_str + } + Some(TokenDescription::Keyword) => fluent::parse_expected_semi_found_keyword_str, + Some(TokenDescription::ReservedKeyword) => { + fluent::parse_expected_semi_found_reserved_keyword_str + } + Some(TokenDescription::DocComment) => { + fluent::parse_expected_semi_found_doc_comment_str + } + Some(TokenDescription::MetaVar(_)) => { + add_token = false; + fluent::parse_expected_semi_found_metavar_str + } + None => fluent::parse_expected_semi_found_str, + }, + ); diag.span(self.span); if add_token { diag.arg("token", self.token); diff --git a/compiler/rustc_parse/src/parser/attr_wrapper.rs b/compiler/rustc_parse/src/parser/attr_wrapper.rs index 434f71beac2..cff998fa137 100644 --- a/compiler/rustc_parse/src/parser/attr_wrapper.rs +++ b/compiler/rustc_parse/src/parser/attr_wrapper.rs @@ -502,10 +502,10 @@ fn make_attr_token_stream( for flat_token in iter { match flat_token { FlatToken::Token((Token { kind: TokenKind::OpenDelim(delim), span }, spacing)) => { - stack_rest.push(mem::replace(&mut stack_top, FrameData { - open_delim_sp: Some((delim, span, spacing)), - inner: vec![], - })); + stack_rest.push(mem::replace( + &mut stack_top, + FrameData { open_delim_sp: Some((delim, span, spacing)), inner: vec![] }, + )); } FlatToken::Token((Token { kind: TokenKind::CloseDelim(delim), span }, spacing)) => { let frame_data = mem::replace(&mut stack_top, stack_rest.pop().unwrap()); diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 47bf80a0783..72aebb5d121 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -684,12 +684,15 @@ impl<'a> Parser<'a> { let span = self.token.span.with_lo(pos).with_hi(pos); err.span_suggestion_verbose( span, - format!("add a space before {} to write a regular comment", match (kind, style) { - (token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`", - (token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`", - (token::CommentKind::Line, ast::AttrStyle::Outer) => "the last `/`", - (token::CommentKind::Block, ast::AttrStyle::Outer) => "the last `*`", - },), + format!( + "add a space before {} to write a regular comment", + match (kind, style) { + (token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`", + (token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`", + (token::CommentKind::Line, ast::AttrStyle::Outer) => "the last `/`", + (token::CommentKind::Block, ast::AttrStyle::Outer) => "the last `*`", + }, + ), " ".to_string(), Applicability::MachineApplicable, ); @@ -1894,13 +1897,14 @@ impl<'a> Parser<'a> { (token::Eof, None) => (self.prev_token.span, self.token.span), _ => (self.prev_token.span.shrink_to_hi(), self.token.span), }; - let msg = format!("expected `{}`, found {}", token_str, match ( - &self.token.kind, - self.subparser_name - ) { - (token::Eof, Some(origin)) => format!("end of {origin}"), - _ => this_token_str, - },); + let msg = format!( + "expected `{}`, found {}", + token_str, + match (&self.token.kind, self.subparser_name) { + (token::Eof, Some(origin)) => format!("end of {origin}"), + _ => this_token_str, + }, + ); let mut err = self.dcx().struct_span_err(sp, msg); let label_exp = format!("expected `{token_str}`"); let sm = self.psess.source_map(); @@ -2826,25 +2830,27 @@ impl<'a> Parser<'a> { PatKind::Ident(BindingMode::NONE, ident, None) => { match &first_pat.kind { PatKind::Ident(_, old_ident, _) => { - let path = PatKind::Path(None, Path { - span: new_span, - segments: thin_vec![ - PathSegment::from_ident(*old_ident), - PathSegment::from_ident(*ident), - ], - tokens: None, - }); + let path = PatKind::Path( + None, + Path { + span: new_span, + segments: thin_vec![ + PathSegment::from_ident(*old_ident), + PathSegment::from_ident(*ident), + ], + tokens: None, + }, + ); first_pat = self.mk_pat(new_span, path); show_sugg = true; } PatKind::Path(old_qself, old_path) => { let mut segments = old_path.segments.clone(); segments.push(PathSegment::from_ident(*ident)); - let path = PatKind::Path(old_qself.clone(), Path { - span: new_span, - segments, - tokens: None, - }); + let path = PatKind::Path( + old_qself.clone(), + Path { span: new_span, segments, tokens: None }, + ); first_pat = self.mk_pat(new_span, path); show_sugg = true; } diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index ffd46f20767..e0e6c2177da 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -807,17 +807,20 @@ impl<'a> Parser<'a> { // Check if an illegal postfix operator has been added after the cast. // If the resulting expression is not a cast, it is an illegal postfix operator. if !matches!(with_postfix.kind, ExprKind::Cast(_, _)) { - let msg = format!("cast cannot be followed by {}", match with_postfix.kind { - ExprKind::Index(..) => "indexing", - ExprKind::Try(_) => "`?`", - ExprKind::Field(_, _) => "a field access", - ExprKind::MethodCall(_) => "a method call", - ExprKind::Call(_, _) => "a function call", - ExprKind::Await(_, _) => "`.await`", - ExprKind::Match(_, _, MatchKind::Postfix) => "a postfix match", - ExprKind::Err(_) => return Ok(with_postfix), - _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"), - }); + let msg = format!( + "cast cannot be followed by {}", + match with_postfix.kind { + ExprKind::Index(..) => "indexing", + ExprKind::Try(_) => "`?`", + ExprKind::Field(_, _) => "a field access", + ExprKind::MethodCall(_) => "a method call", + ExprKind::Call(_, _) => "a function call", + ExprKind::Await(_, _) => "`.await`", + ExprKind::Match(_, _, MatchKind::Postfix) => "a postfix match", + ExprKind::Err(_) => return Ok(with_postfix), + _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"), + } + ); let mut err = self.dcx().struct_span_err(span, msg); let suggest_parens = |err: &mut Diag<'_>| { @@ -2862,13 +2865,10 @@ impl<'a> Parser<'a> { .emit_err(errors::MissingExpressionInForLoop { span: expr.span.shrink_to_lo() }); let err_expr = self.mk_expr(expr.span, ExprKind::Err(guar)); let block = self.mk_block(thin_vec![], BlockCheckMode::Default, self.prev_token.span); - return Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::ForLoop { - pat, - iter: err_expr, - body: block, - label: opt_label, - kind, - })); + return Ok(self.mk_expr( + lo.to(self.prev_token.span), + ExprKind::ForLoop { pat, iter: err_expr, body: block, label: opt_label, kind }, + )); } let (attrs, loop_block) = self.parse_inner_attrs_and_block()?; diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index dbdc31f06a2..637ed2774a2 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -1954,10 +1954,10 @@ impl<'a> Parser<'a> { // Try to recover extra trailing angle brackets if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind { if let Some(last_segment) = segments.last() { - let guar = self.check_trailing_angle_brackets(last_segment, &[ - exp!(Comma), - exp!(CloseBrace), - ]); + let guar = self.check_trailing_angle_brackets( + last_segment, + &[exp!(Comma), exp!(CloseBrace)], + ); if let Some(_guar) = guar { // Handle a case like `Vec>,` where we can continue parsing fields // after the comma diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 39737b9e137..576711e6677 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -106,11 +106,10 @@ impl<'a> Parser<'a> { self.parse_path_segments(&mut path.segments, style, None)?; } - Ok((qself, Path { - segments: path.segments, - span: lo.to(self.prev_token.span), - tokens: None, - })) + Ok(( + qself, + Path { segments: path.segments, span: lo.to(self.prev_token.span), tokens: None }, + )) } /// Recover from an invalid single colon, when the user likely meant a qualified path. @@ -485,13 +484,16 @@ impl<'a> Parser<'a> { error.span_suggestion_verbose( prev_token_before_parsing.span, - format!("consider removing the `::` here to {}", match style { - PathStyle::Expr => "call the expression", - PathStyle::Pat => "turn this into a tuple struct pattern", - _ => { - return; + format!( + "consider removing the `::` here to {}", + match style { + PathStyle::Expr => "call the expression", + PathStyle::Pat => "turn this into a tuple struct pattern", + _ => { + return; + } } - }), + ), "", Applicability::MaybeIncorrect, ); diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 1ddb5fc0a11..a2699b077fc 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -417,14 +417,20 @@ impl<'a> Parser<'a> { fn check_let_else_init_trailing_brace(&self, init: &ast::Expr) { if let Some(trailing) = classify::expr_trailing_brace(init) { let (span, sugg) = match trailing { - TrailingBrace::MacCall(mac) => (mac.span(), errors::WrapInParentheses::MacroArgs { - left: mac.args.dspan.open, - right: mac.args.dspan.close, - }), - TrailingBrace::Expr(expr) => (expr.span, errors::WrapInParentheses::Expression { - left: expr.span.shrink_to_lo(), - right: expr.span.shrink_to_hi(), - }), + TrailingBrace::MacCall(mac) => ( + mac.span(), + errors::WrapInParentheses::MacroArgs { + left: mac.args.dspan.open, + right: mac.args.dspan.close, + }, + ), + TrailingBrace::Expr(expr) => ( + expr.span, + errors::WrapInParentheses::Expression { + left: expr.span.shrink_to_lo(), + right: expr.span.shrink_to_hi(), + }, + ), }; self.dcx().emit_err(errors::InvalidCurlyInLetElse { span: span.with_lo(span.hi() - BytePos(1)), diff --git a/compiler/rustc_parse_format/src/lib.rs b/compiler/rustc_parse_format/src/lib.rs index d021ea107ed..3b985621b57 100644 --- a/compiler/rustc_parse_format/src/lib.rs +++ b/compiler/rustc_parse_format/src/lib.rs @@ -863,28 +863,34 @@ impl<'a> Parser<'a> { if let (Some(pos), Some(_)) = (self.consume_pos('?'), self.consume_pos(':')) { let word = self.word(); let pos = self.to_span_index(pos); - self.errors.insert(0, ParseError { - description: "expected format parameter to occur after `:`".to_owned(), - note: Some(format!("`?` comes after `:`, try `{}:{}` instead", word, "?")), - label: "expected `?` to occur after `:`".to_owned(), - span: pos.to(pos), - secondary_label: None, - suggestion: Suggestion::None, - }); + self.errors.insert( + 0, + ParseError { + description: "expected format parameter to occur after `:`".to_owned(), + note: Some(format!("`?` comes after `:`, try `{}:{}` instead", word, "?")), + label: "expected `?` to occur after `:`".to_owned(), + span: pos.to(pos), + secondary_label: None, + suggestion: Suggestion::None, + }, + ); } } fn suggest_format_align(&mut self, alignment: char) { if let Some(pos) = self.consume_pos(alignment) { let pos = self.to_span_index(pos); - self.errors.insert(0, ParseError { - description: "expected format parameter to occur after `:`".to_owned(), - note: None, - label: format!("expected `{}` to occur after `:`", alignment), - span: pos.to(pos), - secondary_label: None, - suggestion: Suggestion::None, - }); + self.errors.insert( + 0, + ParseError { + description: "expected format parameter to occur after `:`".to_owned(), + note: None, + label: format!("expected `{}` to occur after `:`", alignment), + span: pos.to(pos), + secondary_label: None, + suggestion: Suggestion::None, + }, + ); } } @@ -901,24 +907,36 @@ impl<'a> Parser<'a> { if let ArgumentNamed(_) = arg.position { match field.position { ArgumentNamed(_) => { - self.errors.insert(0, ParseError { - description: "field access isn't supported".to_string(), - note: None, - label: "not supported".to_string(), - span: InnerSpan::new(arg.position_span.start, field.position_span.end), - secondary_label: None, - suggestion: Suggestion::UsePositional, - }); + self.errors.insert( + 0, + ParseError { + description: "field access isn't supported".to_string(), + note: None, + label: "not supported".to_string(), + span: InnerSpan::new( + arg.position_span.start, + field.position_span.end, + ), + secondary_label: None, + suggestion: Suggestion::UsePositional, + }, + ); } ArgumentIs(_) => { - self.errors.insert(0, ParseError { - description: "tuple index access isn't supported".to_string(), - note: None, - label: "not supported".to_string(), - span: InnerSpan::new(arg.position_span.start, field.position_span.end), - secondary_label: None, - suggestion: Suggestion::UsePositional, - }); + self.errors.insert( + 0, + ParseError { + description: "tuple index access isn't supported".to_string(), + note: None, + label: "not supported".to_string(), + span: InnerSpan::new( + arg.position_span.start, + field.position_span.end, + ), + secondary_label: None, + suggestion: Suggestion::UsePositional, + }, + ); } _ => {} }; @@ -940,14 +958,17 @@ impl<'a> Parser<'a> { let span = self.span(pos - 1, pos + 1); let pos = self.to_span_index(pos); - self.errors.insert(0, ParseError { - description: format!("expected `}}`, found `{c}`"), - note: None, - label: "expected `'}'`".into(), - span: pos.to(pos), - secondary_label: None, - suggestion: Suggestion::ReorderFormatParameter(span, format!("{replacement}")), - }) + self.errors.insert( + 0, + ParseError { + description: format!("expected `}}`, found `{c}`"), + note: None, + label: "expected `'}'`".into(), + span: pos.to(pos), + secondary_label: None, + suggestion: Suggestion::ReorderFormatParameter(span, format!("{replacement}")), + }, + ) } } diff --git a/compiler/rustc_parse_format/src/tests.rs b/compiler/rustc_parse_format/src/tests.rs index fbb217b16fc..cc8a0069c4e 100644 --- a/compiler/rustc_parse_format/src/tests.rs +++ b/compiler/rustc_parse_format/src/tests.rs @@ -80,302 +80,55 @@ fn invalid_precision() { #[test] fn format_nothing() { - same("{}", &[NextArgument(Box::new(Argument { - position: ArgumentImplicitlyIs(0), - position_span: InnerSpan { start: 2, end: 2 }, - format: fmtdflt(), - }))]); + same( + "{}", + &[NextArgument(Box::new(Argument { + position: ArgumentImplicitlyIs(0), + position_span: InnerSpan { start: 2, end: 2 }, + format: fmtdflt(), + }))], + ); } #[test] fn format_position() { - same("{3}", &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: fmtdflt(), - }))]); + same( + "{3}", + &[NextArgument(Box::new(Argument { + position: ArgumentIs(3), + position_span: InnerSpan { start: 2, end: 3 }, + format: fmtdflt(), + }))], + ); } #[test] fn format_position_nothing_else() { - same("{3:}", &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: fmtdflt(), - }))]); + same( + "{3:}", + &[NextArgument(Box::new(Argument { + position: ArgumentIs(3), + position_span: InnerSpan { start: 2, end: 3 }, + format: fmtdflt(), + }))], + ); } #[test] fn format_named() { - same("{name}", &[NextArgument(Box::new(Argument { - position: ArgumentNamed("name"), - position_span: InnerSpan { start: 2, end: 6 }, - format: fmtdflt(), - }))]) + same( + "{name}", + &[NextArgument(Box::new(Argument { + position: ArgumentNamed("name"), + position_span: InnerSpan { start: 2, end: 6 }, + format: fmtdflt(), + }))], + ) } #[test] fn format_type() { - same("{3:x}", &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: FormatSpec { - fill: None, - fill_span: None, - align: AlignUnknown, - sign: None, - alternate: false, - zero_pad: false, - debug_hex: None, - precision: CountImplied, - width: CountImplied, - precision_span: None, - width_span: None, - ty: "x", - ty_span: None, - }, - }))]); -} -#[test] -fn format_align_fill() { - same("{3:>}", &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: FormatSpec { - fill: None, - fill_span: None, - align: AlignRight, - sign: None, - alternate: false, - zero_pad: false, - debug_hex: None, - precision: CountImplied, - width: CountImplied, - precision_span: None, - width_span: None, - ty: "", - ty_span: None, - }, - }))]); - same("{3:0<}", &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: FormatSpec { - fill: Some('0'), - fill_span: Some(InnerSpan::new(4, 5)), - align: AlignLeft, - sign: None, - alternate: false, - zero_pad: false, - debug_hex: None, - precision: CountImplied, - width: CountImplied, - precision_span: None, - width_span: None, - ty: "", - ty_span: None, - }, - }))]); - same("{3:*}", + &[NextArgument(Box::new(Argument { + position: ArgumentIs(3), + position_span: InnerSpan { start: 2, end: 3 }, + format: FormatSpec { + fill: None, + fill_span: None, + align: AlignRight, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, + precision: CountImplied, + width: CountImplied, + precision_span: None, + width_span: None, + ty: "", + ty_span: None, + }, + }))], + ); + same( + "{3:0<}", + &[NextArgument(Box::new(Argument { + position: ArgumentIs(3), + position_span: InnerSpan { start: 2, end: 3 }, + format: FormatSpec { + fill: Some('0'), + fill_span: Some(InnerSpan::new(4, 5)), + align: AlignLeft, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, + precision: CountImplied, + width: CountImplied, + precision_span: None, + width_span: None, + ty: "", + ty_span: None, + }, + }))], + ); + same( + "{3:* CheckAttrVisitor<'tcx> { } fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) { - self.tcx - .emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::IgnoredAttr { sym }); + self.tcx.emit_node_span_lint( + UNUSED_ATTRIBUTES, + hir_id, + attr.span, + errors::IgnoredAttr { sym }, + ); } /// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl. @@ -1506,10 +1510,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> { _ => { // FIXME: #[cold] was previously allowed on non-functions and some crates used // this, so only emit a warning. - self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::Cold { - span, - on_crate: hir_id == CRATE_HIR_ID, - }); + self.tcx.emit_node_span_lint( + UNUSED_ATTRIBUTES, + hir_id, + attr.span, + errors::Cold { span, on_crate: hir_id == CRATE_HIR_ID }, + ); } } } @@ -1524,9 +1530,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> { return; } - self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::Link { - span: (target != Target::ForeignMod).then_some(span), - }); + self.tcx.emit_node_span_lint( + UNUSED_ATTRIBUTES, + hir_id, + attr.span, + errors::Link { span: (target != Target::ForeignMod).then_some(span) }, + ); } /// Checks if `#[link_name]` is applied to an item other than a foreign function or static. @@ -2393,10 +2402,12 @@ impl<'tcx> CheckAttrVisitor<'tcx> { return; }; - self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::Unused { - attr_span: attr.span, - note, - }); + self.tcx.emit_node_span_lint( + UNUSED_ATTRIBUTES, + hir_id, + attr.span, + errors::Unused { attr_span: attr.span, note }, + ); } /// A best effort attempt to create an error for a mismatching proc macro signature. diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 0aa50ad19ff..9bcdd238547 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -1394,11 +1394,15 @@ pub(crate) struct DuplicateLangItem { impl Diagnostic<'_, G> for DuplicateLangItem { #[track_caller] fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { - let mut diag = Diag::new(dcx, level, match self.duplicate { - Duplicate::Plain => fluent::passes_duplicate_lang_item, - Duplicate::Crate => fluent::passes_duplicate_lang_item_crate, - Duplicate::CrateDepends => fluent::passes_duplicate_lang_item_crate_depends, - }); + let mut diag = Diag::new( + dcx, + level, + match self.duplicate { + Duplicate::Plain => fluent::passes_duplicate_lang_item, + Duplicate::Crate => fluent::passes_duplicate_lang_item_crate, + Duplicate::CrateDepends => fluent::passes_duplicate_lang_item_crate_depends, + }, + ); diag.code(E0152); diag.arg("lang_item_name", self.lang_item_name); diag.arg("crate_name", self.crate_name); diff --git a/compiler/rustc_passes/src/input_stats.rs b/compiler/rustc_passes/src/input_stats.rs index 6d9c70177a4..f7cae89852e 100644 --- a/compiler/rustc_passes/src/input_stats.rs +++ b/compiler/rustc_passes/src/input_stats.rs @@ -230,24 +230,27 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_item(&mut self, i: &'v hir::Item<'v>) { - record_variants!((self, i, i.kind, Some(i.hir_id()), hir, Item, ItemKind), [ - ExternCrate, - Use, - Static, - Const, - Fn, - Macro, - Mod, - ForeignMod, - GlobalAsm, - TyAlias, - Enum, - Struct, - Union, - Trait, - TraitAlias, - Impl - ]); + record_variants!( + (self, i, i.kind, Some(i.hir_id()), hir, Item, ItemKind), + [ + ExternCrate, + Use, + Static, + Const, + Fn, + Macro, + Mod, + ForeignMod, + GlobalAsm, + TyAlias, + Enum, + Struct, + Union, + Trait, + TraitAlias, + Impl + ] + ); hir_visit::walk_item(self, i) } @@ -262,9 +265,10 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_foreign_item(&mut self, i: &'v hir::ForeignItem<'v>) { - record_variants!((self, i, i.kind, Some(i.hir_id()), hir, ForeignItem, ForeignItemKind), [ - Fn, Static, Type - ]); + record_variants!( + (self, i, i.kind, Some(i.hir_id()), hir, ForeignItem, ForeignItemKind), + [Fn, Static, Type] + ); hir_visit::walk_foreign_item(self, i) } @@ -279,9 +283,10 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) { - record_variants!((self, s, s.kind, Some(s.hir_id), hir, Stmt, StmtKind), [ - Let, Item, Expr, Semi - ]); + record_variants!( + (self, s, s.kind, Some(s.hir_id), hir, Stmt, StmtKind), + [Let, Item, Expr, Semi] + ); hir_visit::walk_stmt(self, s) } @@ -291,23 +296,26 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_pat(&mut self, p: &'v hir::Pat<'v>) { - record_variants!((self, p, p.kind, Some(p.hir_id), hir, Pat, PatKind), [ - Wild, - Binding, - Struct, - TupleStruct, - Or, - Never, - Tuple, - Box, - Deref, - Ref, - Expr, - Guard, - Range, - Slice, - Err - ]); + record_variants!( + (self, p, p.kind, Some(p.hir_id), hir, Pat, PatKind), + [ + Wild, + Binding, + Struct, + TupleStruct, + Or, + Never, + Tuple, + Box, + Deref, + Ref, + Expr, + Guard, + Range, + Slice, + Err + ] + ); hir_visit::walk_pat(self, p) } @@ -317,42 +325,45 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_expr(&mut self, e: &'v hir::Expr<'v>) { - record_variants!((self, e, e.kind, Some(e.hir_id), hir, Expr, ExprKind), [ - ConstBlock, - Array, - Call, - MethodCall, - Tup, - Binary, - Unary, - Lit, - Cast, - Type, - DropTemps, - Let, - If, - Loop, - Match, - Closure, - Block, - Assign, - AssignOp, - Field, - Index, - Path, - AddrOf, - Break, - Continue, - Ret, - Become, - InlineAsm, - OffsetOf, - Struct, - Repeat, - Yield, - UnsafeBinderCast, - Err - ]); + record_variants!( + (self, e, e.kind, Some(e.hir_id), hir, Expr, ExprKind), + [ + ConstBlock, + Array, + Call, + MethodCall, + Tup, + Binary, + Unary, + Lit, + Cast, + Type, + DropTemps, + Let, + If, + Loop, + Match, + Closure, + Block, + Assign, + AssignOp, + Field, + Index, + Path, + AddrOf, + Break, + Continue, + Ret, + Become, + InlineAsm, + OffsetOf, + Struct, + Repeat, + Yield, + UnsafeBinderCast, + Err + ] + ); hir_visit::walk_expr(self, e) } @@ -362,25 +373,28 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_ty(&mut self, t: &'v hir::Ty<'v, AmbigArg>) { - record_variants!((self, t, t.kind, Some(t.hir_id), hir, Ty, TyKind), [ - InferDelegation, - Slice, - Array, - Ptr, - Ref, - BareFn, - UnsafeBinder, - Never, - Tup, - Path, - OpaqueDef, - TraitAscription, - TraitObject, - Typeof, - Infer, - Pat, - Err - ]); + record_variants!( + (self, t, t.kind, Some(t.hir_id), hir, Ty, TyKind), + [ + InferDelegation, + Slice, + Array, + Ptr, + Ref, + BareFn, + UnsafeBinder, + Never, + Tup, + Path, + OpaqueDef, + TraitAscription, + TraitObject, + Typeof, + Infer, + Pat, + Err + ] + ); hir_visit::walk_ty(self, t) } @@ -421,9 +435,10 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_trait_item(&mut self, ti: &'v hir::TraitItem<'v>) { - record_variants!((self, ti, ti.kind, Some(ti.hir_id()), hir, TraitItem, TraitItemKind), [ - Const, Fn, Type - ]); + record_variants!( + (self, ti, ti.kind, Some(ti.hir_id()), hir, TraitItem, TraitItemKind), + [Const, Fn, Type] + ); hir_visit::walk_trait_item(self, ti) } @@ -433,9 +448,10 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_impl_item(&mut self, ii: &'v hir::ImplItem<'v>) { - record_variants!((self, ii, ii.kind, Some(ii.hir_id()), hir, ImplItem, ImplItemKind), [ - Const, Fn, Type - ]); + record_variants!( + (self, ii, ii.kind, Some(ii.hir_id()), hir, ImplItem, ImplItemKind), + [Const, Fn, Type] + ); hir_visit::walk_impl_item(self, ii) } @@ -450,9 +466,10 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_param_bound(&mut self, b: &'v hir::GenericBound<'v>) { - record_variants!((self, b, b, None, hir, GenericBound, GenericBound), [ - Trait, Outlives, Use - ]); + record_variants!( + (self, b, b, None, hir, GenericBound, GenericBound), + [Trait, Outlives, Use] + ); hir_visit::walk_param_bound(self, b) } @@ -467,9 +484,10 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_generic_arg(&mut self, ga: &'v hir::GenericArg<'v>) { - record_variants!((self, ga, ga, Some(ga.hir_id()), hir, GenericArg, GenericArg), [ - Lifetime, Type, Const, Infer - ]); + record_variants!( + (self, ga, ga, Some(ga.hir_id()), hir, GenericArg, GenericArg), + [Lifetime, Type, Const, Infer] + ); match ga { hir::GenericArg::Lifetime(lt) => self.visit_lifetime(lt), hir::GenericArg::Type(ty) => self.visit_ty(ty), @@ -515,34 +533,38 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { fn visit_foreign_item(&mut self, i: &'v ast::ForeignItem) { - record_variants!((self, i, i.kind, None, ast, ForeignItem, ForeignItemKind), [ - Static, Fn, TyAlias, MacCall - ]); + record_variants!( + (self, i, i.kind, None, ast, ForeignItem, ForeignItemKind), + [Static, Fn, TyAlias, MacCall] + ); ast_visit::walk_item(self, i) } fn visit_item(&mut self, i: &'v ast::Item) { - record_variants!((self, i, i.kind, None, ast, Item, ItemKind), [ - ExternCrate, - Use, - Static, - Const, - Fn, - Mod, - ForeignMod, - GlobalAsm, - TyAlias, - Enum, - Struct, - Union, - Trait, - TraitAlias, - Impl, - MacCall, - MacroDef, - Delegation, - DelegationMac - ]); + record_variants!( + (self, i, i.kind, None, ast, Item, ItemKind), + [ + ExternCrate, + Use, + Static, + Const, + Fn, + Mod, + ForeignMod, + GlobalAsm, + TyAlias, + Enum, + Struct, + Union, + Trait, + TraitAlias, + Impl, + MacCall, + MacroDef, + Delegation, + DelegationMac + ] + ); ast_visit::walk_item(self, i) } @@ -557,9 +579,10 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_stmt(&mut self, s: &'v ast::Stmt) { - record_variants!((self, s, s.kind, None, ast, Stmt, StmtKind), [ - Let, Item, Expr, Semi, Empty, MacCall - ]); + record_variants!( + (self, s, s.kind, None, ast, Stmt, StmtKind), + [Let, Item, Expr, Semi, Empty, MacCall] + ); ast_visit::walk_stmt(self, s) } @@ -574,27 +597,30 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_pat(&mut self, p: &'v ast::Pat) { - record_variants!((self, p, p.kind, None, ast, Pat, PatKind), [ - Wild, - Ident, - Struct, - TupleStruct, - Or, - Path, - Tuple, - Box, - Deref, - Ref, - Expr, - Range, - Slice, - Rest, - Never, - Guard, - Paren, - MacCall, - Err - ]); + record_variants!( + (self, p, p.kind, None, ast, Pat, PatKind), + [ + Wild, + Ident, + Struct, + TupleStruct, + Or, + Path, + Tuple, + Box, + Deref, + Ref, + Expr, + Range, + Slice, + Rest, + Never, + Guard, + Paren, + MacCall, + Err + ] + ); ast_visit::walk_pat(self, p) } @@ -614,29 +640,32 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_ty(&mut self, t: &'v ast::Ty) { - record_variants!((self, t, t.kind, None, ast, Ty, TyKind), [ - Slice, - Array, - Ptr, - Ref, - PinnedRef, - BareFn, - UnsafeBinder, - Never, - Tup, - Path, - Pat, - TraitObject, - ImplTrait, - Paren, - Typeof, - Infer, - ImplicitSelf, - MacCall, - CVarArgs, - Dummy, - Err - ]); + record_variants!( + (self, t, t.kind, None, ast, Ty, TyKind), + [ + Slice, + Array, + Ptr, + Ref, + PinnedRef, + BareFn, + UnsafeBinder, + Never, + Tup, + Path, + Pat, + TraitObject, + ImplTrait, + Paren, + Typeof, + Infer, + ImplicitSelf, + MacCall, + CVarArgs, + Dummy, + Err + ] + ); ast_visit::walk_ty(self, t) } @@ -647,11 +676,10 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_where_predicate(&mut self, p: &'v ast::WherePredicate) { - record_variants!((self, p, &p.kind, None, ast, WherePredicate, WherePredicateKind), [ - BoundPredicate, - RegionPredicate, - EqPredicate - ]); + record_variants!( + (self, p, &p.kind, None, ast, WherePredicate, WherePredicateKind), + [BoundPredicate, RegionPredicate, EqPredicate] + ); ast_visit::walk_where_predicate(self, p) } @@ -661,21 +689,18 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_assoc_item(&mut self, i: &'v ast::AssocItem, ctxt: ast_visit::AssocCtxt) { - record_variants!((self, i, i.kind, None, ast, AssocItem, AssocItemKind), [ - Const, - Fn, - Type, - MacCall, - Delegation, - DelegationMac - ]); + record_variants!( + (self, i, i.kind, None, ast, AssocItem, AssocItemKind), + [Const, Fn, Type, MacCall, Delegation, DelegationMac] + ); ast_visit::walk_assoc_item(self, i, ctxt); } fn visit_param_bound(&mut self, b: &'v ast::GenericBound, _ctxt: BoundKind) { - record_variants!((self, b, b, None, ast, GenericBound, GenericBound), [ - Trait, Outlives, Use - ]); + record_variants!( + (self, b, b, None, ast, GenericBound, GenericBound), + [Trait, Outlives, Use] + ); ast_visit::walk_param_bound(self, b) } @@ -708,18 +733,18 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { // common, so we implement `visit_generic_args` and tolerate the double // counting in the former case. fn visit_generic_args(&mut self, g: &'v ast::GenericArgs) { - record_variants!((self, g, g, None, ast, GenericArgs, GenericArgs), [ - AngleBracketed, - Parenthesized, - ParenthesizedElided - ]); + record_variants!( + (self, g, g, None, ast, GenericArgs, GenericArgs), + [AngleBracketed, Parenthesized, ParenthesizedElided] + ); ast_visit::walk_generic_args(self, g) } fn visit_attribute(&mut self, attr: &'v ast::Attribute) { - record_variants!((self, attr, attr.kind, None, ast, Attribute, AttrKind), [ - Normal, DocComment - ]); + record_variants!( + (self, attr, attr.kind, None, ast, Attribute, AttrKind), + [Normal, DocComment] + ); ast_visit::walk_attribute(self, attr) } diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index ca7064a36a1..c6781ecc566 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -567,10 +567,13 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { Some(rename) => source.ident.span.to(rename.span), None => source.ident.span, }; - self.r.report_error(span, ResolutionError::SelfImportsOnlyAllowedWithin { - root: parent.is_none(), - span_with_rename, - }); + self.r.report_error( + span, + ResolutionError::SelfImportsOnlyAllowedWithin { + root: parent.is_none(), + span_with_rename, + }, + ); // Error recovery: replace `use foo::self;` with `use foo;` if let Some(parent) = module_path.pop() { diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index db607dbb419..5eb8e420fa4 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -95,11 +95,14 @@ impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> { fn visit_macro_invoc(&mut self, id: NodeId) { let id = id.placeholder_to_expn_id(); - let old_parent = self.resolver.invocation_parents.insert(id, InvocationParent { - parent_def: self.parent_def, - impl_trait_context: self.impl_trait_context, - in_attr: self.in_attr, - }); + let old_parent = self.resolver.invocation_parents.insert( + id, + InvocationParent { + parent_def: self.parent_def, + impl_trait_context: self.impl_trait_context, + in_attr: self.in_attr, + }, + ); assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation"); } } diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 8dc752c2cb3..8d42b478647 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -990,14 +990,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { VisResolutionError::AncestorOnly(span) => { self.dcx().create_err(errs::AncestorOnly(span)) } - VisResolutionError::FailedToResolve(span, label, suggestion) => { - self.into_struct_error(span, ResolutionError::FailedToResolve { - segment: None, - label, - suggestion, - module: None, - }) - } + VisResolutionError::FailedToResolve(span, label, suggestion) => self.into_struct_error( + span, + ResolutionError::FailedToResolve { segment: None, label, suggestion, module: None }, + ), VisResolutionError::ExpectedFound(span, path_str, res) => { self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str }) } diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index a3d3e87ade0..499b9bca4d2 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -1181,21 +1181,25 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } Some(_) => None, }; - (rib_ident.span, AttemptToUseNonConstantValueInConstant { - ident: original_rib_ident_def, - suggestion: "const", - current: "let", - type_span, - }) + ( + rib_ident.span, + AttemptToUseNonConstantValueInConstant { + ident: original_rib_ident_def, + suggestion: "const", + current: "let", + type_span, + }, + ) } - Some((ident, kind)) => { - (span, AttemptToUseNonConstantValueInConstant { + Some((ident, kind)) => ( + span, + AttemptToUseNonConstantValueInConstant { ident, suggestion: "let", current: kind.as_str(), type_span: None, - }) - } + }, + ), }; self.report_error(span, resolution_error); } @@ -1203,10 +1207,13 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } RibKind::ConstParamTy => { if let Some(span) = finalize { - self.report_error(span, ParamInTyOfConstParam { - name: rib_ident.name, - param_kind: None, - }); + self.report_error( + span, + ParamInTyOfConstParam { + name: rib_ident.name, + param_kind: None, + }, + ); } return Res::Err; } @@ -1287,10 +1294,13 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } RibKind::ConstParamTy => { if let Some(span) = finalize { - self.report_error(span, ResolutionError::ParamInTyOfConstParam { - name: rib_ident.name, - param_kind: Some(errors::ParamKindInTyOfConstParam::Type), - }); + self.report_error( + span, + ResolutionError::ParamInTyOfConstParam { + name: rib_ident.name, + param_kind: Some(errors::ParamKindInTyOfConstParam::Type), + }, + ); } return Res::Err; } @@ -1353,10 +1363,13 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } RibKind::ConstParamTy => { if let Some(span) = finalize { - self.report_error(span, ResolutionError::ParamInTyOfConstParam { - name: rib_ident.name, - param_kind: Some(errors::ParamKindInTyOfConstParam::Const), - }); + self.report_error( + span, + ResolutionError::ParamInTyOfConstParam { + name: rib_ident.name, + param_kind: Some(errors::ParamKindInTyOfConstParam::Const), + }, + ); } return Res::Err; } diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index d555c938770..7bbff743ac9 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -914,12 +914,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } => { if no_ambiguity { assert!(import.imported_module.get().is_none()); - self.report_error(span, ResolutionError::FailedToResolve { - segment: Some(segment_name), - label, - suggestion, - module, - }); + self.report_error( + span, + ResolutionError::FailedToResolve { + segment: Some(segment_name), + label, + suggestion, + module, + }, + ); } return None; } diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index e37e7e98ee7..508bd831ccb 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -1823,9 +1823,11 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { && Some(true) == self.diag_metadata.in_non_gat_assoc_type && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind { - if def_id_matches_path(self.r.tcx, trait_id, &[ - "core", "iter", "traits", "iterator", "Iterator", - ]) { + if def_id_matches_path( + self.r.tcx, + trait_id, + &["core", "iter", "traits", "iterator", "Iterator"], + ) { self.r.dcx().emit_err(errors::LendingIteratorReportError { lifetime: lifetime.ident.span, ty: ty.span, @@ -3425,11 +3427,14 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { match seen_trait_items.entry(id_in_trait) { Entry::Occupied(entry) => { - self.report_error(span, ResolutionError::TraitImplDuplicate { - name: ident, - old_span: *entry.get(), - trait_item_span: binding.span, - }); + self.report_error( + span, + ResolutionError::TraitImplDuplicate { + name: ident, + old_span: *entry.get(), + trait_item_span: binding.span, + }, + ); return; } Entry::Vacant(entry) => { @@ -3460,13 +3465,16 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } }; let trait_path = path_names_to_string(path); - self.report_error(span, ResolutionError::TraitImplMismatch { - name: ident, - kind, - code, - trait_path, - trait_item_span: binding.span, - }); + self.report_error( + span, + ResolutionError::TraitImplMismatch { + name: ident, + kind, + code, + trait_path, + trait_item_span: binding.span, + }, + ); } fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) { @@ -3845,10 +3853,13 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { .patterns_with_skipped_bindings .entry(def_id) .or_default() - .push((pat.span, match rest { - ast::PatFieldsRest::Recovered(guar) => Err(*guar), - _ => Ok(()), - })); + .push(( + pat.span, + match rest { + ast::PatFieldsRest::Recovered(guar) => Err(*guar), + _ => Ok(()), + }, + )); } } ast::PatFieldsRest::None => {} @@ -4485,12 +4496,15 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { segment_name, error_implied_by_parse_error: _, } => { - return Err(respan(span, ResolutionError::FailedToResolve { - segment: Some(segment_name), - label, - suggestion, - module, - })); + return Err(respan( + span, + ResolutionError::FailedToResolve { + segment: Some(segment_name), + label, + suggestion, + module, + }, + )); } PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None), PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"), diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 57679d595da..a80b68d9773 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -1048,12 +1048,15 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { debug!("smart_resolve_path_fragment: E0424, source={:?}", source); err.code(E0424); - err.span_label(span, match source { - PathSource::Pat => { - "`self` value is a keyword and may not be bound to variables or shadowed" - } - _ => "`self` value is a keyword only available in methods with a `self` parameter", - }); + err.span_label( + span, + match source { + PathSource::Pat => { + "`self` value is a keyword and may not be bound to variables or shadowed" + } + _ => "`self` value is a keyword only available in methods with a `self` parameter", + }, + ); let is_assoc_fn = self.self_type_is_available(); let self_from_macro = "a `self` parameter, but a macro invocation can only \ access identifiers it receives from parameters"; @@ -2399,15 +2402,18 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { if module_def_id == def_id { let path = Path { span: name_binding.span, segments: path_segments, tokens: None }; - result = Some((module, ImportSuggestion { - did: Some(def_id), - descr: "module", - path, - accessible: true, - doc_visible, - note: None, - via_import: false, - })); + result = Some(( + module, + ImportSuggestion { + did: Some(def_id), + descr: "module", + path, + accessible: true, + doc_visible, + note: None, + via_import: false, + }, + )); } else { // add the module to the lookup if seen_modules.insert(module_def_id) { diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index aeb9672b758..cca01a01e98 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -888,12 +888,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { None, ) }; - self.report_error(span, ResolutionError::FailedToResolve { - segment: path.last().map(|segment| segment.ident.name), - label, - suggestion, - module, - }); + self.report_error( + span, + ResolutionError::FailedToResolve { + segment: path.last().map(|segment| segment.ident.name), + label, + suggestion, + module, + }, + ); } PathResult::Module(..) | PathResult::Indeterminate => unreachable!(), } diff --git a/compiler/rustc_session/src/config/native_libs/tests.rs b/compiler/rustc_session/src/config/native_libs/tests.rs index 3bcab93ef4b..287c98fe7eb 100644 --- a/compiler/rustc_session/src/config/native_libs/tests.rs +++ b/compiler/rustc_session/src/config/native_libs/tests.rs @@ -14,30 +14,22 @@ fn split() { (":bar", P { kind: None, modifiers: None, name: "", new_name: Some("bar") }), ("kind=foo", P { kind: Some("kind"), modifiers: None, name: "foo", new_name: None }), (":mods=foo", P { kind: Some(""), modifiers: Some("mods"), name: "foo", new_name: None }), - (":mods=:bar", P { - kind: Some(""), - modifiers: Some("mods"), - name: "", - new_name: Some("bar"), - }), - ("kind=foo:bar", P { - kind: Some("kind"), - modifiers: None, - name: "foo", - new_name: Some("bar"), - }), - ("kind:mods=foo", P { - kind: Some("kind"), - modifiers: Some("mods"), - name: "foo", - new_name: None, - }), - ("kind:mods=foo:bar", P { - kind: Some("kind"), - modifiers: Some("mods"), - name: "foo", - new_name: Some("bar"), - }), + ( + ":mods=:bar", + P { kind: Some(""), modifiers: Some("mods"), name: "", new_name: Some("bar") }, + ), + ( + "kind=foo:bar", + P { kind: Some("kind"), modifiers: None, name: "foo", new_name: Some("bar") }, + ), + ( + "kind:mods=foo", + P { kind: Some("kind"), modifiers: Some("mods"), name: "foo", new_name: None }, + ), + ( + "kind:mods=foo:bar", + P { kind: Some("kind"), modifiers: Some("mods"), name: "foo", new_name: Some("bar") }, + ), ("::==::", P { kind: Some(""), modifiers: Some(":"), name: "=", new_name: Some(":") }), ("==::==", P { kind: Some(""), modifiers: None, name: "=", new_name: Some(":==") }), ]; diff --git a/compiler/rustc_session/src/search_paths.rs b/compiler/rustc_session/src/search_paths.rs index 78473fccd2d..b750d870cb6 100644 --- a/compiler/rustc_session/src/search_paths.rs +++ b/compiler/rustc_session/src/search_paths.rs @@ -140,10 +140,10 @@ impl SearchPath { e.ok().and_then(|e| { e.file_name().to_str().map(|s| { let file_name_str: Arc = s.into(); - (Arc::clone(&file_name_str), SearchPathFile { - path: e.path().into(), - file_name_str, - }) + ( + Arc::clone(&file_name_str), + SearchPathFile { path: e.path().into(), file_name_str }, + ) }) }) }) diff --git a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs index a2d95f0f693..a0faf20c79a 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs @@ -771,12 +771,10 @@ impl<'tcx> Stable<'tcx> for ty::RegionKind<'tcx> { index: early_reg.index, name: early_reg.name.to_string(), }), - ty::ReBound(db_index, bound_reg) => { - RegionKind::ReBound(db_index.as_u32(), BoundRegion { - var: bound_reg.var.as_u32(), - kind: bound_reg.kind.stable(tables), - }) - } + ty::ReBound(db_index, bound_reg) => RegionKind::ReBound( + db_index.as_u32(), + BoundRegion { var: bound_reg.var.as_u32(), kind: bound_reg.kind.stable(tables) }, + ), ty::ReStatic => RegionKind::ReStatic, ty::RePlaceholder(place_holder) => { RegionKind::RePlaceholder(stable_mir::ty::Placeholder { diff --git a/compiler/rustc_target/src/spec/base/apple/tests.rs b/compiler/rustc_target/src/spec/base/apple/tests.rs index a7335c9bcae..7a985ad4dc0 100644 --- a/compiler/rustc_target/src/spec/base/apple/tests.rs +++ b/compiler/rustc_target/src/spec/base/apple/tests.rs @@ -32,10 +32,13 @@ fn macos_link_environment_unmodified() { for target in all_macos_targets { // macOS targets should only remove information for cross-compiling, but never // for the host. - assert_eq!(target.link_env_remove, crate::spec::cvs![ - "IPHONEOS_DEPLOYMENT_TARGET", - "TVOS_DEPLOYMENT_TARGET", - "XROS_DEPLOYMENT_TARGET" - ],); + assert_eq!( + target.link_env_remove, + crate::spec::cvs![ + "IPHONEOS_DEPLOYMENT_TARGET", + "TVOS_DEPLOYMENT_TARGET", + "XROS_DEPLOYMENT_TARGET" + ], + ); } } diff --git a/compiler/rustc_target/src/spec/base/avr_gnu.rs b/compiler/rustc_target/src/spec/base/avr_gnu.rs index 4f348af21ad..3554dcfcb4a 100644 --- a/compiler/rustc_target/src/spec/base/avr_gnu.rs +++ b/compiler/rustc_target/src/spec/base/avr_gnu.rs @@ -28,9 +28,10 @@ pub(crate) fn target(target_cpu: &'static str, mmcu: &'static str) -> Target { linker: Some("avr-gcc".into()), eh_frame_header: false, pre_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[mmcu]), - late_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - "-lgcc", - ]), + late_link_args: TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &["-lgcc"], + ), max_atomic_width: Some(16), atomic_cas: false, relocation_model: RelocModel::Static, diff --git a/compiler/rustc_target/src/spec/base/fuchsia.rs b/compiler/rustc_target/src/spec/base/fuchsia.rs index 910ee328368..9deafcac27f 100644 --- a/compiler/rustc_target/src/spec/base/fuchsia.rs +++ b/compiler/rustc_target/src/spec/base/fuchsia.rs @@ -8,19 +8,22 @@ pub(crate) fn opts() -> TargetOptions { // so we only list them for ld/lld. // // https://github.com/llvm/llvm-project/blob/db9322b2066c55254e7691efeab863f43bfcc084/clang/lib/Driver/ToolChains/Fuchsia.cpp#L31 - let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "--build-id", - "--hash-style=gnu", - "-z", - "max-page-size=4096", - "-z", - "now", - "-z", - "rodynamic", - "-z", - "separate-loadable-segments", - "--pack-dyn-relocs=relr", - ]); + let pre_link_args = TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &[ + "--build-id", + "--hash-style=gnu", + "-z", + "max-page-size=4096", + "-z", + "now", + "-z", + "rodynamic", + "-z", + "separate-loadable-segments", + "--pack-dyn-relocs=relr", + ], + ); TargetOptions { os: "fuchsia".into(), diff --git a/compiler/rustc_target/src/spec/base/illumos.rs b/compiler/rustc_target/src/spec/base/illumos.rs index bb7dfafc53e..2391b229e5b 100644 --- a/compiler/rustc_target/src/spec/base/illumos.rs +++ b/compiler/rustc_target/src/spec/base/illumos.rs @@ -1,25 +1,28 @@ use crate::spec::{Cc, FramePointer, LinkerFlavor, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { - let late_link_args = TargetOptions::link_args(LinkerFlavor::Unix(Cc::Yes), &[ - // The illumos libc contains a stack unwinding implementation, as - // does libgcc_s. The latter implementation includes several - // additional symbols that are not always in base libc. To force - // the consistent use of just one unwinder, we ensure libc appears - // after libgcc_s in the NEEDED list for the resultant binary by - // ignoring any attempts to add it as a dynamic dependency until the - // very end. - // FIXME: This should be replaced by a more complete and generic - // mechanism for controlling the order of library arguments passed - // to the linker. - "-lc", - // LLVM will insert calls to the stack protector functions - // "__stack_chk_fail" and "__stack_chk_guard" into code in native - // object files. Some platforms include these symbols directly in - // libc, but at least historically these have been provided in - // libssp.so on illumos and Solaris systems. - "-lssp", - ]); + let late_link_args = TargetOptions::link_args( + LinkerFlavor::Unix(Cc::Yes), + &[ + // The illumos libc contains a stack unwinding implementation, as + // does libgcc_s. The latter implementation includes several + // additional symbols that are not always in base libc. To force + // the consistent use of just one unwinder, we ensure libc appears + // after libgcc_s in the NEEDED list for the resultant binary by + // ignoring any attempts to add it as a dynamic dependency until the + // very end. + // FIXME: This should be replaced by a more complete and generic + // mechanism for controlling the order of library arguments passed + // to the linker. + "-lc", + // LLVM will insert calls to the stack protector functions + // "__stack_chk_fail" and "__stack_chk_guard" into code in native + // object files. Some platforms include these symbols directly in + // libc, but at least historically these have been provided in + // libssp.so on illumos and Solaris systems. + "-lssp", + ], + ); TargetOptions { os: "illumos".into(), diff --git a/compiler/rustc_target/src/spec/base/nto_qnx.rs b/compiler/rustc_target/src/spec/base/nto_qnx.rs index 819e68a0500..3f35b8b801a 100644 --- a/compiler/rustc_target/src/spec/base/nto_qnx.rs +++ b/compiler/rustc_target/src/spec/base/nto_qnx.rs @@ -77,10 +77,10 @@ pub(crate) fn pre_link_args(api_var: ApiVariant, arch: Arch) -> LinkArgs { ApiVariant::Default => { TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[qcc_arg]) } - ApiVariant::IoSock => TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - qcc_arg, - get_iosock_param(arch_lib_dir), - ]), + ApiVariant::IoSock => TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &[qcc_arg, get_iosock_param(arch_lib_dir)], + ), } } diff --git a/compiler/rustc_target/src/spec/base/uefi_msvc.rs b/compiler/rustc_target/src/spec/base/uefi_msvc.rs index b0232ecbe61..4766eab7fd7 100644 --- a/compiler/rustc_target/src/spec/base/uefi_msvc.rs +++ b/compiler/rustc_target/src/spec/base/uefi_msvc.rs @@ -14,22 +14,25 @@ use crate::spec::{LinkerFlavor, Lld, PanicStrategy, StackProbeType, TargetOption pub(crate) fn opts() -> TargetOptions { let mut base = base::msvc::opts(); - base.add_pre_link_args(LinkerFlavor::Msvc(Lld::No), &[ - // Non-standard subsystems have no default entry-point in PE+ files. We have to define - // one. "efi_main" seems to be a common choice amongst other implementations and the - // spec. - "/entry:efi_main", - // COFF images have a "Subsystem" field in their header, which defines what kind of - // program it is. UEFI has 3 fields reserved, which are EFI_APPLICATION, - // EFI_BOOT_SERVICE_DRIVER, and EFI_RUNTIME_DRIVER. We default to EFI_APPLICATION, - // which is very likely the most common option. Individual projects can override this - // with custom linker flags. - // The subsystem-type only has minor effects on the application. It defines the memory - // regions the application is loaded into (runtime-drivers need to be put into - // reserved areas), as well as whether a return from the entry-point is treated as - // exit (default for applications). - "/subsystem:efi_application", - ]); + base.add_pre_link_args( + LinkerFlavor::Msvc(Lld::No), + &[ + // Non-standard subsystems have no default entry-point in PE+ files. We have to define + // one. "efi_main" seems to be a common choice amongst other implementations and the + // spec. + "/entry:efi_main", + // COFF images have a "Subsystem" field in their header, which defines what kind of + // program it is. UEFI has 3 fields reserved, which are EFI_APPLICATION, + // EFI_BOOT_SERVICE_DRIVER, and EFI_RUNTIME_DRIVER. We default to EFI_APPLICATION, + // which is very likely the most common option. Individual projects can override this + // with custom linker flags. + // The subsystem-type only has minor effects on the application. It defines the memory + // regions the application is loaded into (runtime-drivers need to be put into + // reserved areas), as well as whether a return from the entry-point is treated as + // exit (default for applications). + "/subsystem:efi_application", + ], + ); TargetOptions { os: "uefi".into(), diff --git a/compiler/rustc_target/src/spec/base/windows_gnu.rs b/compiler/rustc_target/src/spec/base/windows_gnu.rs index d8b6ae8cf32..024b10f2faa 100644 --- a/compiler/rustc_target/src/spec/base/windows_gnu.rs +++ b/compiler/rustc_target/src/spec/base/windows_gnu.rs @@ -6,19 +6,26 @@ use crate::spec::{ }; pub(crate) fn opts() -> TargetOptions { - let mut pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - // Enable ASLR - "--dynamicbase", - // ASLR will rebase it anyway so leaving that option enabled only leads to confusion - "--disable-auto-image-base", - ]); - add_link_args(&mut pre_link_args, LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - // Tell GCC to avoid linker plugins, because we are not bundling - // them with Windows installer, and Rust does its own LTO anyways. - "-fno-use-linker-plugin", - "-Wl,--dynamicbase", - "-Wl,--disable-auto-image-base", - ]); + let mut pre_link_args = TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &[ + // Enable ASLR + "--dynamicbase", + // ASLR will rebase it anyway so leaving that option enabled only leads to confusion + "--disable-auto-image-base", + ], + ); + add_link_args( + &mut pre_link_args, + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &[ + // Tell GCC to avoid linker plugins, because we are not bundling + // them with Windows installer, and Rust does its own LTO anyways. + "-fno-use-linker-plugin", + "-Wl,--dynamicbase", + "-Wl,--disable-auto-image-base", + ], + ); // Order of `late_link_args*` was found through trial and error to work with various // mingw-w64 versions (not tested on the CI). It's expected to change from time to time. diff --git a/compiler/rustc_target/src/spec/base/windows_gnullvm.rs b/compiler/rustc_target/src/spec/base/windows_gnullvm.rs index 86e52117dbf..4a6e7c75200 100644 --- a/compiler/rustc_target/src/spec/base/windows_gnullvm.rs +++ b/compiler/rustc_target/src/spec/base/windows_gnullvm.rs @@ -7,18 +7,15 @@ pub(crate) fn opts() -> TargetOptions { // as a path since it's not added to linker search path by the default. // There were attempts to make it behave like libgcc (so one can just use -l) // but LLVM maintainers rejected it: https://reviews.llvm.org/D51440 - let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - "-nolibc", - "--unwindlib=none", - ]); + let pre_link_args = TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &["-nolibc", "--unwindlib=none"], + ); // Order of `late_link_args*` does not matter with LLD. - let late_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - "-lmingw32", - "-lmingwex", - "-lmsvcrt", - "-lkernel32", - "-luser32", - ]); + let late_link_args = TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &["-lmingw32", "-lmingwex", "-lmsvcrt", "-lkernel32", "-luser32"], + ); TargetOptions { os: "windows".into(), diff --git a/compiler/rustc_target/src/spec/json.rs b/compiler/rustc_target/src/spec/json.rs index a6b0ec072e8..f703132e51f 100644 --- a/compiler/rustc_target/src/spec/json.rs +++ b/compiler/rustc_target/src/spec/json.rs @@ -647,10 +647,10 @@ impl Target { // Each field should have been read using `Json::remove` so any keys remaining are unused. let remaining_keys = obj.keys(); - Ok((base, TargetWarnings { - unused_fields: remaining_keys.cloned().collect(), - incorrect_type, - })) + Ok(( + base, + TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type }, + )) } } diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_none.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_none.rs index 05fe32734a7..27dd713cc53 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_none.rs @@ -16,9 +16,10 @@ pub(crate) fn target() -> Target { linker_flavor: LinkerFlavor::Gnu(Cc::No, Lld::Yes), linker: Some("rust-lld".into()), // Enable the Cortex-A53 errata 843419 mitigation by default - pre_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "--fix-cortex-a53-843419", - ]), + pre_link_args: TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["--fix-cortex-a53-843419"], + ), features: "+v8a,+strict-align,+neon,+fp-armv8".into(), supported_sanitizers: SanitizerSet::KCFI | SanitizerSet::KERNELADDRESS, relocation_model: RelocModel::Static, diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_nuttx.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_nuttx.rs index 582211b02b6..f7f8dc1e1ef 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_nuttx.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_nuttx.rs @@ -16,9 +16,10 @@ pub(crate) fn target() -> Target { linker_flavor: LinkerFlavor::Gnu(Cc::No, Lld::Yes), linker: Some("rust-lld".into()), // Enable the Cortex-A53 errata 843419 mitigation by default - pre_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "--fix-cortex-a53-843419", - ]), + pre_link_args: TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["--fix-cortex-a53-843419"], + ), features: "+v8a,+strict-align,+neon,+fp-armv8".into(), supported_sanitizers: SanitizerSet::KCFI | SanitizerSet::KERNELADDRESS, relocation_model: RelocModel::Static, diff --git a/compiler/rustc_target/src/spec/targets/arm64ec_pc_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/arm64ec_pc_windows_msvc.rs index 03c96fbfdb0..5026c52429e 100644 --- a/compiler/rustc_target/src/spec/targets/arm64ec_pc_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/arm64ec_pc_windows_msvc.rs @@ -4,10 +4,11 @@ pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); base.max_atomic_width = Some(128); base.features = "+v8a,+neon,+fp-armv8".into(); - add_link_args(&mut base.late_link_args, LinkerFlavor::Msvc(Lld::No), &[ - "/machine:arm64ec", - "softintrin.lib", - ]); + add_link_args( + &mut base.late_link_args, + LinkerFlavor::Msvc(Lld::No), + &["/machine:arm64ec", "softintrin.lib"], + ); Target { llvm_target: "arm64ec-pc-windows-msvc".into(), diff --git a/compiler/rustc_target/src/spec/targets/armv6k_nintendo_3ds.rs b/compiler/rustc_target/src/spec/targets/armv6k_nintendo_3ds.rs index b323d2f8655..5438811803b 100644 --- a/compiler/rustc_target/src/spec/targets/armv6k_nintendo_3ds.rs +++ b/compiler/rustc_target/src/spec/targets/armv6k_nintendo_3ds.rs @@ -5,12 +5,10 @@ use crate::spec::{Cc, FloatAbi, LinkerFlavor, Lld, RelocModel, Target, TargetOpt /// Requires the devkitARM toolchain for 3DS targets on the host system. pub(crate) fn target() -> Target { - let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - "-specs=3dsx.specs", - "-mtune=mpcore", - "-mfloat-abi=hard", - "-mtp=soft", - ]); + let pre_link_args = TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &["-specs=3dsx.specs", "-mtune=mpcore", "-mfloat-abi=hard", "-mtp=soft"], + ); Target { llvm_target: "armv6k-none-eabihf".into(), diff --git a/compiler/rustc_target/src/spec/targets/armv7_sony_vita_newlibeabihf.rs b/compiler/rustc_target/src/spec/targets/armv7_sony_vita_newlibeabihf.rs index 18d834597d8..f468ac68384 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_sony_vita_newlibeabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_sony_vita_newlibeabihf.rs @@ -6,10 +6,10 @@ use crate::spec::{Cc, FloatAbi, LinkerFlavor, Lld, RelocModel, Target, TargetOpt /// Requires the VITASDK toolchain on the host system. pub(crate) fn target() -> Target { - let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - "-Wl,-q", - "-Wl,--pic-veneer", - ]); + let pre_link_args = TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &["-Wl,-q", "-Wl,--pic-veneer"], + ); Target { llvm_target: "thumbv7a-vita-eabihf".into(), diff --git a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs index 9ef8e120e0d..208fe50912c 100644 --- a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs @@ -9,11 +9,10 @@ pub(crate) fn target() -> Target { // Mark all dynamic libraries and executables as compatible with the larger 4GiB address // space available to x86 Windows binaries on x86_64. - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "-m", - "i386pe", - "--large-address-aware", - ]); + base.add_pre_link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["-m", "i386pe", "--large-address-aware"], + ); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-Wl,--large-address-aware"]); Target { diff --git a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs index 13d3c5532ff..5df8dce1aa3 100644 --- a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs +++ b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs @@ -9,11 +9,10 @@ pub(crate) fn target() -> Target { // Mark all dynamic libraries and executables as compatible with the larger 4GiB address // space available to x86 Windows binaries on x86_64. - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "-m", - "i386pe", - "--large-address-aware", - ]); + base.add_pre_link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["-m", "i386pe", "--large-address-aware"], + ); Target { llvm_target: "i686-pc-windows-gnu".into(), diff --git a/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs index aacad266863..180750bc7a8 100644 --- a/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs @@ -6,15 +6,18 @@ pub(crate) fn target() -> Target { base.max_atomic_width = Some(64); base.supported_sanitizers = SanitizerSet::ADDRESS; - base.add_pre_link_args(LinkerFlavor::Msvc(Lld::No), &[ - // Mark all dynamic libraries and executables as compatible with the larger 4GiB address - // space available to x86 Windows binaries on x86_64. - "/LARGEADDRESSAWARE", - // Ensure the linker will only produce an image if it can also produce a table of - // the image's safe exception handlers. - // https://docs.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers - "/SAFESEH", - ]); + base.add_pre_link_args( + LinkerFlavor::Msvc(Lld::No), + &[ + // Mark all dynamic libraries and executables as compatible with the larger 4GiB address + // space available to x86 Windows binaries on x86_64. + "/LARGEADDRESSAWARE", + // Ensure the linker will only produce an image if it can also produce a table of + // the image's safe exception handlers. + // https://docs.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers + "/SAFESEH", + ], + ); Target { llvm_target: "i686-pc-windows-msvc".into(), diff --git a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs index ffb9926e944..6e3733538ed 100644 --- a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs @@ -8,11 +8,10 @@ pub(crate) fn target() -> Target { // Mark all dynamic libraries and executables as compatible with the larger 4GiB address // space available to x86 Windows binaries on x86_64. - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "-m", - "i386pe", - "--large-address-aware", - ]); + base.add_pre_link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["-m", "i386pe", "--large-address-aware"], + ); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-Wl,--large-address-aware"]); Target { diff --git a/compiler/rustc_target/src/spec/targets/i686_win7_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_win7_windows_gnu.rs index 086a799a68c..1d084c0729c 100644 --- a/compiler/rustc_target/src/spec/targets/i686_win7_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_win7_windows_gnu.rs @@ -10,11 +10,10 @@ pub(crate) fn target() -> Target { // Mark all dynamic libraries and executables as compatible with the larger 4GiB address // space available to x86 Windows binaries on x86_64. - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "-m", - "i386pe", - "--large-address-aware", - ]); + base.add_pre_link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["-m", "i386pe", "--large-address-aware"], + ); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-Wl,--large-address-aware"]); Target { diff --git a/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs index 173977b77bd..7efba3aa986 100644 --- a/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs @@ -7,15 +7,18 @@ pub(crate) fn target() -> Target { base.max_atomic_width = Some(64); base.supported_sanitizers = SanitizerSet::ADDRESS; - base.add_pre_link_args(LinkerFlavor::Msvc(Lld::No), &[ - // Mark all dynamic libraries and executables as compatible with the larger 4GiB address - // space available to x86 Windows binaries on x86_64. - "/LARGEADDRESSAWARE", - // Ensure the linker will only produce an image if it can also produce a table of - // the image's safe exception handlers. - // https://docs.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers - "/SAFESEH", - ]); + base.add_pre_link_args( + LinkerFlavor::Msvc(Lld::No), + &[ + // Mark all dynamic libraries and executables as compatible with the larger 4GiB address + // space available to x86 Windows binaries on x86_64. + "/LARGEADDRESSAWARE", + // Ensure the linker will only produce an image if it can also produce a table of + // the image's safe exception handlers. + // https://docs.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers + "/SAFESEH", + ], + ); Target { llvm_target: "i686-pc-windows-msvc".into(), diff --git a/compiler/rustc_target/src/spec/targets/mipsel_sony_psp.rs b/compiler/rustc_target/src/spec/targets/mipsel_sony_psp.rs index bf51d864372..2c63b0f2f38 100644 --- a/compiler/rustc_target/src/spec/targets/mipsel_sony_psp.rs +++ b/compiler/rustc_target/src/spec/targets/mipsel_sony_psp.rs @@ -4,10 +4,10 @@ use crate::spec::{Cc, LinkerFlavor, Lld, RelocModel, Target, TargetOptions, cvs} const LINKER_SCRIPT: &str = include_str!("./mipsel_sony_psp_linker_script.ld"); pub(crate) fn target() -> Target { - let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "--emit-relocs", - "--nmagic", - ]); + let pre_link_args = TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["--emit-relocs", "--nmagic"], + ); Target { llvm_target: "mipsel-sony-psp".into(), diff --git a/compiler/rustc_target/src/spec/targets/powerpc64_ibm_aix.rs b/compiler/rustc_target/src/spec/targets/powerpc64_ibm_aix.rs index edabbbf5f00..2125c95e266 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64_ibm_aix.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64_ibm_aix.rs @@ -3,12 +3,10 @@ use crate::spec::{Cc, LinkerFlavor, Target, base}; pub(crate) fn target() -> Target { let mut base = base::aix::opts(); base.max_atomic_width = Some(64); - base.add_pre_link_args(LinkerFlavor::Unix(Cc::No), &[ - "-b64", - "-bpT:0x100000000", - "-bpD:0x110000000", - "-bcdtors:all:0:s", - ]); + base.add_pre_link_args( + LinkerFlavor::Unix(Cc::No), + &["-b64", "-bpT:0x100000000", "-bpD:0x110000000", "-bcdtors:all:0:s"], + ); Target { llvm_target: "powerpc64-ibm-aix".into(), diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_freebsd.rs index 9cfc2153ac1..890fae67d76 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_freebsd.rs @@ -4,10 +4,10 @@ use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, pub(crate) fn target() -> Target { let mut base = base::freebsd::opts(); // Extra hint to linker that we are generating secure-PLT code. - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - "-m32", - "--target=powerpc-unknown-freebsd13.0", - ]); + base.add_pre_link_args( + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &["-m32", "--target=powerpc-unknown-freebsd13.0"], + ); base.max_atomic_width = Some(32); base.stack_probes = StackProbeType::Inline; diff --git a/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs index 45941cd7c01..c92a01c40cf 100644 --- a/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs @@ -17,9 +17,10 @@ pub(crate) fn target() -> Target { features: "+v8plus".into(), cpu: "v9".into(), endian: Endian::Big, - late_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ - "-mcpu=v9", "-m32", - ]), + late_link_args: TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::Yes, Lld::No), + &["-mcpu=v9", "-m32"], + ), max_atomic_width: Some(32), ..base::linux_gnu::opts() }, diff --git a/compiler/rustc_target/src/spec/targets/wasm32_unknown_unknown.rs b/compiler/rustc_target/src/spec/targets/wasm32_unknown_unknown.rs index 96237f20891..bcf7b69fe74 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_unknown_unknown.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_unknown_unknown.rs @@ -16,17 +16,23 @@ pub(crate) fn target() -> Target { let mut options = base::wasm::options(); options.os = "unknown".into(); - options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::No), &[ - // For now this target just never has an entry symbol no matter the output - // type, so unconditionally pass this. - "--no-entry", - ]); - options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::Yes), &[ - // Make sure clang uses LLD as its linker and is configured appropriately - // otherwise - "--target=wasm32-unknown-unknown", - "-Wl,--no-entry", - ]); + options.add_pre_link_args( + LinkerFlavor::WasmLld(Cc::No), + &[ + // For now this target just never has an entry symbol no matter the output + // type, so unconditionally pass this. + "--no-entry", + ], + ); + options.add_pre_link_args( + LinkerFlavor::WasmLld(Cc::Yes), + &[ + // Make sure clang uses LLD as its linker and is configured appropriately + // otherwise + "--target=wasm32-unknown-unknown", + "-Wl,--no-entry", + ], + ); Target { llvm_target: "wasm32-unknown-unknown".into(), diff --git a/compiler/rustc_target/src/spec/targets/wasm32_wasip1_threads.rs b/compiler/rustc_target/src/spec/targets/wasm32_wasip1_threads.rs index 0c2e2bfeda6..2411d386f52 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_wasip1_threads.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_wasip1_threads.rs @@ -15,17 +15,19 @@ pub(crate) fn target() -> Target { options.os = "wasi".into(); options.env = "p1".into(); - options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::No), &[ - "--import-memory", - "--export-memory", - "--shared-memory", - ]); - options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::Yes), &[ - "--target=wasm32-wasip1-threads", - "-Wl,--import-memory", - "-Wl,--export-memory,", - "-Wl,--shared-memory", - ]); + options.add_pre_link_args( + LinkerFlavor::WasmLld(Cc::No), + &["--import-memory", "--export-memory", "--shared-memory"], + ); + options.add_pre_link_args( + LinkerFlavor::WasmLld(Cc::Yes), + &[ + "--target=wasm32-wasip1-threads", + "-Wl,--import-memory", + "-Wl,--export-memory,", + "-Wl,--shared-memory", + ], + ); options.pre_link_objects_self_contained = crt_objects::pre_wasi_self_contained(); options.post_link_objects_self_contained = crt_objects::post_wasi_self_contained(); diff --git a/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs b/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs index 5c35e9c21d3..ab1dc21d125 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32v1_none.rs @@ -23,17 +23,23 @@ pub(crate) fn target() -> Target { options.cpu = "mvp".into(); options.features = "+mutable-globals".into(); - options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::No), &[ - // For now this target just never has an entry symbol no matter the output - // type, so unconditionally pass this. - "--no-entry", - ]); - options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::Yes), &[ - // Make sure clang uses LLD as its linker and is configured appropriately - // otherwise - "--target=wasm32-unknown-unknown", - "-Wl,--no-entry", - ]); + options.add_pre_link_args( + LinkerFlavor::WasmLld(Cc::No), + &[ + // For now this target just never has an entry symbol no matter the output + // type, so unconditionally pass this. + "--no-entry", + ], + ); + options.add_pre_link_args( + LinkerFlavor::WasmLld(Cc::Yes), + &[ + // Make sure clang uses LLD as its linker and is configured appropriately + // otherwise + "--target=wasm32-unknown-unknown", + "-Wl,--no-entry", + ], + ); Target { llvm_target: "wasm32-unknown-unknown".into(), diff --git a/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs b/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs index 22fa26d3cdb..596e26d1e9d 100644 --- a/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs +++ b/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs @@ -13,18 +13,24 @@ pub(crate) fn target() -> Target { let mut options = base::wasm::options(); options.os = "unknown".into(); - options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::No), &[ - // For now this target just never has an entry symbol no matter the output - // type, so unconditionally pass this. - "--no-entry", - "-mwasm64", - ]); - options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::Yes), &[ - // Make sure clang uses LLD as its linker and is configured appropriately - // otherwise - "--target=wasm64-unknown-unknown", - "-Wl,--no-entry", - ]); + options.add_pre_link_args( + LinkerFlavor::WasmLld(Cc::No), + &[ + // For now this target just never has an entry symbol no matter the output + // type, so unconditionally pass this. + "--no-entry", + "-mwasm64", + ], + ); + options.add_pre_link_args( + LinkerFlavor::WasmLld(Cc::Yes), + &[ + // Make sure clang uses LLD as its linker and is configured appropriately + // otherwise + "--target=wasm64-unknown-unknown", + "-Wl,--no-entry", + ], + ); // Any engine that implements wasm64 will surely implement the rest of these // features since they were all merged into the official spec by the time diff --git a/compiler/rustc_target/src/spec/targets/x86_64_fortanix_unknown_sgx.rs b/compiler/rustc_target/src/spec/targets/x86_64_fortanix_unknown_sgx.rs index 65c31634630..60d078371bb 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_fortanix_unknown_sgx.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_fortanix_unknown_sgx.rs @@ -3,37 +3,40 @@ use std::borrow::Cow; use crate::spec::{Cc, LinkerFlavor, Lld, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { - let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "-e", - "elf_entry", - "-Bstatic", - "--gc-sections", - "-z", - "text", - "-z", - "norelro", - "--no-undefined", - "--error-unresolved-symbols", - "--no-undefined-version", - "-Bsymbolic", - "--export-dynamic", - // The following symbols are needed by libunwind, which is linked after - // libstd. Make sure they're included in the link. - "-u", - "__rust_abort", - "-u", - "__rust_c_alloc", - "-u", - "__rust_c_dealloc", - "-u", - "__rust_print_err", - "-u", - "__rust_rwlock_rdlock", - "-u", - "__rust_rwlock_unlock", - "-u", - "__rust_rwlock_wrlock", - ]); + let pre_link_args = TargetOptions::link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &[ + "-e", + "elf_entry", + "-Bstatic", + "--gc-sections", + "-z", + "text", + "-z", + "norelro", + "--no-undefined", + "--error-unresolved-symbols", + "--no-undefined-version", + "-Bsymbolic", + "--export-dynamic", + // The following symbols are needed by libunwind, which is linked after + // libstd. Make sure they're included in the link. + "-u", + "__rust_abort", + "-u", + "__rust_c_alloc", + "-u", + "__rust_c_dealloc", + "-u", + "__rust_print_err", + "-u", + "__rust_rwlock_rdlock", + "-u", + "__rust_rwlock_unlock", + "-u", + "__rust_rwlock_wrlock", + ], + ); const EXPORT_SYMBOLS: &[&str] = &[ "sgx_entry", diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnu.rs index e0ffcaf5a72..b10d4478d5e 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnu.rs @@ -6,11 +6,10 @@ pub(crate) fn target() -> Target { base.features = "+cx16,+sse3,+sahf".into(); base.plt_by_default = false; // Use high-entropy 64 bit address space for ASLR - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "-m", - "i386pep", - "--high-entropy-va", - ]); + base.add_pre_link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["-m", "i386pep", "--high-entropy-va"], + ); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64", "-Wl,--high-entropy-va"]); base.max_atomic_width = Some(128); base.linker = Some("x86_64-w64-mingw32-gcc".into()); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_gnu.rs index fd10bc087ef..0ef41d315af 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_gnu.rs @@ -6,11 +6,10 @@ pub(crate) fn target() -> Target { base.features = "+cx16,+sse3,+sahf".into(); base.plt_by_default = false; // Use high-entropy 64 bit address space for ASLR - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "-m", - "i386pep", - "--high-entropy-va", - ]); + base.add_pre_link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["-m", "i386pep", "--high-entropy-va"], + ); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64", "-Wl,--high-entropy-va"]); base.max_atomic_width = Some(128); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_win7_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/x86_64_win7_windows_gnu.rs index d40df5a3e7d..8f903934a90 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_win7_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_win7_windows_gnu.rs @@ -6,11 +6,10 @@ pub(crate) fn target() -> Target { base.cpu = "x86-64".into(); base.plt_by_default = false; // Use high-entropy 64 bit address space for ASLR - base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ - "-m", - "i386pep", - "--high-entropy-va", - ]); + base.add_pre_link_args( + LinkerFlavor::Gnu(Cc::No, Lld::No), + &["-m", "i386pep", "--high-entropy-va"], + ); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64", "-Wl,--high-entropy-va"]); base.max_atomic_width = Some(64); base.linker = Some("x86_64-w64-mingw32-gcc".into()); diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index e423ca71dfc..ea7c15a3595 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -341,13 +341,17 @@ static AARCH64_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("sve2p1", Unstable(sym::aarch64_unstable_target_feature), &["sve2"]), // FEAT_TME ("tme", Stable, &[]), - ("v8.1a", Unstable(sym::aarch64_ver_target_feature), &[ - "crc", "lse", "rdm", "pan", "lor", "vh", - ]), + ( + "v8.1a", + Unstable(sym::aarch64_ver_target_feature), + &["crc", "lse", "rdm", "pan", "lor", "vh"], + ), ("v8.2a", Unstable(sym::aarch64_ver_target_feature), &["v8.1a", "ras", "dpb"]), - ("v8.3a", Unstable(sym::aarch64_ver_target_feature), &[ - "v8.2a", "rcpc", "paca", "pacg", "jsconv", - ]), + ( + "v8.3a", + Unstable(sym::aarch64_ver_target_feature), + &["v8.2a", "rcpc", "paca", "pacg", "jsconv"], + ), ("v8.4a", Unstable(sym::aarch64_ver_target_feature), &["v8.3a", "dotprod", "dit", "flagm"]), ("v8.5a", Unstable(sym::aarch64_ver_target_feature), &["v8.4a", "ssbs", "sb", "dpb2", "bti"]), ("v8.6a", Unstable(sym::aarch64_ver_target_feature), &["v8.5a", "bf16", "i8mm"]), diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs index dfbef39e9e1..039e21cb556 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs @@ -323,9 +323,12 @@ pub fn suggest_new_region_bound( .params .iter() .filter(|p| { - matches!(p.kind, GenericParamKind::Lifetime { - kind: hir::LifetimeParamKind::Explicit - }) + matches!( + p.kind, + GenericParamKind::Lifetime { + kind: hir::LifetimeParamKind::Explicit + } + ) }) .map(|p| { if let hir::ParamName::Plain(name) = p.name { diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 3128577776a..1b43820bac0 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -1837,13 +1837,16 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } } span.push_span_label(self.tcx.def_span(other_trait_def_id), "this is the found trait"); - err.highlighted_span_note(span, vec![ - StringPart::normal("there are ".to_string()), - StringPart::highlighted("multiple different versions".to_string()), - StringPart::normal(" of crate `".to_string()), - StringPart::highlighted(format!("{crate_name}")), - StringPart::normal("` in the dependency graph\n".to_string()), - ]); + err.highlighted_span_note( + span, + vec![ + StringPart::normal("there are ".to_string()), + StringPart::highlighted("multiple different versions".to_string()), + StringPart::normal(" of crate `".to_string()), + StringPart::highlighted(format!("{crate_name}")), + StringPart::normal("` in the dependency graph\n".to_string()), + ], + ); if points_at_type { // We only clarify that the same type from different crate versions are not the // same when we *find* the same type coming from different crate versions, otherwise @@ -2977,12 +2980,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { .inputs .iter() .map(|arg| match arg.kind { - hir::TyKind::Tup(tys) => { - ArgKind::Tuple(Some(arg.span), vec![ - ("_".to_owned(), "_".to_owned()); - tys.len() - ]) - } + hir::TyKind::Tup(tys) => ArgKind::Tuple( + Some(arg.span), + vec![("_".to_owned(), "_".to_owned()); tys.len()], + ), _ => ArgKind::empty(), }) .collect::>(), diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index c194cc11727..527d2e54e43 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -640,10 +640,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } // Empty suggestions with empty spans ICE with debug assertions if steps == 0 { - return (msg.trim_end_matches(" and dereferencing instead"), vec![( - prefix_span, - String::new(), - )]); + return ( + msg.trim_end_matches(" and dereferencing instead"), + vec![(prefix_span, String::new())], + ); } let derefs = "*".repeat(steps); let needs_parens = steps > 0 @@ -3552,10 +3552,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } ObligationCauseCode::TrivialBound => { err.help("see issue #48214"); - tcx.disabled_nightly_features(err, Some(tcx.local_def_id_to_hir_id(body_id)), [( - String::new(), - sym::trivial_bounds, - )]); + tcx.disabled_nightly_features( + err, + Some(tcx.local_def_id_to_hir_id(body_id)), + [(String::new(), sym::trivial_bounds)], + ); } ObligationCauseCode::OpaqueReturnType(expr_info) => { let (expr_ty, expr) = if let Some((expr_ty, hir_id)) = expr_info { diff --git a/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs b/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs index 8edd623e5d0..7364b4aa343 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill/derive_errors.rs @@ -153,10 +153,10 @@ fn find_best_leaf_obligation<'tcx>( infcx .fudge_inference_if_ok(|| { infcx - .visit_proof_tree(obligation.clone().into(), &mut BestObligation { - obligation: obligation.clone(), - consider_ambiguities, - }) + .visit_proof_tree( + obligation.clone().into(), + &mut BestObligation { obligation: obligation.clone(), consider_ambiguities }, + ) .break_value() .ok_or(()) }) diff --git a/compiler/rustc_trait_selection/src/solve/normalize.rs b/compiler/rustc_trait_selection/src/solve/normalize.rs index a724705ffe9..232357dc71a 100644 --- a/compiler/rustc_trait_selection/src/solve/normalize.rs +++ b/compiler/rustc_trait_selection/src/solve/normalize.rs @@ -130,11 +130,12 @@ where self.depth += 1; let new_infer_ct = infcx.next_const_var(self.at.cause.span); - let obligation = - Obligation::new(tcx, self.at.cause.clone(), self.at.param_env, ty::NormalizesTo { - alias: uv.into(), - term: new_infer_ct.into(), - }); + let obligation = Obligation::new( + tcx, + self.at.cause.clone(), + self.at.param_env, + ty::NormalizesTo { alias: uv.into(), term: new_infer_ct.into() }, + ); let result = if infcx.predicate_may_hold(&obligation) { self.fulfill_cx.register_predicate_obligation(infcx, obligation); @@ -252,20 +253,20 @@ impl<'tcx> TypeFolder> for DeeplyNormalizeForDiagnosticsFolder<'_, } fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { - deeply_normalize_with_skipped_universes(self.at, ty, vec![ - None; - ty.outer_exclusive_binder() - .as_usize() - ]) + deeply_normalize_with_skipped_universes( + self.at, + ty, + vec![None; ty.outer_exclusive_binder().as_usize()], + ) .unwrap_or_else(|_: Vec>| ty.super_fold_with(self)) } fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { - deeply_normalize_with_skipped_universes(self.at, ct, vec![ - None; - ct.outer_exclusive_binder() - .as_usize() - ]) + deeply_normalize_with_skipped_universes( + self.at, + ct, + vec![None; ct.outer_exclusive_binder().as_usize()], + ) .unwrap_or_else(|_: Vec>| ct.super_fold_with(self)) } } diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index 7ee9eb45309..3b40882ef57 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -368,9 +368,10 @@ fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>( overflowing_predicates: ambiguities .into_iter() .filter(|error| { - matches!(error.code, FulfillmentErrorCode::Ambiguity { - overflow: Some(true) - }) + matches!( + error.code, + FulfillmentErrorCode::Ambiguity { overflow: Some(true) } + ) }) .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate)) .collect(), @@ -491,13 +492,16 @@ fn plug_infer_with_placeholders<'tcx>( // Comparing against a type variable never registers hidden types anyway DefineOpaqueTypes::Yes, ty, - Ty::new_placeholder(self.infcx.tcx, ty::Placeholder { - universe: self.universe, - bound: ty::BoundTy { - var: self.next_var(), - kind: ty::BoundTyKind::Anon, + Ty::new_placeholder( + self.infcx.tcx, + ty::Placeholder { + universe: self.universe, + bound: ty::BoundTy { + var: self.next_var(), + kind: ty::BoundTyKind::Anon, + }, }, - }), + ), ) else { bug!("we always expect to be able to plug an infer var with placeholder") @@ -517,10 +521,10 @@ fn plug_infer_with_placeholders<'tcx>( // registration happening anyway. DefineOpaqueTypes::Yes, ct, - ty::Const::new_placeholder(self.infcx.tcx, ty::Placeholder { - universe: self.universe, - bound: self.next_var(), - }), + ty::Const::new_placeholder( + self.infcx.tcx, + ty::Placeholder { universe: self.universe, bound: self.next_var() }, + ), ) else { bug!("we always expect to be able to plug an infer var with placeholder") @@ -545,13 +549,16 @@ fn plug_infer_with_placeholders<'tcx>( // Lifetimes don't contain opaque types (or any types for that matter). DefineOpaqueTypes::Yes, r, - ty::Region::new_placeholder(self.infcx.tcx, ty::Placeholder { - universe: self.universe, - bound: ty::BoundRegion { - var: self.next_var(), - kind: ty::BoundRegionKind::Anon, + ty::Region::new_placeholder( + self.infcx.tcx, + ty::Placeholder { + universe: self.universe, + bound: ty::BoundRegion { + var: self.next_var(), + kind: ty::BoundRegionKind::Anon, + }, }, - }), + ), ) else { bug!("we always expect to be able to plug an infer var with placeholder") @@ -763,9 +770,9 @@ fn search_ambiguity_causes<'tcx>( causes: &mut FxIndexSet>, ) { infcx.probe(|_| { - infcx.visit_proof_tree(goal, &mut AmbiguityCausesVisitor { - cache: Default::default(), - causes, - }) + infcx.visit_proof_tree( + goal, + &mut AmbiguityCausesVisitor { cache: Default::default(), causes }, + ) }); } diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index d4a9664e282..105cb917571 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -660,13 +660,16 @@ fn replace_param_and_infer_args_with_placeholder<'tcx>( self.idx += 1; idx }; - Ty::new_placeholder(self.tcx, ty::PlaceholderType { - universe: ty::UniverseIndex::ROOT, - bound: ty::BoundTy { - var: ty::BoundVar::from_u32(idx), - kind: ty::BoundTyKind::Anon, + Ty::new_placeholder( + self.tcx, + ty::PlaceholderType { + universe: ty::UniverseIndex::ROOT, + bound: ty::BoundTy { + var: ty::BoundVar::from_u32(idx), + kind: ty::BoundTyKind::Anon, + }, }, - }) + ) } else { t.super_fold_with(self) } @@ -674,14 +677,17 @@ fn replace_param_and_infer_args_with_placeholder<'tcx>( fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> { if let ty::ConstKind::Infer(_) = c.kind() { - ty::Const::new_placeholder(self.tcx, ty::PlaceholderConst { - universe: ty::UniverseIndex::ROOT, - bound: ty::BoundVar::from_u32({ - let idx = self.idx; - self.idx += 1; - idx - }), - }) + ty::Const::new_placeholder( + self.tcx, + ty::PlaceholderConst { + universe: ty::UniverseIndex::ROOT, + bound: ty::BoundVar::from_u32({ + let idx = self.idx; + self.idx += 1; + idx + }), + }, + ) } else { c.super_fold_with(self) } diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 537b042bde5..de5aaa5bd97 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -1670,14 +1670,18 @@ fn confirm_closure_candidate<'cx, 'tcx>( } else { let upvars_projection_def_id = tcx.require_lang_item(LangItem::AsyncFnKindUpvars, None); - let tupled_upvars_ty = Ty::new_projection(tcx, upvars_projection_def_id, [ - ty::GenericArg::from(kind_ty), - Ty::from_closure_kind(tcx, ty::ClosureKind::FnOnce).into(), - tcx.lifetimes.re_static.into(), - sig.tupled_inputs_ty.into(), - args.tupled_upvars_ty().into(), - args.coroutine_captures_by_ref_ty().into(), - ]); + let tupled_upvars_ty = Ty::new_projection( + tcx, + upvars_projection_def_id, + [ + ty::GenericArg::from(kind_ty), + Ty::from_closure_kind(tcx, ty::ClosureKind::FnOnce).into(), + tcx.lifetimes.re_static.into(), + sig.tupled_inputs_ty.into(), + args.tupled_upvars_ty().into(), + args.coroutine_captures_by_ref_ty().into(), + ], + ); sig.to_coroutine( tcx, args.parent_args(), @@ -1795,14 +1799,18 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( // will project to the right upvars for the generator, appending the inputs and // coroutine upvars respecting the closure kind. // N.B. No need to register a `AsyncFnKindHelper` goal here, it's already in `nested`. - let tupled_upvars_ty = Ty::new_projection(tcx, upvars_projection_def_id, [ - ty::GenericArg::from(kind_ty), - Ty::from_closure_kind(tcx, goal_kind).into(), - env_region.into(), - sig.tupled_inputs_ty.into(), - args.tupled_upvars_ty().into(), - args.coroutine_captures_by_ref_ty().into(), - ]); + let tupled_upvars_ty = Ty::new_projection( + tcx, + upvars_projection_def_id, + [ + ty::GenericArg::from(kind_ty), + Ty::from_closure_kind(tcx, goal_kind).into(), + env_region.into(), + sig.tupled_inputs_ty.into(), + args.tupled_upvars_ty().into(), + args.coroutine_captures_by_ref_ty().into(), + ], + ); sig.to_coroutine( tcx, args.parent_args(), @@ -1816,17 +1824,16 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( name => bug!("no such associated type: {name}"), }; let projection_term = match item_name { - sym::CallOnceFuture | sym::Output => { - ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ - self_ty, - sig.tupled_inputs_ty, - ]) - } - sym::CallRefFuture => ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ - ty::GenericArg::from(self_ty), - sig.tupled_inputs_ty.into(), - env_region.into(), - ]), + sym::CallOnceFuture | sym::Output => ty::AliasTerm::new( + tcx, + obligation.predicate.def_id, + [self_ty, sig.tupled_inputs_ty], + ), + sym::CallRefFuture => ty::AliasTerm::new( + tcx, + obligation.predicate.def_id, + [ty::GenericArg::from(self_ty), sig.tupled_inputs_ty.into(), env_region.into()], + ), name => bug!("no such associated type: {name}"), }; @@ -1846,17 +1853,20 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( name => bug!("no such associated type: {name}"), }; let projection_term = match item_name { - sym::CallOnceFuture | sym::Output => { - ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ - self_ty, - Ty::new_tup(tcx, sig.inputs()), - ]) - } - sym::CallRefFuture => ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ - ty::GenericArg::from(self_ty), - Ty::new_tup(tcx, sig.inputs()).into(), - env_region.into(), - ]), + sym::CallOnceFuture | sym::Output => ty::AliasTerm::new( + tcx, + obligation.predicate.def_id, + [self_ty, Ty::new_tup(tcx, sig.inputs())], + ), + sym::CallRefFuture => ty::AliasTerm::new( + tcx, + obligation.predicate.def_id, + [ + ty::GenericArg::from(self_ty), + Ty::new_tup(tcx, sig.inputs()).into(), + env_region.into(), + ], + ), name => bug!("no such associated type: {name}"), }; @@ -1879,11 +1889,11 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( sym::CallOnceFuture | sym::Output => { ty::AliasTerm::new(tcx, obligation.predicate.def_id, [self_ty, sig.inputs()[0]]) } - sym::CallRefFuture => ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ - ty::GenericArg::from(self_ty), - sig.inputs()[0].into(), - env_region.into(), - ]), + sym::CallRefFuture => ty::AliasTerm::new( + tcx, + obligation.predicate.def_id, + [ty::GenericArg::from(self_ty), sig.inputs()[0].into(), env_region.into()], + ), name => bug!("no such associated type: {name}"), }; diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 729ae3f2c2a..eb4adde716a 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -301,11 +301,15 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let make_transmute_obl = |src, dst| { let transmute_trait = obligation.predicate.def_id(); let assume = obligation.predicate.skip_binder().trait_ref.args.const_at(2); - let trait_ref = ty::TraitRef::new(tcx, transmute_trait, [ - ty::GenericArg::from(dst), - ty::GenericArg::from(src), - ty::GenericArg::from(assume), - ]); + let trait_ref = ty::TraitRef::new( + tcx, + transmute_trait, + [ + ty::GenericArg::from(dst), + ty::GenericArg::from(src), + ty::GenericArg::from(assume), + ], + ); Obligation::with_depth( tcx, obligation.cause.clone(), @@ -316,10 +320,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }; let make_freeze_obl = |ty| { - let trait_ref = - ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Freeze, None), [ - ty::GenericArg::from(ty), - ]); + let trait_ref = ty::TraitRef::new( + tcx, + tcx.require_lang_item(LangItem::Freeze, None), + [ty::GenericArg::from(ty)], + ); Obligation::with_depth( tcx, obligation.cause.clone(), @@ -863,10 +868,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } ty::CoroutineClosure(_, args) => { args.as_coroutine_closure().coroutine_closure_sig().map_bound(|sig| { - ty::TraitRef::new(self.tcx(), obligation.predicate.def_id(), [ - self_ty, - sig.tupled_inputs_ty, - ]) + ty::TraitRef::new( + self.tcx(), + obligation.predicate.def_id(), + [self_ty, sig.tupled_inputs_ty], + ) }) } _ => { @@ -892,10 +898,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::CoroutineClosure(_, args) => { let args = args.as_coroutine_closure(); let trait_ref = args.coroutine_closure_sig().map_bound(|sig| { - ty::TraitRef::new(self.tcx(), obligation.predicate.def_id(), [ - self_ty, - sig.tupled_inputs_ty, - ]) + ty::TraitRef::new( + self.tcx(), + obligation.predicate.def_id(), + [self_ty, sig.tupled_inputs_ty], + ) }); // Note that unlike below, we don't need to check `Future + Sized` for @@ -906,10 +913,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::FnDef(..) | ty::FnPtr(..) => { let sig = self_ty.fn_sig(tcx); let trait_ref = sig.map_bound(|sig| { - ty::TraitRef::new(self.tcx(), obligation.predicate.def_id(), [ - self_ty, - Ty::new_tup(tcx, sig.inputs()), - ]) + ty::TraitRef::new( + self.tcx(), + obligation.predicate.def_id(), + [self_ty, Ty::new_tup(tcx, sig.inputs())], + ) }); // We must additionally check that the return type impls `Future + Sized`. @@ -934,10 +942,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let args = args.as_closure(); let sig = args.sig(); let trait_ref = sig.map_bound(|sig| { - ty::TraitRef::new(self.tcx(), obligation.predicate.def_id(), [ - self_ty, - sig.inputs()[0], - ]) + ty::TraitRef::new( + self.tcx(), + obligation.predicate.def_id(), + [self_ty, sig.inputs()[0]], + ) }); // We must additionally check that the return type impls `Future + Sized`. @@ -1295,10 +1304,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // Construct the nested `TailField: Unsize>` predicate. let tail_unsize_obligation = obligation.with( tcx, - ty::TraitRef::new(tcx, obligation.predicate.def_id(), [ - source_tail, - target_tail, - ]), + ty::TraitRef::new( + tcx, + obligation.predicate.def_id(), + [source_tail, target_tail], + ), ); nested.push(tail_unsize_obligation); @@ -1359,10 +1369,11 @@ fn pointer_like_goal_for_rpitit<'tcx>( ty::GenericParamDefKind::Lifetime => { let kind = ty::BoundRegionKind::Named(arg.def_id, tcx.item_name(arg.def_id)); bound_vars.push(ty::BoundVariableKind::Region(kind)); - ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { - var: ty::BoundVar::from_usize(bound_vars.len() - 1), - kind, - }) + ty::Region::new_bound( + tcx, + ty::INNERMOST, + ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind }, + ) .into() } ty::GenericParamDefKind::Type { .. } | ty::GenericParamDefKind::Const { .. } => { @@ -1371,9 +1382,11 @@ fn pointer_like_goal_for_rpitit<'tcx>( }); ty::Binder::bind_with_vars( - ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::PointerLike, Some(cause.span)), [ - Ty::new_projection_from_args(tcx, rpitit_item, args), - ]), + ty::TraitRef::new( + tcx, + tcx.require_lang_item(LangItem::PointerLike, Some(cause.span)), + [Ty::new_projection_from_args(tcx, rpitit_item, args)], + ), tcx.mk_bound_variable_kinds(&bound_vars), ) } diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 99ce1fd9fb4..6b1e1774f03 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2422,9 +2422,11 @@ impl<'tcx> SelectionContext<'_, 'tcx> { } else { // If this is an ill-formed auto/built-in trait, then synthesize // new error args for the missing generics. - let err_args = ty::GenericArgs::extend_with_error(tcx, trait_def_id, &[ - normalized_ty.into(), - ]); + let err_args = ty::GenericArgs::extend_with_error( + tcx, + trait_def_id, + &[normalized_ty.into()], + ); ty::TraitRef::new_from_args(tcx, trait_def_id, err_args) }; diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index c4637f1293c..cc7baf8daac 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -79,10 +79,10 @@ fn assumed_wf_types<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx [(Ty<' if matches!(*orig_lt, ty::ReLateParam(..)) { mapping.insert( orig_lt, - ty::Region::new_early_param(tcx, ty::EarlyParamRegion { - index: param.index, - name: param.name, - }), + ty::Region::new_early_param( + tcx, + ty::EarlyParamRegion { index: param.index, name: param.name }, + ), ); } } diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 2f258b23f2d..ce8dc3a2515 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -240,14 +240,20 @@ fn layout_of_uncached<'tcx>( } // Basic scalars. - ty::Bool => tcx.mk_layout(LayoutData::scalar(cx, Scalar::Initialized { - value: Int(I8, false), - valid_range: WrappingRange { start: 0, end: 1 }, - })), - ty::Char => tcx.mk_layout(LayoutData::scalar(cx, Scalar::Initialized { - value: Int(I32, false), - valid_range: WrappingRange { start: 0, end: 0x10FFFF }, - })), + ty::Bool => tcx.mk_layout(LayoutData::scalar( + cx, + Scalar::Initialized { + value: Int(I8, false), + valid_range: WrappingRange { start: 0, end: 1 }, + }, + )), + ty::Char => tcx.mk_layout(LayoutData::scalar( + cx, + Scalar::Initialized { + value: Int(I32, false), + valid_range: WrappingRange { start: 0, end: 0x10FFFF }, + }, + )), ty::Int(ity) => scalar(Int(abi::Integer::from_int_ty(dl, ity), true)), ty::Uint(ity) => scalar(Int(abi::Integer::from_uint_ty(dl, ity), false)), ty::Float(fty) => scalar(Float(abi::Float::from_float_ty(fty))), @@ -551,10 +557,13 @@ fn layout_of_uncached<'tcx>( // Non-power-of-two vectors have padding up to the next power-of-two. // If we're a packed repr, remove the padding while keeping the alignment as close // to a vector as possible. - (BackendRepr::Memory { sized: true }, AbiAndPrefAlign { - abi: Align::max_for_offset(size), - pref: dl.vector_align(size).pref, - }) + ( + BackendRepr::Memory { sized: true }, + AbiAndPrefAlign { + abi: Align::max_for_offset(size), + pref: dl.vector_align(size).pref, + }, + ) } else { (BackendRepr::Vector { element: e_abi, count: e_len }, dl.vector_align(size)) }; @@ -1179,10 +1188,13 @@ fn variant_info_for_adt<'tcx>( }) .collect(); - (variant_infos, match tag_encoding { - TagEncoding::Direct => Some(tag.size(cx)), - _ => None, - }) + ( + variant_infos, + match tag_encoding { + TagEncoding::Direct => Some(tag.size(cx)), + _ => None, + }, + ) } } } @@ -1302,8 +1314,11 @@ fn variant_info_for_coroutine<'tcx>( let end_states: Vec<_> = end_states.collect(); variant_infos.extend(end_states); - (variant_infos, match tag_encoding { - TagEncoding::Direct => Some(tag.size(cx)), - _ => None, - }) + ( + variant_infos, + match tag_encoding { + TagEncoding::Direct => Some(tag.size(cx)), + _ => None, + }, + ) } diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index f75b2927600..51790b13ec7 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -552,35 +552,29 @@ impl AliasTerm { pub fn to_term(self, interner: I) -> I::Term { match self.kind(interner) { - AliasTermKind::ProjectionTy => { - Ty::new_alias(interner, ty::AliasTyKind::Projection, ty::AliasTy { - def_id: self.def_id, - args: self.args, - _use_alias_ty_new_instead: (), - }) - .into() - } - AliasTermKind::InherentTy => { - Ty::new_alias(interner, ty::AliasTyKind::Inherent, ty::AliasTy { - def_id: self.def_id, - args: self.args, - _use_alias_ty_new_instead: (), - }) - .into() - } - AliasTermKind::OpaqueTy => { - Ty::new_alias(interner, ty::AliasTyKind::Opaque, ty::AliasTy { - def_id: self.def_id, - args: self.args, - _use_alias_ty_new_instead: (), - }) - .into() - } - AliasTermKind::WeakTy => Ty::new_alias(interner, ty::AliasTyKind::Weak, ty::AliasTy { - def_id: self.def_id, - args: self.args, - _use_alias_ty_new_instead: (), - }) + AliasTermKind::ProjectionTy => Ty::new_alias( + interner, + ty::AliasTyKind::Projection, + ty::AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () }, + ) + .into(), + AliasTermKind::InherentTy => Ty::new_alias( + interner, + ty::AliasTyKind::Inherent, + ty::AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () }, + ) + .into(), + AliasTermKind::OpaqueTy => Ty::new_alias( + interner, + ty::AliasTyKind::Opaque, + ty::AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () }, + ) + .into(), + AliasTermKind::WeakTy => Ty::new_alias( + interner, + ty::AliasTyKind::Weak, + ty::AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () }, + ) .into(), AliasTermKind::UnevaluatedConst | AliasTermKind::ProjectionConst => { I::Const::new_unevaluated( diff --git a/compiler/rustc_type_ir/src/ty_kind/closure.rs b/compiler/rustc_type_ir/src/ty_kind/closure.rs index 74e4e035c87..d1ca9bdb7fb 100644 --- a/compiler/rustc_type_ir/src/ty_kind/closure.rs +++ b/compiler/rustc_type_ir/src/ty_kind/closure.rs @@ -399,15 +399,18 @@ impl CoroutineClosureSignature { coroutine_def_id: I::DefId, tupled_upvars_ty: I::Ty, ) -> I::Ty { - let coroutine_args = ty::CoroutineArgs::new(cx, ty::CoroutineArgsParts { - parent_args, - kind_ty: coroutine_kind_ty, - resume_ty: self.resume_ty, - yield_ty: self.yield_ty, - return_ty: self.return_ty, - witness: self.interior, - tupled_upvars_ty, - }); + let coroutine_args = ty::CoroutineArgs::new( + cx, + ty::CoroutineArgsParts { + parent_args, + kind_ty: coroutine_kind_ty, + resume_ty: self.resume_ty, + yield_ty: self.yield_ty, + return_ty: self.return_ty, + witness: self.interior, + tupled_upvars_ty, + }, + ); Ty::new_coroutine(cx, coroutine_def_id, coroutine_args.args) } diff --git a/compiler/rustc_type_ir_macros/src/lib.rs b/compiler/rustc_type_ir_macros/src/lib.rs index aaf69e2648d..ede6dcd469c 100644 --- a/compiler/rustc_type_ir_macros/src/lib.rs +++ b/compiler/rustc_type_ir_macros/src/lib.rs @@ -57,15 +57,18 @@ fn type_visitable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Tok }); s.bind_with(|_| synstructure::BindStyle::Move); - s.bound_impl(quote!(::rustc_type_ir::visit::TypeVisitable), quote! { - fn visit_with<__V: ::rustc_type_ir::visit::TypeVisitor>( - &self, - __visitor: &mut __V - ) -> __V::Result { - match *self { #body_visit } - <__V::Result as ::rustc_ast_ir::visit::VisitorResult>::output() - } - }) + s.bound_impl( + quote!(::rustc_type_ir::visit::TypeVisitable), + quote! { + fn visit_with<__V: ::rustc_type_ir::visit::TypeVisitor>( + &self, + __visitor: &mut __V + ) -> __V::Result { + match *self { #body_visit } + <__V::Result as ::rustc_ast_ir::visit::VisitorResult>::output() + } + }, + ) } fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { @@ -101,14 +104,17 @@ fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Toke // to generate code for them. s.filter(|bi| !has_ignore_attr(&bi.ast().attrs, "type_foldable", "identity")); s.add_bounds(synstructure::AddBounds::Fields); - s.bound_impl(quote!(::rustc_type_ir::fold::TypeFoldable), quote! { - fn try_fold_with<__F: ::rustc_type_ir::fold::FallibleTypeFolder>( - self, - __folder: &mut __F - ) -> Result { - Ok(match self { #body_fold }) - } - }) + s.bound_impl( + quote!(::rustc_type_ir::fold::TypeFoldable), + quote! { + fn try_fold_with<__F: ::rustc_type_ir::fold::FallibleTypeFolder>( + self, + __folder: &mut __F + ) -> Result { + Ok(match self { #body_fold }) + } + }, + ) } fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { @@ -148,16 +154,19 @@ fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { let self_ty: syn::Type = parse_quote! { #name #ty_generics }; let lifted_ty = lift(self_ty); - s.bound_impl(quote!(::rustc_type_ir::lift::Lift), quote! { - type Lifted = #lifted_ty; + s.bound_impl( + quote!(::rustc_type_ir::lift::Lift), + quote! { + type Lifted = #lifted_ty; - fn lift_to_interner( - self, - interner: J, - ) -> Option { - Some(match self { #body_fold }) - } - }) + fn lift_to_interner( + self, + interner: J, + ) -> Option { + Some(match self { #body_fold }) + } + }, + ) } fn lift(mut ty: syn::Type) -> syn::Type { diff --git a/library/alloc/src/collections/btree/set/tests.rs b/library/alloc/src/collections/btree/set/tests.rs index 990044e069f..d538ef707eb 100644 --- a/library/alloc/src/collections/btree/set/tests.rs +++ b/library/alloc/src/collections/btree/set/tests.rs @@ -132,9 +132,11 @@ fn test_difference() { check_difference(&[1, 3, 5, 9, 11], &[3, 6, 9], &[1, 5, 11]); check_difference(&[1, 3, 5, 9, 11], &[0, 1], &[3, 5, 9, 11]); check_difference(&[1, 3, 5, 9, 11], &[11, 12], &[1, 3, 5, 9]); - check_difference(&[-5, 11, 22, 33, 40, 42], &[-12, -5, 14, 23, 34, 38, 39, 50], &[ - 11, 22, 33, 40, 42, - ]); + check_difference( + &[-5, 11, 22, 33, 40, 42], + &[-12, -5, 14, 23, 34, 38, 39, 50], + &[11, 22, 33, 40, 42], + ); if cfg!(miri) { // Miri is too slow @@ -250,9 +252,11 @@ fn test_union() { check_union(&[], &[], &[]); check_union(&[1, 2, 3], &[2], &[1, 2, 3]); check_union(&[2], &[1, 2, 3], &[1, 2, 3]); - check_union(&[1, 3, 5, 9, 11, 16, 19, 24], &[-2, 1, 5, 9, 13, 19], &[ - -2, 1, 3, 5, 9, 11, 13, 16, 19, 24, - ]); + check_union( + &[1, 3, 5, 9, 11, 16, 19, 24], + &[-2, 1, 5, 9, 13, 19], + &[-2, 1, 3, 5, 9, 11, 13, 16, 19, 24], + ); } #[test] diff --git a/library/alloc/src/collections/linked_list/tests.rs b/library/alloc/src/collections/linked_list/tests.rs index aa19239f6c5..812fe229a0f 100644 --- a/library/alloc/src/collections/linked_list/tests.rs +++ b/library/alloc/src/collections/linked_list/tests.rs @@ -696,9 +696,10 @@ fn test_cursor_mut_insert() { cursor.splice_after(p); cursor.splice_before(q); check_links(&m); - assert_eq!(m.iter().cloned().collect::>(), &[ - 200, 201, 202, 203, 1, 100, 101, 102, 103, 8, 2, 3, 4, 5, 6 - ]); + assert_eq!( + m.iter().cloned().collect::>(), + &[200, 201, 202, 203, 1, 100, 101, 102, 103, 8, 2, 3, 4, 5, 6] + ); let mut cursor = m.cursor_front_mut(); cursor.move_prev(); let tmp = cursor.split_before(); @@ -915,9 +916,10 @@ fn extract_if_complex() { assert_eq!(removed, vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]); assert_eq!(list.len(), 14); - assert_eq!(list.into_iter().collect::>(), vec![ - 1, 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39 - ]); + assert_eq!( + list.into_iter().collect::>(), + vec![1, 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39] + ); } { @@ -932,9 +934,10 @@ fn extract_if_complex() { assert_eq!(removed, vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]); assert_eq!(list.len(), 13); - assert_eq!(list.into_iter().collect::>(), vec![ - 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39 - ]); + assert_eq!( + list.into_iter().collect::>(), + vec![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39] + ); } { @@ -949,9 +952,10 @@ fn extract_if_complex() { assert_eq!(removed, vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]); assert_eq!(list.len(), 11); - assert_eq!(list.into_iter().collect::>(), vec![ - 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35 - ]); + assert_eq!( + list.into_iter().collect::>(), + vec![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35] + ); } { diff --git a/library/alloc/src/collections/vec_deque/tests.rs b/library/alloc/src/collections/vec_deque/tests.rs index 6328b3b4db8..c90679f1797 100644 --- a/library/alloc/src/collections/vec_deque/tests.rs +++ b/library/alloc/src/collections/vec_deque/tests.rs @@ -562,9 +562,10 @@ fn make_contiguous_head_to_end() { tester.push_front(i as char); } - assert_eq!(tester, [ - 'P', 'O', 'N', 'M', 'L', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K' - ]); + assert_eq!( + tester, + ['P', 'O', 'N', 'M', 'L', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'] + ); // ABCDEFGHIJKPONML let expected_start = 0; diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index ae3318b839d..3c73469e90b 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -2350,11 +2350,10 @@ impl Default for Rc { fn default() -> Rc { unsafe { Self::from_inner( - Box::leak(Box::write(Box::new_uninit(), RcInner { - strong: Cell::new(1), - weak: Cell::new(1), - value: T::default(), - })) + Box::leak(Box::write( + Box::new_uninit(), + RcInner { strong: Cell::new(1), weak: Cell::new(1), value: T::default() }, + )) .into(), ) } diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 431e19e6ef1..dba1449347a 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -3466,11 +3466,14 @@ impl Default for Arc { fn default() -> Arc { unsafe { Self::from_inner( - Box::leak(Box::write(Box::new_uninit(), ArcInner { - strong: atomic::AtomicUsize::new(1), - weak: atomic::AtomicUsize::new(1), - data: T::default(), - })) + Box::leak(Box::write( + Box::new_uninit(), + ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data: T::default(), + }, + )) .into(), ) } diff --git a/library/alloc/tests/str.rs b/library/alloc/tests/str.rs index 5720d3ffd97..23a0e5e5256 100644 --- a/library/alloc/tests/str.rs +++ b/library/alloc/tests/str.rs @@ -1524,18 +1524,14 @@ fn test_lines() { t("bare\r", &["bare\r"]); t("bare\rcr", &["bare\rcr"]); t("Text\n\r", &["Text", "\r"]); - t("\nMäry häd ä little lämb\n\r\nLittle lämb\n", &[ - "", - "Märy häd ä little lämb", - "", - "Little lämb", - ]); - t("\r\nMäry häd ä little lämb\n\nLittle lämb", &[ - "", - "Märy häd ä little lämb", - "", - "Little lämb", - ]); + t( + "\nMäry häd ä little lämb\n\r\nLittle lämb\n", + &["", "Märy häd ä little lämb", "", "Little lämb"], + ); + t( + "\r\nMäry häd ä little lämb\n\nLittle lämb", + &["", "Märy häd ä little lämb", "", "Little lämb"], + ); } #[test] @@ -1978,73 +1974,88 @@ mod pattern { assert_eq!(v, right); } - make_test!(str_searcher_ascii_haystack, "bb", "abbcbbd", [ - Reject(0, 1), - Match(1, 3), - Reject(3, 4), - Match(4, 6), - Reject(6, 7), - ]); - make_test!(str_searcher_ascii_haystack_seq, "bb", "abbcbbbbd", [ - Reject(0, 1), - Match(1, 3), - Reject(3, 4), - Match(4, 6), - Match(6, 8), - Reject(8, 9), - ]); - make_test!(str_searcher_empty_needle_ascii_haystack, "", "abbcbbd", [ - Match(0, 0), - Reject(0, 1), - Match(1, 1), - Reject(1, 2), - Match(2, 2), - Reject(2, 3), - Match(3, 3), - Reject(3, 4), - Match(4, 4), - Reject(4, 5), - Match(5, 5), - Reject(5, 6), - Match(6, 6), - Reject(6, 7), - Match(7, 7), - ]); - make_test!(str_searcher_multibyte_haystack, " ", "├──", [ - Reject(0, 3), - Reject(3, 6), - Reject(6, 9), - ]); - make_test!(str_searcher_empty_needle_multibyte_haystack, "", "├──", [ - Match(0, 0), - Reject(0, 3), - Match(3, 3), - Reject(3, 6), - Match(6, 6), - Reject(6, 9), - Match(9, 9), - ]); + make_test!( + str_searcher_ascii_haystack, + "bb", + "abbcbbd", + [Reject(0, 1), Match(1, 3), Reject(3, 4), Match(4, 6), Reject(6, 7),] + ); + make_test!( + str_searcher_ascii_haystack_seq, + "bb", + "abbcbbbbd", + [Reject(0, 1), Match(1, 3), Reject(3, 4), Match(4, 6), Match(6, 8), Reject(8, 9),] + ); + make_test!( + str_searcher_empty_needle_ascii_haystack, + "", + "abbcbbd", + [ + Match(0, 0), + Reject(0, 1), + Match(1, 1), + Reject(1, 2), + Match(2, 2), + Reject(2, 3), + Match(3, 3), + Reject(3, 4), + Match(4, 4), + Reject(4, 5), + Match(5, 5), + Reject(5, 6), + Match(6, 6), + Reject(6, 7), + Match(7, 7), + ] + ); + make_test!( + str_searcher_multibyte_haystack, + " ", + "├──", + [Reject(0, 3), Reject(3, 6), Reject(6, 9),] + ); + make_test!( + str_searcher_empty_needle_multibyte_haystack, + "", + "├──", + [ + Match(0, 0), + Reject(0, 3), + Match(3, 3), + Reject(3, 6), + Match(6, 6), + Reject(6, 9), + Match(9, 9), + ] + ); make_test!(str_searcher_empty_needle_empty_haystack, "", "", [Match(0, 0),]); make_test!(str_searcher_nonempty_needle_empty_haystack, "├", "", []); - make_test!(char_searcher_ascii_haystack, 'b', "abbcbbd", [ - Reject(0, 1), - Match(1, 2), - Match(2, 3), - Reject(3, 4), - Match(4, 5), - Match(5, 6), - Reject(6, 7), - ]); - make_test!(char_searcher_multibyte_haystack, ' ', "├──", [ - Reject(0, 3), - Reject(3, 6), - Reject(6, 9), - ]); - make_test!(char_searcher_short_haystack, '\u{1F4A9}', "* \t", [ - Reject(0, 1), - Reject(1, 2), - Reject(2, 3), - ]); + make_test!( + char_searcher_ascii_haystack, + 'b', + "abbcbbd", + [ + Reject(0, 1), + Match(1, 2), + Match(2, 3), + Reject(3, 4), + Match(4, 5), + Match(5, 6), + Reject(6, 7), + ] + ); + make_test!( + char_searcher_multibyte_haystack, + ' ', + "├──", + [Reject(0, 3), Reject(3, 6), Reject(6, 9),] + ); + make_test!( + char_searcher_short_haystack, + '\u{1F4A9}', + "* \t", + [Reject(0, 1), Reject(1, 2), Reject(2, 3),] + ); // See #85462 #[test] diff --git a/library/alloc/tests/string.rs b/library/alloc/tests/string.rs index 1c8bff1564d..d996c55f946 100644 --- a/library/alloc/tests/string.rs +++ b/library/alloc/tests/string.rs @@ -154,19 +154,28 @@ fn test_fromutf8error_into_lossy() { #[test] fn test_from_utf16() { let pairs = [ - (String::from("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"), vec![ - 0xd800, 0xdf45, 0xd800, 0xdf3f, 0xd800, 0xdf3b, 0xd800, 0xdf46, 0xd800, 0xdf39, 0xd800, - 0xdf3b, 0xd800, 0xdf30, 0x000a, - ]), - (String::from("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"), vec![ - 0xd801, 0xdc12, 0xd801, 0xdc49, 0xd801, 0xdc2e, 0xd801, 0xdc40, 0xd801, 0xdc32, 0xd801, - 0xdc4b, 0x0020, 0xd801, 0xdc0f, 0xd801, 0xdc32, 0xd801, 0xdc4d, 0x000a, - ]), - (String::from("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"), vec![ - 0xd800, 0xdf00, 0xd800, 0xdf16, 0xd800, 0xdf0b, 0xd800, 0xdf04, 0xd800, 0xdf11, 0xd800, - 0xdf09, 0x00b7, 0xd800, 0xdf0c, 0xd800, 0xdf04, 0xd800, 0xdf15, 0xd800, 0xdf04, 0xd800, - 0xdf0b, 0xd800, 0xdf09, 0xd800, 0xdf11, 0x000a, - ]), + ( + String::from("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"), + vec![ + 0xd800, 0xdf45, 0xd800, 0xdf3f, 0xd800, 0xdf3b, 0xd800, 0xdf46, 0xd800, 0xdf39, + 0xd800, 0xdf3b, 0xd800, 0xdf30, 0x000a, + ], + ), + ( + String::from("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"), + vec![ + 0xd801, 0xdc12, 0xd801, 0xdc49, 0xd801, 0xdc2e, 0xd801, 0xdc40, 0xd801, 0xdc32, + 0xd801, 0xdc4b, 0x0020, 0xd801, 0xdc0f, 0xd801, 0xdc32, 0xd801, 0xdc4d, 0x000a, + ], + ), + ( + String::from("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"), + vec![ + 0xd800, 0xdf00, 0xd800, 0xdf16, 0xd800, 0xdf0b, 0xd800, 0xdf04, 0xd800, 0xdf11, + 0xd800, 0xdf09, 0x00b7, 0xd800, 0xdf0c, 0xd800, 0xdf04, 0xd800, 0xdf15, 0xd800, + 0xdf04, 0xd800, 0xdf0b, 0xd800, 0xdf09, 0xd800, 0xdf11, 0x000a, + ], + ), ( String::from("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"), vec![ diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index 320d8176011..cbf00106c51 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -1590,10 +1590,10 @@ impl<'b, T: ?Sized> Ref<'b, T> { { let (a, b) = f(&*orig); let borrow = orig.borrow.clone(); - (Ref { value: NonNull::from(a), borrow }, Ref { - value: NonNull::from(b), - borrow: orig.borrow, - }) + ( + Ref { value: NonNull::from(a), borrow }, + Ref { value: NonNull::from(b), borrow: orig.borrow }, + ) } /// Converts into a reference to the underlying data. @@ -1758,11 +1758,10 @@ impl<'b, T: ?Sized> RefMut<'b, T> { { let borrow = orig.borrow.clone(); let (a, b) = f(&mut *orig); - (RefMut { value: NonNull::from(a), borrow, marker: PhantomData }, RefMut { - value: NonNull::from(b), - borrow: orig.borrow, - marker: PhantomData, - }) + ( + RefMut { value: NonNull::from(a), borrow, marker: PhantomData }, + RefMut { value: NonNull::from(b), borrow: orig.borrow, marker: PhantomData }, + ) } /// Converts into a mutable reference to the underlying data. diff --git a/library/coretests/tests/iter/adapters/map_windows.rs b/library/coretests/tests/iter/adapters/map_windows.rs index b677f1cfd55..01cebc9b27f 100644 --- a/library/coretests/tests/iter/adapters/map_windows.rs +++ b/library/coretests/tests/iter/adapters/map_windows.rs @@ -159,11 +159,10 @@ fn output_n2() { >::new(), ); assert_eq!("ab".chars().map_windows(|a: &[_; 2]| *a).collect::>(), vec![['a', 'b']]); - assert_eq!("abcd".chars().map_windows(|a: &[_; 2]| *a).collect::>(), vec![ - ['a', 'b'], - ['b', 'c'], - ['c', 'd'] - ],); + assert_eq!( + "abcd".chars().map_windows(|a: &[_; 2]| *a).collect::>(), + vec![['a', 'b'], ['b', 'c'], ['c', 'd']], + ); } #[test] diff --git a/library/panic_unwind/src/emcc.rs b/library/panic_unwind/src/emcc.rs index 9127449edb1..86906b46d66 100644 --- a/library/panic_unwind/src/emcc.rs +++ b/library/panic_unwind/src/emcc.rs @@ -98,11 +98,14 @@ pub(crate) unsafe fn panic(data: Box) -> u32 { if exception.is_null() { return uw::_URC_FATAL_PHASE1_ERROR as u32; } - ptr::write(exception, Exception { - canary: &EXCEPTION_TYPE_INFO, - caught: AtomicBool::new(false), - data: Some(data), - }); + ptr::write( + exception, + Exception { + canary: &EXCEPTION_TYPE_INFO, + caught: AtomicBool::new(false), + data: Some(data), + }, + ); __cxa_throw(exception as *mut _, &EXCEPTION_TYPE_INFO, exception_cleanup); } diff --git a/library/std/src/io/stdio/tests.rs b/library/std/src/io/stdio/tests.rs index bf8f3a5adfb..e68d8c29fbc 100644 --- a/library/std/src/io/stdio/tests.rs +++ b/library/std/src/io/stdio/tests.rs @@ -159,7 +159,8 @@ where assert_eq!(rx2.recv().unwrap(), Release2); // release th2 th2.join().unwrap(); th1.join().unwrap(); - assert_eq!(*log.lock().unwrap(), [ - Start1, Acquire1, Start2, Release1, Acquire2, Release2, Acquire1, Release1 - ]); + assert_eq!( + *log.lock().unwrap(), + [Start1, Acquire1, Start2, Release1, Acquire2, Release2, Acquire1, Release1] + ); } diff --git a/library/std/src/os/windows/process.rs b/library/std/src/os/windows/process.rs index 0277b79b8b6..201274cf03a 100644 --- a/library/std/src/os/windows/process.rs +++ b/library/std/src/os/windows/process.rs @@ -590,10 +590,10 @@ impl<'a> ProcThreadAttributeListBuilder<'a> { value_ptr: *const T, value_size: usize, ) -> Self { - self.attributes.insert(attribute, ProcThreadAttributeValue { - ptr: value_ptr.cast::(), - size: value_size, - }); + self.attributes.insert( + attribute, + ProcThreadAttributeValue { ptr: value_ptr.cast::(), size: value_size }, + ); self } diff --git a/library/std/src/os/xous/ffi/definitions.rs b/library/std/src/os/xous/ffi/definitions.rs index 1b16849af03..345005bcc78 100644 --- a/library/std/src/os/xous/ffi/definitions.rs +++ b/library/std/src/os/xous/ffi/definitions.rs @@ -126,36 +126,42 @@ impl From for Error { #[stable(feature = "rust1", since = "1.0.0")] impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!(f, "{}", match self { - Error::NoError => "no error occurred", - Error::BadAlignment => "memory was not properly aligned", - Error::BadAddress => "an invalid address was supplied", - Error::OutOfMemory => "the process or service has run out of memory", - Error::MemoryInUse => "the requested address is in use", - Error::InterruptNotFound => "the requested interrupt does not exist on this platform", - Error::InterruptInUse => "the requested interrupt is currently in use", - Error::InvalidString => "the specified string was not formatted correctly", - Error::ServerExists => "a server with that address already exists", - Error::ServerNotFound => "the requetsed server could not be found", - Error::ProcessNotFound => "the target process does not exist", - Error::ProcessNotChild => "the requested operation can only be done on child processes", - Error::ProcessTerminated => "the target process has crashed", - Error::Timeout => "the requested operation timed out", - Error::InternalError => "an internal error occurred", - Error::ServerQueueFull => "the server has too many pending messages", - Error::ThreadNotAvailable => "the specified thread does not exist", - Error::UnhandledSyscall => "the kernel did not recognize that syscall", - Error::InvalidSyscall => "the syscall had incorrect parameters", - Error::ShareViolation => "an attempt was made to share memory twice", - Error::InvalidThread => "tried to resume a thread that was not ready", - Error::InvalidPid => "kernel attempted to use a pid that was not valid", - Error::AccessDenied => "no permission to perform the requested operation", - Error::UseBeforeInit => "attempt to use a service before initialization finished", - Error::DoubleFree => "the requested resource was freed twice", - Error::DebugInProgress => "kernel attempted to activate a thread being debugged", - Error::InvalidLimit => "process attempted to adjust an invalid limit", - Error::UnknownError => "an unknown error occurred", - }) + write!( + f, + "{}", + match self { + Error::NoError => "no error occurred", + Error::BadAlignment => "memory was not properly aligned", + Error::BadAddress => "an invalid address was supplied", + Error::OutOfMemory => "the process or service has run out of memory", + Error::MemoryInUse => "the requested address is in use", + Error::InterruptNotFound => + "the requested interrupt does not exist on this platform", + Error::InterruptInUse => "the requested interrupt is currently in use", + Error::InvalidString => "the specified string was not formatted correctly", + Error::ServerExists => "a server with that address already exists", + Error::ServerNotFound => "the requetsed server could not be found", + Error::ProcessNotFound => "the target process does not exist", + Error::ProcessNotChild => + "the requested operation can only be done on child processes", + Error::ProcessTerminated => "the target process has crashed", + Error::Timeout => "the requested operation timed out", + Error::InternalError => "an internal error occurred", + Error::ServerQueueFull => "the server has too many pending messages", + Error::ThreadNotAvailable => "the specified thread does not exist", + Error::UnhandledSyscall => "the kernel did not recognize that syscall", + Error::InvalidSyscall => "the syscall had incorrect parameters", + Error::ShareViolation => "an attempt was made to share memory twice", + Error::InvalidThread => "tried to resume a thread that was not ready", + Error::InvalidPid => "kernel attempted to use a pid that was not valid", + Error::AccessDenied => "no permission to perform the requested operation", + Error::UseBeforeInit => "attempt to use a service before initialization finished", + Error::DoubleFree => "the requested resource was freed twice", + Error::DebugInProgress => "kernel attempted to activate a thread being debugged", + Error::InvalidLimit => "process attempted to adjust an invalid limit", + Error::UnknownError => "an unknown error occurred", + } + ) } } diff --git a/library/std/src/sys/pal/itron/time/tests.rs b/library/std/src/sys/pal/itron/time/tests.rs index 28db4f8b679..d14035d9da4 100644 --- a/library/std/src/sys/pal/itron/time/tests.rs +++ b/library/std/src/sys/pal/itron/time/tests.rs @@ -8,24 +8,26 @@ fn reltim2dur(t: u64) -> Duration { fn test_dur2reltims() { assert_eq!(dur2reltims(reltim2dur(0)).collect::>(), vec![]); assert_eq!(dur2reltims(reltim2dur(42)).collect::>(), vec![42]); - assert_eq!(dur2reltims(reltim2dur(abi::TMAX_RELTIM as u64)).collect::>(), vec![ - abi::TMAX_RELTIM - ]); - assert_eq!(dur2reltims(reltim2dur(abi::TMAX_RELTIM as u64 + 10000)).collect::>(), vec![ - abi::TMAX_RELTIM, - 10000 - ]); + assert_eq!( + dur2reltims(reltim2dur(abi::TMAX_RELTIM as u64)).collect::>(), + vec![abi::TMAX_RELTIM] + ); + assert_eq!( + dur2reltims(reltim2dur(abi::TMAX_RELTIM as u64 + 10000)).collect::>(), + vec![abi::TMAX_RELTIM, 10000] + ); } #[test] fn test_dur2tmos() { assert_eq!(dur2tmos(reltim2dur(0)).collect::>(), vec![0]); assert_eq!(dur2tmos(reltim2dur(42)).collect::>(), vec![42]); - assert_eq!(dur2tmos(reltim2dur(abi::TMAX_RELTIM as u64)).collect::>(), vec![ - abi::TMAX_RELTIM - ]); - assert_eq!(dur2tmos(reltim2dur(abi::TMAX_RELTIM as u64 + 10000)).collect::>(), vec![ - abi::TMAX_RELTIM, - 10000 - ]); + assert_eq!( + dur2tmos(reltim2dur(abi::TMAX_RELTIM as u64)).collect::>(), + vec![abi::TMAX_RELTIM] + ); + assert_eq!( + dur2tmos(reltim2dur(abi::TMAX_RELTIM as u64 + 10000)).collect::>(), + vec![abi::TMAX_RELTIM, 10000] + ); } diff --git a/library/std/src/sys/pal/windows/args/tests.rs b/library/std/src/sys/pal/windows/args/tests.rs index 6d5c953cbd5..484a90ab056 100644 --- a/library/std/src/sys/pal/windows/args/tests.rs +++ b/library/std/src/sys/pal/windows/args/tests.rs @@ -47,10 +47,10 @@ fn whitespace_behavior() { fn genius_quotes() { chk(r#"EXE "" """#, &["EXE", "", ""]); chk(r#"EXE "" """"#, &["EXE", "", r#"""#]); - chk(r#"EXE "this is """all""" in the same argument""#, &[ - "EXE", - r#"this is "all" in the same argument"#, - ]); + chk( + r#"EXE "this is """all""" in the same argument""#, + &["EXE", r#"this is "all" in the same argument"#], + ); chk(r#"EXE "a"""#, &["EXE", r#"a""#]); chk(r#"EXE "a"" a"#, &["EXE", r#"a" a"#]); // quotes cannot be escaped in command names diff --git a/library/std/src/sys_common/wtf8/tests.rs b/library/std/src/sys_common/wtf8/tests.rs index bc06eaa2b8f..b57c99a8452 100644 --- a/library/std/src/sys_common/wtf8/tests.rs +++ b/library/std/src/sys_common/wtf8/tests.rs @@ -356,32 +356,32 @@ fn wtf8buf_from_iterator() { fn f(values: &[u32]) -> Wtf8Buf { values.iter().map(|&c| CodePoint::from_u32(c).unwrap()).collect::() } - assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]), Wtf8Buf { - bytes: b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec(), - is_known_utf8: true - }); + assert_eq!( + f(&[0x61, 0xE9, 0x20, 0x1F4A9]), + Wtf8Buf { bytes: b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec(), is_known_utf8: true } + ); assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! - assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]), Wtf8Buf { - bytes: b"\xED\xA0\xBD \xED\xB2\xA9".to_vec(), - is_known_utf8: false - }); - assert_eq!(f(&[0xD800, 0xDBFF]), Wtf8Buf { - bytes: b"\xED\xA0\x80\xED\xAF\xBF".to_vec(), - is_known_utf8: false - }); - assert_eq!(f(&[0xD800, 0xE000]), Wtf8Buf { - bytes: b"\xED\xA0\x80\xEE\x80\x80".to_vec(), - is_known_utf8: false - }); - assert_eq!(f(&[0xD7FF, 0xDC00]), Wtf8Buf { - bytes: b"\xED\x9F\xBF\xED\xB0\x80".to_vec(), - is_known_utf8: false - }); - assert_eq!(f(&[0x61, 0xDC00]), Wtf8Buf { - bytes: b"\x61\xED\xB0\x80".to_vec(), - is_known_utf8: false - }); + assert_eq!( + f(&[0xD83D, 0x20, 0xDCA9]), + Wtf8Buf { bytes: b"\xED\xA0\xBD \xED\xB2\xA9".to_vec(), is_known_utf8: false } + ); + assert_eq!( + f(&[0xD800, 0xDBFF]), + Wtf8Buf { bytes: b"\xED\xA0\x80\xED\xAF\xBF".to_vec(), is_known_utf8: false } + ); + assert_eq!( + f(&[0xD800, 0xE000]), + Wtf8Buf { bytes: b"\xED\xA0\x80\xEE\x80\x80".to_vec(), is_known_utf8: false } + ); + assert_eq!( + f(&[0xD7FF, 0xDC00]), + Wtf8Buf { bytes: b"\xED\x9F\xBF\xED\xB0\x80".to_vec(), is_known_utf8: false } + ); + assert_eq!( + f(&[0x61, 0xDC00]), + Wtf8Buf { bytes: b"\x61\xED\xB0\x80".to_vec(), is_known_utf8: false } + ); assert_eq!(f(&[0xDC00]), Wtf8Buf { bytes: b"\xED\xB0\x80".to_vec(), is_known_utf8: false }); } @@ -396,36 +396,36 @@ fn wtf8buf_extend() { string } - assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]), Wtf8Buf { - bytes: b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec(), - is_known_utf8: true - }); + assert_eq!( + e(&[0x61, 0xE9], &[0x20, 0x1F4A9]), + Wtf8Buf { bytes: b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec(), is_known_utf8: true } + ); assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! - assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]), Wtf8Buf { - bytes: b"\xED\xA0\xBD \xED\xB2\xA9".to_vec(), - is_known_utf8: false - }); - assert_eq!(e(&[0xD800], &[0xDBFF]), Wtf8Buf { - bytes: b"\xED\xA0\x80\xED\xAF\xBF".to_vec(), - is_known_utf8: false - }); - assert_eq!(e(&[0xD800], &[0xE000]), Wtf8Buf { - bytes: b"\xED\xA0\x80\xEE\x80\x80".to_vec(), - is_known_utf8: false - }); - assert_eq!(e(&[0xD7FF], &[0xDC00]), Wtf8Buf { - bytes: b"\xED\x9F\xBF\xED\xB0\x80".to_vec(), - is_known_utf8: false - }); - assert_eq!(e(&[0x61], &[0xDC00]), Wtf8Buf { - bytes: b"\x61\xED\xB0\x80".to_vec(), - is_known_utf8: false - }); - assert_eq!(e(&[], &[0xDC00]), Wtf8Buf { - bytes: b"\xED\xB0\x80".to_vec(), - is_known_utf8: false - }); + assert_eq!( + e(&[0xD83D, 0x20], &[0xDCA9]), + Wtf8Buf { bytes: b"\xED\xA0\xBD \xED\xB2\xA9".to_vec(), is_known_utf8: false } + ); + assert_eq!( + e(&[0xD800], &[0xDBFF]), + Wtf8Buf { bytes: b"\xED\xA0\x80\xED\xAF\xBF".to_vec(), is_known_utf8: false } + ); + assert_eq!( + e(&[0xD800], &[0xE000]), + Wtf8Buf { bytes: b"\xED\xA0\x80\xEE\x80\x80".to_vec(), is_known_utf8: false } + ); + assert_eq!( + e(&[0xD7FF], &[0xDC00]), + Wtf8Buf { bytes: b"\xED\x9F\xBF\xED\xB0\x80".to_vec(), is_known_utf8: false } + ); + assert_eq!( + e(&[0x61], &[0xDC00]), + Wtf8Buf { bytes: b"\x61\xED\xB0\x80".to_vec(), is_known_utf8: false } + ); + assert_eq!( + e(&[], &[0xDC00]), + Wtf8Buf { bytes: b"\xED\xB0\x80".to_vec(), is_known_utf8: false } + ); } #[test] @@ -556,9 +556,10 @@ fn wtf8_encode_wide() { let mut string = Wtf8Buf::from_str("aé "); string.push(CodePoint::from_u32(0xD83D).unwrap()); string.push_char('💩'); - assert_eq!(string.encode_wide().collect::>(), vec![ - 0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9 - ]); + assert_eq!( + string.encode_wide().collect::>(), + vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9] + ); } #[test] diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index 82779dc6306..25e5e9e6eb9 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -157,12 +157,16 @@ pub fn prebuilt_llvm_config( /// This retrieves the LLVM sha we *want* to use, according to git history. pub(crate) fn detect_llvm_sha(config: &Config, is_git: bool) -> String { let llvm_sha = if is_git { - get_closest_merge_commit(Some(&config.src), &config.git_config(), &[ - config.src.join("src/llvm-project"), - config.src.join("src/bootstrap/download-ci-llvm-stamp"), - // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly` - config.src.join("src/version"), - ]) + get_closest_merge_commit( + Some(&config.src), + &config.git_config(), + &[ + config.src.join("src/llvm-project"), + config.src.join("src/bootstrap/download-ci-llvm-stamp"), + // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly` + config.src.join("src/version"), + ], + ) .unwrap() } else if let Some(info) = crate::utils::channel::read_commit_info_file(&config.src) { info.sha.trim().to_owned() diff --git a/src/bootstrap/src/core/build_steps/toolstate.rs b/src/bootstrap/src/core/build_steps/toolstate.rs index 84871331bd5..668133f05cb 100644 --- a/src/bootstrap/src/core/build_steps/toolstate.rs +++ b/src/bootstrap/src/core/build_steps/toolstate.rs @@ -42,11 +42,15 @@ pub enum ToolState { impl fmt::Display for ToolState { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", match self { - ToolState::TestFail => "test-fail", - ToolState::TestPass => "test-pass", - ToolState::BuildFail => "build-fail", - }) + write!( + f, + "{}", + match self { + ToolState::TestFail => "test-fail", + ToolState::TestPass => "test-pass", + ToolState::BuildFail => "build-fail", + } + ) } } diff --git a/src/bootstrap/src/core/builder/mod.rs b/src/bootstrap/src/core/builder/mod.rs index 08421dc1f5b..8e767a8dcc6 100644 --- a/src/bootstrap/src/core/builder/mod.rs +++ b/src/bootstrap/src/core/builder/mod.rs @@ -315,29 +315,32 @@ const PATH_REMAP: &[(&str, &[&str])] = &[ // actual path is `proc-macro-srv-cli` ("rust-analyzer-proc-macro-srv", &["src/tools/rust-analyzer/crates/proc-macro-srv-cli"]), // Make `x test tests` function the same as `x t tests/*` - ("tests", &[ - // tidy-alphabetical-start - "tests/assembly", - "tests/codegen", - "tests/codegen-units", - "tests/coverage", - "tests/coverage-run-rustdoc", - "tests/crashes", - "tests/debuginfo", - "tests/incremental", - "tests/mir-opt", - "tests/pretty", - "tests/run-make", - "tests/rustdoc", - "tests/rustdoc-gui", - "tests/rustdoc-js", - "tests/rustdoc-js-std", - "tests/rustdoc-json", - "tests/rustdoc-ui", - "tests/ui", - "tests/ui-fulldeps", - // tidy-alphabetical-end - ]), + ( + "tests", + &[ + // tidy-alphabetical-start + "tests/assembly", + "tests/codegen", + "tests/codegen-units", + "tests/coverage", + "tests/coverage-run-rustdoc", + "tests/crashes", + "tests/debuginfo", + "tests/incremental", + "tests/mir-opt", + "tests/pretty", + "tests/run-make", + "tests/rustdoc", + "tests/rustdoc-gui", + "tests/rustdoc-js", + "tests/rustdoc-js-std", + "tests/rustdoc-json", + "tests/rustdoc-ui", + "tests/ui", + "tests/ui-fulldeps", + // tidy-alphabetical-end + ], + ), ]; fn remap_paths(paths: &mut Vec) { diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 0c27597083d..74e1ed5c637 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -114,11 +114,14 @@ fn test_intersection() { ]; let subset = library_set.intersection_removing_matches(&mut command_paths, Kind::Build); assert_eq!(subset, set(&["library/core", "library/alloc"]),); - assert_eq!(command_paths, vec![ - CLIStepPath::from(PathBuf::from("library/core")).will_be_executed(true), - CLIStepPath::from(PathBuf::from("library/alloc")).will_be_executed(true), - CLIStepPath::from(PathBuf::from("library/stdarch")).will_be_executed(false), - ]); + assert_eq!( + command_paths, + vec![ + CLIStepPath::from(PathBuf::from("library/core")).will_be_executed(true), + CLIStepPath::from(PathBuf::from("library/alloc")).will_be_executed(true), + CLIStepPath::from(PathBuf::from("library/stdarch")).will_be_executed(false), + ] + ); } #[test] @@ -135,10 +138,13 @@ fn test_resolve_parent_and_subpaths() { let library_set = set(&["src/tools/miri", "src/tools/miri/cargo-miri"]); library_set.intersection_removing_matches(&mut command_paths, Kind::Build); - assert_eq!(command_paths, vec![ - CLIStepPath::from(PathBuf::from("src/tools/miri")).will_be_executed(true), - CLIStepPath::from(PathBuf::from("src/tools/miri/cargo-miri")).will_be_executed(true), - ]); + assert_eq!( + command_paths, + vec![ + CLIStepPath::from(PathBuf::from("src/tools/miri")).will_be_executed(true), + CLIStepPath::from(PathBuf::from("src/tools/miri/cargo-miri")).will_be_executed(true), + ] + ); } #[test] @@ -212,18 +218,22 @@ fn alias_and_path_for_library() { &["library".into(), "core".into()], configure("build", &[TEST_TRIPLE_1], &[TEST_TRIPLE_1]), ); - assert_eq!(first(cache.all::()), &[ - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1) - ]); + assert_eq!( + first(cache.all::()), + &[ + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1) + ] + ); let mut cache = run_build( &["library".into(), "core".into()], configure("doc", &[TEST_TRIPLE_1], &[TEST_TRIPLE_1]), ); - assert_eq!(first(cache.all::()), &[ - doc_std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0) - ]); + assert_eq!( + first(cache.all::()), + &[doc_std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0)] + ); } #[test] @@ -271,10 +281,13 @@ mod defaults { let mut cache = run_build(&[], configure("build", &[TEST_TRIPLE_1], &[TEST_TRIPLE_1])); let a = TargetSelection::from_user(TEST_TRIPLE_1); - assert_eq!(first(cache.all::()), &[ - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), - ]); + assert_eq!( + first(cache.all::()), + &[ + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), + ] + ); assert!(!cache.all::().is_empty()); // Make sure rustdoc is only built once. assert_eq!( @@ -283,9 +296,10 @@ mod defaults { // - this is the compiler it's _linked_ to, not built with. &[tool::Rustdoc { compiler: Compiler { host: a, stage: 1 } }], ); - assert_eq!(first(cache.all::()), &[ - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0) - ],); + assert_eq!( + first(cache.all::()), + &[rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0)], + ); } #[test] @@ -294,9 +308,10 @@ mod defaults { let mut cache = run_build(&[], config); let a = TargetSelection::from_user(TEST_TRIPLE_1); - assert_eq!(first(cache.all::()), &[ - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0) - ]); + assert_eq!( + first(cache.all::()), + &[std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0)] + ); assert!(!cache.all::().is_empty()); assert_eq!( first(cache.all::()), @@ -323,25 +338,37 @@ mod defaults { // there's not really a need for us to build for target A in this case // (since we're producing stage 1 libraries/binaries). But currently // bootstrap is just a bit buggy here; this should be fixed though. - assert_eq!(first(cache.all::()), &[ - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 0), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), - ]); - assert_eq!(first(cache.all::()), &[ - compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, - compile::Assemble { target_compiler: Compiler { host: b, stage: 1 } }, - ]); - assert_eq!(first(cache.all::()), &[ - tool::Rustdoc { compiler: Compiler { host: a, stage: 1 } }, - tool::Rustdoc { compiler: Compiler { host: b, stage: 1 } }, - ],); - assert_eq!(first(cache.all::()), &[ - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 0), - ]); + assert_eq!( + first(cache.all::()), + &[ + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 0), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), + ] + ); + assert_eq!( + first(cache.all::()), + &[ + compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, + compile::Assemble { target_compiler: Compiler { host: b, stage: 1 } }, + ] + ); + assert_eq!( + first(cache.all::()), + &[ + tool::Rustdoc { compiler: Compiler { host: a, stage: 1 } }, + tool::Rustdoc { compiler: Compiler { host: b, stage: 1 } }, + ], + ); + assert_eq!( + first(cache.all::()), + &[ + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 0), + ] + ); } #[test] @@ -355,15 +382,17 @@ mod defaults { // error_index_generator uses stage 0 to share rustdoc artifacts with the // rustdoc tool. assert_eq!(first(cache.all::()), &[doc::ErrorIndex { target: a },]); - assert_eq!(first(cache.all::()), &[tool::ErrorIndex { - compiler: Compiler { host: a, stage: 0 } - }]); + assert_eq!( + first(cache.all::()), + &[tool::ErrorIndex { compiler: Compiler { host: a, stage: 0 } }] + ); // docs should be built with the beta compiler, not with the stage0 artifacts. // recall that rustdoc is off-by-one: `stage` is the compiler rustdoc is _linked_ to, // not the one it was built by. - assert_eq!(first(cache.all::()), &[tool::Rustdoc { - compiler: Compiler { host: a, stage: 0 } - },]); + assert_eq!( + first(cache.all::()), + &[tool::Rustdoc { compiler: Compiler { host: a, stage: 0 } },] + ); } } @@ -385,18 +414,20 @@ mod dist { assert_eq!(first(cache.all::()), &[dist::Docs { host: a },]); assert_eq!(first(cache.all::()), &[dist::Mingw { host: a },]); - assert_eq!(first(cache.all::()), &[dist::Rustc { - compiler: Compiler { host: a, stage: 2 } - },]); - assert_eq!(first(cache.all::()), &[dist::Std { - compiler: Compiler { host: a, stage: 1 }, - target: a - },]); + assert_eq!( + first(cache.all::()), + &[dist::Rustc { compiler: Compiler { host: a, stage: 2 } },] + ); + assert_eq!( + first(cache.all::()), + &[dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a },] + ); assert_eq!(first(cache.all::()), &[dist::Src]); // Make sure rustdoc is only built once. - assert_eq!(first(cache.all::()), &[tool::Rustdoc { - compiler: Compiler { host: a, stage: 2 } - },]); + assert_eq!( + first(cache.all::()), + &[tool::Rustdoc { compiler: Compiler { host: a, stage: 2 } },] + ); } #[test] @@ -407,19 +438,25 @@ mod dist { let a = TargetSelection::from_user(TEST_TRIPLE_1); let b = TargetSelection::from_user(TEST_TRIPLE_2); - assert_eq!(first(cache.all::()), &[dist::Docs { host: a }, dist::Docs { - host: b - },]); - assert_eq!(first(cache.all::()), &[dist::Mingw { host: a }, dist::Mingw { - host: b - },]); - assert_eq!(first(cache.all::()), &[dist::Rustc { - compiler: Compiler { host: a, stage: 2 } - },]); - assert_eq!(first(cache.all::()), &[ - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, - dist::Std { compiler: Compiler { host: a, stage: 2 }, target: b }, - ]); + assert_eq!( + first(cache.all::()), + &[dist::Docs { host: a }, dist::Docs { host: b },] + ); + assert_eq!( + first(cache.all::()), + &[dist::Mingw { host: a }, dist::Mingw { host: b },] + ); + assert_eq!( + first(cache.all::()), + &[dist::Rustc { compiler: Compiler { host: a, stage: 2 } },] + ); + assert_eq!( + first(cache.all::()), + &[ + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, + dist::Std { compiler: Compiler { host: a, stage: 2 }, target: b }, + ] + ); assert_eq!(first(cache.all::()), &[dist::Src]); } @@ -433,27 +470,38 @@ mod dist { let a = TargetSelection::from_user(TEST_TRIPLE_1); let b = TargetSelection::from_user(TEST_TRIPLE_2); - assert_eq!(first(cache.all::()), &[dist::Docs { host: a }, dist::Docs { - host: b - },]); - assert_eq!(first(cache.all::()), &[dist::Mingw { host: a }, dist::Mingw { - host: b - },]); - assert_eq!(first(cache.all::()), &[ - dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, - dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, - ]); - assert_eq!(first(cache.all::()), &[ - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, - ]); - assert_eq!(first(cache.all::()), &[ - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 2), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 2), - ],); + assert_eq!( + first(cache.all::()), + &[dist::Docs { host: a }, dist::Docs { host: b },] + ); + assert_eq!( + first(cache.all::()), + &[dist::Mingw { host: a }, dist::Mingw { host: b },] + ); + assert_eq!( + first(cache.all::()), + &[ + dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, + dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, + ] + ); + assert_eq!( + first(cache.all::()), + &[ + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, + ] + ); + assert_eq!( + first(cache.all::()), + &[ + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 2), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 2), + ], + ); assert_eq!(first(cache.all::()), &[dist::Src]); } @@ -467,49 +515,56 @@ mod dist { config.hosts = vec![b]; let mut cache = run_build(&[], config); - assert_eq!(first(cache.all::()), &[dist::Rustc { - compiler: Compiler { host: b, stage: 2 } - },]); - assert_eq!(first(cache.all::()), &[ - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), - ]); + assert_eq!( + first(cache.all::()), + &[dist::Rustc { compiler: Compiler { host: b, stage: 2 } },] + ); + assert_eq!( + first(cache.all::()), + &[ + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), + ] + ); } #[test] fn dist_with_targets_and_hosts() { let mut cache = run_build( &[], - configure(&[TEST_TRIPLE_1, TEST_TRIPLE_2], &[ - TEST_TRIPLE_1, - TEST_TRIPLE_2, - TEST_TRIPLE_3, - ]), + configure( + &[TEST_TRIPLE_1, TEST_TRIPLE_2], + &[TEST_TRIPLE_1, TEST_TRIPLE_2, TEST_TRIPLE_3], + ), ); let a = TargetSelection::from_user(TEST_TRIPLE_1); let b = TargetSelection::from_user(TEST_TRIPLE_2); let c = TargetSelection::from_user(TEST_TRIPLE_3); - assert_eq!(first(cache.all::()), &[ - dist::Docs { host: a }, - dist::Docs { host: b }, - dist::Docs { host: c }, - ]); - assert_eq!(first(cache.all::()), &[ - dist::Mingw { host: a }, - dist::Mingw { host: b }, - dist::Mingw { host: c }, - ]); - assert_eq!(first(cache.all::()), &[ - dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, - dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, - ]); - assert_eq!(first(cache.all::()), &[ - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, - dist::Std { compiler: Compiler { host: a, stage: 2 }, target: c }, - ]); + assert_eq!( + first(cache.all::()), + &[dist::Docs { host: a }, dist::Docs { host: b }, dist::Docs { host: c },] + ); + assert_eq!( + first(cache.all::()), + &[dist::Mingw { host: a }, dist::Mingw { host: b }, dist::Mingw { host: c },] + ); + assert_eq!( + first(cache.all::()), + &[ + dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, + dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, + ] + ); + assert_eq!( + first(cache.all::()), + &[ + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, + dist::Std { compiler: Compiler { host: a, stage: 2 }, target: c }, + ] + ); assert_eq!(first(cache.all::()), &[dist::Src]); } @@ -523,10 +578,10 @@ mod dist { assert_eq!(first(cache.all::()), &[dist::Docs { host: c },]); assert_eq!(first(cache.all::()), &[dist::Mingw { host: c },]); - assert_eq!(first(cache.all::()), &[dist::Std { - compiler: Compiler { host: a, stage: 2 }, - target: c - },]); + assert_eq!( + first(cache.all::()), + &[dist::Std { compiler: Compiler { host: a, stage: 2 }, target: c },] + ); } #[test] @@ -539,65 +594,84 @@ mod dist { let a = TargetSelection::from_user(TEST_TRIPLE_1); let b = TargetSelection::from_user(TEST_TRIPLE_2); - assert_eq!(first(cache.all::()), &[dist::Docs { host: a }, dist::Docs { - host: b - },]); - assert_eq!(first(cache.all::()), &[dist::Mingw { host: a }, dist::Mingw { - host: b - },]); - assert_eq!(first(cache.all::()), &[ - dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, - dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, - ]); - assert_eq!(first(cache.all::()), &[ - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, - ]); + assert_eq!( + first(cache.all::()), + &[dist::Docs { host: a }, dist::Docs { host: b },] + ); + assert_eq!( + first(cache.all::()), + &[dist::Mingw { host: a }, dist::Mingw { host: b },] + ); + assert_eq!( + first(cache.all::()), + &[ + dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, + dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, + ] + ); + assert_eq!( + first(cache.all::()), + &[ + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, + ] + ); assert_eq!(first(cache.all::()), &[dist::Src]); - assert_eq!(first(cache.all::()), &[ - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 2), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 2), - ]); - assert_eq!(first(cache.all::()), &[ - compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 2 } }, - compile::Assemble { target_compiler: Compiler { host: b, stage: 2 } }, - ]); + assert_eq!( + first(cache.all::()), + &[ + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 2), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 2), + ] + ); + assert_eq!( + first(cache.all::()), + &[ + compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 2 } }, + compile::Assemble { target_compiler: Compiler { host: b, stage: 2 } }, + ] + ); } #[test] fn build_all() { - let build = Build::new(configure(&[TEST_TRIPLE_1, TEST_TRIPLE_2], &[ - TEST_TRIPLE_1, - TEST_TRIPLE_2, - TEST_TRIPLE_3, - ])); + let build = Build::new(configure( + &[TEST_TRIPLE_1, TEST_TRIPLE_2], + &[TEST_TRIPLE_1, TEST_TRIPLE_2, TEST_TRIPLE_3], + )); let mut builder = Builder::new(&build); - builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[ - "compiler/rustc".into(), - "library".into(), - ]); + builder.run_step_descriptions( + &Builder::get_step_descriptions(Kind::Build), + &["compiler/rustc".into(), "library".into()], + ); - assert_eq!(first(builder.cache.all::()), &[ - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 2), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 2), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_3, stage = 2), - ]); + assert_eq!( + first(builder.cache.all::()), + &[ + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 2), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 2), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_3, stage = 2), + ] + ); assert_eq!(builder.cache.all::().len(), 5); - assert_eq!(first(builder.cache.all::()), &[ - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 2), - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 2), - ]); + assert_eq!( + first(builder.cache.all::()), + &[ + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 2), + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 1), + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_2, stage = 2), + ] + ); } #[test] @@ -626,20 +700,29 @@ mod dist { let a = TargetSelection::from_user(TEST_TRIPLE_1); - assert_eq!(first(builder.cache.all::()), &[ - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), - std!(TEST_TRIPLE_1 => TEST_TRIPLE_3, stage = 2), - ]); - assert_eq!(first(builder.cache.all::()), &[ - compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 2 } }, - ]); - assert_eq!(first(builder.cache.all::()), &[ - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), - rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), - ]); + assert_eq!( + first(builder.cache.all::()), + &[ + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), + std!(TEST_TRIPLE_1 => TEST_TRIPLE_3, stage = 2), + ] + ); + assert_eq!( + first(builder.cache.all::()), + &[ + compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 2 } }, + ] + ); + assert_eq!( + first(builder.cache.all::()), + &[ + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 0), + rustc!(TEST_TRIPLE_1 => TEST_TRIPLE_1, stage = 1), + ] + ); } #[test] @@ -669,18 +752,22 @@ mod dist { let host = TargetSelection::from_user(TEST_TRIPLE_1); - builder.run_step_descriptions(&[StepDescription::from::(Kind::Test)], &[ - "library/std".into(), - ]); + builder.run_step_descriptions( + &[StepDescription::from::(Kind::Test)], + &["library/std".into()], + ); // Ensure we don't build any compiler artifacts. assert!(!builder.cache.contains::()); - assert_eq!(first(builder.cache.all::()), &[test::Crate { - compiler: Compiler { host, stage: 0 }, - target: host, - mode: crate::Mode::Std, - crates: vec!["std".to_owned()], - },]); + assert_eq!( + first(builder.cache.all::()), + &[test::Crate { + compiler: Compiler { host, stage: 0 }, + target: host, + mode: crate::Mode::Std, + crates: vec!["std".to_owned()], + },] + ); } #[test] @@ -699,14 +786,16 @@ mod dist { first(builder.cache.all::()), &[doc::ErrorIndex { target: a },] ); - assert_eq!(first(builder.cache.all::()), &[tool::ErrorIndex { - compiler: Compiler { host: a, stage: 1 } - }]); + assert_eq!( + first(builder.cache.all::()), + &[tool::ErrorIndex { compiler: Compiler { host: a, stage: 1 } }] + ); // This is actually stage 1, but Rustdoc::run swaps out the compiler with // stage minus 1 if --stage is not 0. Very confusing! - assert_eq!(first(builder.cache.all::()), &[tool::Rustdoc { - compiler: Compiler { host: a, stage: 2 } - },]); + assert_eq!( + first(builder.cache.all::()), + &[tool::Rustdoc { compiler: Compiler { host: a, stage: 2 } },] + ); } #[test] @@ -743,9 +832,10 @@ mod dist { first(builder.cache.all::()), &[doc::ErrorIndex { target: a },] ); - assert_eq!(first(builder.cache.all::()), &[tool::ErrorIndex { - compiler: Compiler { host: a, stage: 1 } - }]); + assert_eq!( + first(builder.cache.all::()), + &[tool::ErrorIndex { compiler: Compiler { host: a, stage: 1 } }] + ); // Unfortunately rustdoc is built twice. Once from stage1 for compiletest // (and other things), and once from stage0 for std crates. Ideally it // would only be built once. If someone wants to fix this, it might be @@ -757,11 +847,14 @@ mod dist { // The stage 0 copy is the one downloaded for bootstrapping. It is // (currently) needed to run "cargo test" on the linkchecker, and // should be relatively "free". - assert_eq!(first(builder.cache.all::()), &[ - tool::Rustdoc { compiler: Compiler { host: a, stage: 0 } }, - tool::Rustdoc { compiler: Compiler { host: a, stage: 1 } }, - tool::Rustdoc { compiler: Compiler { host: a, stage: 2 } }, - ]); + assert_eq!( + first(builder.cache.all::()), + &[ + tool::Rustdoc { compiler: Compiler { host: a, stage: 0 } }, + tool::Rustdoc { compiler: Compiler { host: a, stage: 1 } }, + tool::Rustdoc { compiler: Compiler { host: a, stage: 2 } }, + ] + ); } } diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index 4694dd2ca4e..d3ed7ecddd3 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -1928,11 +1928,14 @@ impl Config { config.rustc_default_linker = default_linker; config.musl_root = musl_root.map(PathBuf::from); config.save_toolstates = save_toolstates.map(PathBuf::from); - set(&mut config.deny_warnings, match flags.warnings { - Warnings::Deny => Some(true), - Warnings::Warn => Some(false), - Warnings::Default => deny_warnings, - }); + set( + &mut config.deny_warnings, + match flags.warnings { + Warnings::Deny => Some(true), + Warnings::Warn => Some(false), + Warnings::Default => deny_warnings, + }, + ); set(&mut config.backtrace_on_ice, backtrace_on_ice); set(&mut config.rust_verify_llvm_ir, verify_llvm_ir); config.rust_thin_lto_import_instr_limit = thin_lto_import_instr_limit; diff --git a/src/librustdoc/clean/cfg/tests.rs b/src/librustdoc/clean/cfg/tests.rs index 2c62e12c96d..26dc101e4b5 100644 --- a/src/librustdoc/clean/cfg/tests.rs +++ b/src/librustdoc/clean/cfg/tests.rs @@ -276,10 +276,13 @@ fn test_parse_ok() { let mi = dummy_meta_item_list!(not, [a]); assert_eq!(Cfg::parse(&mi), Ok(!word_cfg("a"))); - let mi = dummy_meta_item_list!(not, [dummy_meta_item_list!(any, [ - dummy_meta_item_word("a"), - dummy_meta_item_list!(all, [b, c]), - ]),]); + let mi = dummy_meta_item_list!( + not, + [dummy_meta_item_list!( + any, + [dummy_meta_item_word("a"), dummy_meta_item_list!(all, [b, c]),] + ),] + ); assert_eq!(Cfg::parse(&mi), Ok(!(word_cfg("a") | (word_cfg("b") & word_cfg("c"))))); let mi = dummy_meta_item_list!(all, [a, b, c]); @@ -302,18 +305,16 @@ fn test_parse_err() { let mi = dummy_meta_item_list!(foo, []); assert!(Cfg::parse(&mi).is_err()); - let mi = - dummy_meta_item_list!( - all, - [dummy_meta_item_list!(foo, []), dummy_meta_item_word("b"),] - ); + let mi = dummy_meta_item_list!( + all, + [dummy_meta_item_list!(foo, []), dummy_meta_item_word("b"),] + ); assert!(Cfg::parse(&mi).is_err()); - let mi = - dummy_meta_item_list!( - any, - [dummy_meta_item_word("a"), dummy_meta_item_list!(foo, []),] - ); + let mi = dummy_meta_item_list!( + any, + [dummy_meta_item_word("a"), dummy_meta_item_list!(foo, []),] + ); assert!(Cfg::parse(&mi).is_err()); let mi = dummy_meta_item_list!(not, [dummy_meta_item_list!(foo, []),]); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index b14381c0c40..1d62a93e723 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -544,14 +544,18 @@ fn clean_generic_param_def( } else { None }; - (def.name, GenericParamDefKind::Type { - bounds: ThinVec::new(), // These are filled in from the where-clauses. - default: default.map(Box::new), - synthetic, - }) + ( + def.name, + GenericParamDefKind::Type { + bounds: ThinVec::new(), // These are filled in from the where-clauses. + default: default.map(Box::new), + synthetic, + }, + ) } - ty::GenericParamDefKind::Const { has_default, synthetic } => { - (def.name, GenericParamDefKind::Const { + ty::GenericParamDefKind::Const { has_default, synthetic } => ( + def.name, + GenericParamDefKind::Const { ty: Box::new(clean_middle_ty( ty::Binder::dummy( cx.tcx @@ -573,8 +577,8 @@ fn clean_generic_param_def( None }, synthetic, - }) - } + }, + ), }; GenericParamDef { name, def_id: def.def_id, kind } @@ -619,21 +623,25 @@ fn clean_generic_param<'tcx>( } else { ThinVec::new() }; - (param.name.ident().name, GenericParamDefKind::Type { - bounds, - default: default.map(|t| clean_ty(t, cx)).map(Box::new), - synthetic, - }) + ( + param.name.ident().name, + GenericParamDefKind::Type { + bounds, + default: default.map(|t| clean_ty(t, cx)).map(Box::new), + synthetic, + }, + ) } - hir::GenericParamKind::Const { ty, default, synthetic } => { - (param.name.ident().name, GenericParamDefKind::Const { + hir::GenericParamKind::Const { ty, default, synthetic } => ( + param.name.ident().name, + GenericParamDefKind::Const { ty: Box::new(clean_ty(ty, cx)), default: default.map(|ct| { Box::new(lower_const_arg_for_rustdoc(cx.tcx, ct, FeedConstTy::No).to_string()) }), synthetic, - }) - } + }, + ), }; GenericParamDef { name, def_id: param.def_id.to_def_id(), kind } @@ -653,9 +661,10 @@ fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool { /// /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information. fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool { - matches!(param.kind, hir::GenericParamKind::Lifetime { - kind: hir::LifetimeParamKind::Elided(_) - }) + matches!( + param.kind, + hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided(_) } + ) } pub(crate) fn clean_generics<'tcx>( @@ -1055,11 +1064,10 @@ fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[hir::Attrib .. } = param { - func.decl.inputs.values.insert(a.get() as _, Argument { - name, - type_: *ty, - is_const: true, - }); + func.decl + .inputs + .values + .insert(a.get() as _, Argument { name, type_: *ty, is_const: true }); } else { panic!("unexpected non const in position {pos}"); } @@ -1422,11 +1430,11 @@ pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocCo let bounds = tcx.explicit_item_bounds(assoc_item.def_id).iter_identity_copied(); predicates = tcx.arena.alloc_from_iter(bounds.chain(predicates.iter().copied())); } - let mut generics = - clean_ty_generics(cx, tcx.generics_of(assoc_item.def_id), ty::GenericPredicates { - parent: None, - predicates, - }); + let mut generics = clean_ty_generics( + cx, + tcx.generics_of(assoc_item.def_id), + ty::GenericPredicates { parent: None, predicates }, + ); simplify::move_bounds_to_generic_parameters(&mut generics); if let ty::AssocItemContainer::Trait = assoc_item.container { diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 583cd404dca..5f7c30a33ab 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1253,10 +1253,13 @@ impl GenericBound { } pub(crate) fn maybe_sized(cx: &mut DocContext<'_>) -> GenericBound { - Self::sized_with(cx, hir::TraitBoundModifiers { - polarity: hir::BoundPolarity::Maybe(DUMMY_SP), - constness: hir::BoundConstness::Never, - }) + Self::sized_with( + cx, + hir::TraitBoundModifiers { + polarity: hir::BoundPolarity::Maybe(DUMMY_SP), + constness: hir::BoundConstness::Never, + }, + ) } fn sized_with(cx: &mut DocContext<'_>, modifiers: hir::TraitBoundModifiers) -> GenericBound { diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index 7b2aee4b4a5..8c91cae4931 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -65,26 +65,34 @@ fn write_header( tooltip: Tooltip, extra_classes: &[String], ) { - write!(out, "
", match tooltip { - Tooltip::Ignore => " ignore", - Tooltip::CompileFail => " compile_fail", - Tooltip::ShouldPanic => " should_panic", - Tooltip::Edition(_) => " edition", - Tooltip::None => "", - },); + write!( + out, + "
", + match tooltip { + Tooltip::Ignore => " ignore", + Tooltip::CompileFail => " compile_fail", + Tooltip::ShouldPanic => " should_panic", + Tooltip::Edition(_) => " edition", + Tooltip::None => "", + }, + ); if tooltip != Tooltip::None { let edition_code; - write!(out, "", match tooltip { - Tooltip::Ignore => "This example is not tested", - Tooltip::CompileFail => "This example deliberately fails to compile", - Tooltip::ShouldPanic => "This example panics", - Tooltip::Edition(edition) => { - edition_code = format!("This example runs with edition {edition}"); - &edition_code - } - Tooltip::None => unreachable!(), - },); + write!( + out, + "", + match tooltip { + Tooltip::Ignore => "This example is not tested", + Tooltip::CompileFail => "This example deliberately fails to compile", + Tooltip::ShouldPanic => "This example panics", + Tooltip::Edition(edition) => { + edition_code = format!("This example runs with edition {edition}"); + &edition_code + } + Tooltip::None => unreachable!(), + }, + ); } if let Some(extra) = extra_content { diff --git a/src/librustdoc/html/markdown/tests.rs b/src/librustdoc/html/markdown/tests.rs index 2001a763c09..bb42b877a2c 100644 --- a/src/librustdoc/html/markdown/tests.rs +++ b/src/librustdoc/html/markdown/tests.rs @@ -275,14 +275,14 @@ fn test_lang_string_tokenizer() { case("foo", &[LangStringToken::LangToken("foo")]); case("foo,bar", &[LangStringToken::LangToken("foo"), LangStringToken::LangToken("bar")]); case(".foo,.bar", &[]); - case("{.foo,.bar}", &[ - LangStringToken::ClassAttribute("foo"), - LangStringToken::ClassAttribute("bar"), - ]); - case(" {.foo,.bar} ", &[ - LangStringToken::ClassAttribute("foo"), - LangStringToken::ClassAttribute("bar"), - ]); + case( + "{.foo,.bar}", + &[LangStringToken::ClassAttribute("foo"), LangStringToken::ClassAttribute("bar")], + ); + case( + " {.foo,.bar} ", + &[LangStringToken::ClassAttribute("foo"), LangStringToken::ClassAttribute("bar")], + ); case("foo bar", &[LangStringToken::LangToken("foo"), LangStringToken::LangToken("bar")]); case("foo\tbar", &[LangStringToken::LangToken("foo"), LangStringToken::LangToken("bar")]); case("foo\t, bar", &[LangStringToken::LangToken("foo"), LangStringToken::LangToken("bar")]); diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index 8ac8b3a1f84..95f617c9839 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -1265,13 +1265,14 @@ fn simplify_fn_type<'a, 'tcx>( *stored_bounds = type_bounds; } } - ty_constraints.push((RenderTypeId::AssociatedType(name), vec![ - RenderType { + ty_constraints.push(( + RenderTypeId::AssociatedType(name), + vec![RenderType { id: Some(RenderTypeId::Index(idx)), generics: None, bindings: None, - }, - ])) + }], + )) } } } diff --git a/src/librustdoc/json/mod.rs b/src/librustdoc/json/mod.rs index 789a5614967..6f8cf25554f 100644 --- a/src/librustdoc/json/mod.rs +++ b/src/librustdoc/json/mod.rs @@ -268,11 +268,14 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> { .iter() .chain(&self.cache.external_paths) .map(|(&k, &(ref path, kind))| { - (self.id_from_item_default(k.into()), types::ItemSummary { - crate_id: k.krate.as_u32(), - path: path.iter().map(|s| s.to_string()).collect(), - kind: kind.into_json(self), - }) + ( + self.id_from_item_default(k.into()), + types::ItemSummary { + crate_id: k.krate.as_u32(), + path: path.iter().map(|s| s.to_string()).collect(), + kind: kind.into_json(self), + }, + ) }) .collect(), external_crates: self @@ -281,13 +284,16 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> { .iter() .map(|(crate_num, external_location)| { let e = ExternalCrate { crate_num: *crate_num }; - (crate_num.as_u32(), types::ExternalCrate { - name: e.name(self.tcx).to_string(), - html_root_url: match external_location { - ExternalLocation::Remote(s) => Some(s.clone()), - _ => None, + ( + crate_num.as_u32(), + types::ExternalCrate { + name: e.name(self.tcx).to_string(), + html_root_url: match external_location { + ExternalLocation::Remote(s) => Some(s.clone()), + _ => None, + }, }, - }) + ) }) .collect(), format_version: types::FORMAT_VERSION, diff --git a/src/librustdoc/passes/lint/bare_urls.rs b/src/librustdoc/passes/lint/bare_urls.rs index 77d7cf5772d..1e07277d38e 100644 --- a/src/librustdoc/passes/lint/bare_urls.rs +++ b/src/librustdoc/passes/lint/bare_urls.rs @@ -77,9 +77,10 @@ fn find_raw_urls( // For now, we only check "full" URLs (meaning, starting with "http://" or "https://"). for match_ in URL_REGEX.find_iter(text) { let url_range = match_.range(); - f(cx, "this URL is not a hyperlink", Range { - start: range.start + url_range.start, - end: range.start + url_range.end, - }); + f( + cx, + "this URL is not a hyperlink", + Range { start: range.start + url_range.start, end: range.start + url_range.end }, + ); } } diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs index feec2a7444f..c21bf82b852 100644 --- a/src/tools/build-manifest/src/main.rs +++ b/src/tools/build-manifest/src/main.rs @@ -603,11 +603,14 @@ impl Builder { }) .collect(); - dst.insert(pkg.manifest_component_name(), Package { - version: version_info.version.unwrap_or_default(), - git_commit_hash: version_info.git_commit, - target: targets, - }); + dst.insert( + pkg.manifest_component_name(), + Package { + version: version_info.version.unwrap_or_default(), + git_commit_hash: version_info.git_commit, + target: targets, + }, + ); } fn url(&self, path: &Path) -> String { diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs index ebba16d41f9..023658a3dd4 100644 --- a/src/tools/compiletest/src/header/tests.rs +++ b/src/tools/compiletest/src/header/tests.rs @@ -251,9 +251,10 @@ fn revisions() { let config: Config = cfg().build(); assert_eq!(parse_rs(&config, "//@ revisions: a b c").revisions, vec!["a", "b", "c"],); - assert_eq!(parse_makefile(&config, "# revisions: hello there").revisions, vec![ - "hello", "there" - ],); + assert_eq!( + parse_makefile(&config, "# revisions: hello there").revisions, + vec!["hello", "there"], + ); } #[test] diff --git a/src/tools/coverage-dump/src/covfun.rs b/src/tools/coverage-dump/src/covfun.rs index 33fac3edccd..82ebd33d0d1 100644 --- a/src/tools/coverage-dump/src/covfun.rs +++ b/src/tools/coverage-dump/src/covfun.rs @@ -95,10 +95,13 @@ pub(crate) fn dump_covfun_mappings( // has increased or decreased the number of physical counters needed. // (It's possible for the generated code to have more counters that // aren't used by any mappings, but that should hopefully be rare.) - println!("Highest counter ID seen: {}", match max_counter { - Some(id) => format!("c{id}"), - None => "(none)".to_owned(), - }); + println!( + "Highest counter ID seen: {}", + match max_counter { + Some(id) => format!("c{id}"), + None => "(none)".to_owned(), + } + ); println!(); } Ok(()) diff --git a/src/tools/generate-copyright/src/cargo_metadata.rs b/src/tools/generate-copyright/src/cargo_metadata.rs index 420579372ac..51e353e9b22 100644 --- a/src/tools/generate-copyright/src/cargo_metadata.rs +++ b/src/tools/generate-copyright/src/cargo_metadata.rs @@ -98,12 +98,15 @@ pub fn get_metadata( } // otherwise it's an out-of-tree dependency let package_id = Package { name: package.name, version: package.version.to_string() }; - output.insert(package_id, PackageMetadata { - license: package.license.unwrap_or_else(|| String::from("Unspecified")), - authors: package.authors, - notices: BTreeMap::new(), - is_in_libstd: None, - }); + output.insert( + package_id, + PackageMetadata { + license: package.license.unwrap_or_else(|| String::from("Unspecified")), + authors: package.authors, + notices: BTreeMap::new(), + is_in_libstd: None, + }, + ); } } diff --git a/src/tools/generate-copyright/src/main.rs b/src/tools/generate-copyright/src/main.rs index 0a446ecff5b..7a014989e68 100644 --- a/src/tools/generate-copyright/src/main.rs +++ b/src/tools/generate-copyright/src/main.rs @@ -24,12 +24,16 @@ fn main() -> Result<(), Error> { let root_path = std::path::absolute(".")?; // Scan Cargo dependencies - let mut collected_cargo_metadata = - cargo_metadata::get_metadata_and_notices(&cargo, &out_dir.join("vendor"), &root_path, &[ + let mut collected_cargo_metadata = cargo_metadata::get_metadata_and_notices( + &cargo, + &out_dir.join("vendor"), + &root_path, + &[ Path::new("./Cargo.toml"), Path::new("./src/tools/cargo/Cargo.toml"), Path::new("./library/Cargo.toml"), - ])?; + ], + )?; let library_collected_cargo_metadata = cargo_metadata::get_metadata_and_notices( &cargo, diff --git a/src/tools/jsondoclint/src/validator/tests.rs b/src/tools/jsondoclint/src/validator/tests.rs index a37e6c2eb5c..28deb7e7cee 100644 --- a/src/tools/jsondoclint/src/validator/tests.rs +++ b/src/tools/jsondoclint/src/validator/tests.rs @@ -21,32 +21,42 @@ fn errors_on_missing_links() { root: Id(0), crate_version: None, includes_private: false, - index: FxHashMap::from_iter([(Id(0), Item { - name: Some("root".to_owned()), - id: Id(0), - crate_id: 0, - span: None, - visibility: Visibility::Public, - docs: None, - links: FxHashMap::from_iter([("Not Found".to_owned(), Id(1))]), - attrs: vec![], - deprecation: None, - inner: ItemEnum::Module(Module { is_crate: true, items: vec![], is_stripped: false }), - })]), + index: FxHashMap::from_iter([( + Id(0), + Item { + name: Some("root".to_owned()), + id: Id(0), + crate_id: 0, + span: None, + visibility: Visibility::Public, + docs: None, + links: FxHashMap::from_iter([("Not Found".to_owned(), Id(1))]), + attrs: vec![], + deprecation: None, + inner: ItemEnum::Module(Module { + is_crate: true, + items: vec![], + is_stripped: false, + }), + }, + )]), paths: FxHashMap::default(), external_crates: FxHashMap::default(), format_version: rustdoc_json_types::FORMAT_VERSION, }; - check(&k, &[Error { - kind: ErrorKind::NotFound(vec![vec![ - SelectorPart::Field("index".to_owned()), - SelectorPart::Field("0".to_owned()), - SelectorPart::Field("links".to_owned()), - SelectorPart::Field("Not Found".to_owned()), - ]]), - id: Id(1), - }]); + check( + &k, + &[Error { + kind: ErrorKind::NotFound(vec![vec![ + SelectorPart::Field("index".to_owned()), + SelectorPart::Field("0".to_owned()), + SelectorPart::Field("links".to_owned()), + SelectorPart::Field("Not Found".to_owned()), + ]]), + id: Id(1), + }], + ); } // Test we would catch @@ -58,48 +68,60 @@ fn errors_on_local_in_paths_and_not_index() { crate_version: None, includes_private: false, index: FxHashMap::from_iter([ - (Id(0), Item { - id: Id(0), - crate_id: 0, - name: Some("microcore".to_owned()), - span: None, - visibility: Visibility::Public, - docs: None, - links: FxHashMap::from_iter([(("prim@i32".to_owned(), Id(2)))]), - attrs: Vec::new(), - deprecation: None, - inner: ItemEnum::Module(Module { - is_crate: true, - items: vec![Id(1)], - is_stripped: false, - }), - }), - (Id(1), Item { - id: Id(1), - crate_id: 0, - name: Some("i32".to_owned()), - span: None, - visibility: Visibility::Public, - docs: None, - links: FxHashMap::default(), - attrs: Vec::new(), - deprecation: None, - inner: ItemEnum::Primitive(Primitive { name: "i32".to_owned(), impls: vec![] }), - }), + ( + Id(0), + Item { + id: Id(0), + crate_id: 0, + name: Some("microcore".to_owned()), + span: None, + visibility: Visibility::Public, + docs: None, + links: FxHashMap::from_iter([(("prim@i32".to_owned(), Id(2)))]), + attrs: Vec::new(), + deprecation: None, + inner: ItemEnum::Module(Module { + is_crate: true, + items: vec![Id(1)], + is_stripped: false, + }), + }, + ), + ( + Id(1), + Item { + id: Id(1), + crate_id: 0, + name: Some("i32".to_owned()), + span: None, + visibility: Visibility::Public, + docs: None, + links: FxHashMap::default(), + attrs: Vec::new(), + deprecation: None, + inner: ItemEnum::Primitive(Primitive { name: "i32".to_owned(), impls: vec![] }), + }, + ), ]), - paths: FxHashMap::from_iter([(Id(2), ItemSummary { - crate_id: 0, - path: vec!["microcore".to_owned(), "i32".to_owned()], - kind: ItemKind::Primitive, - })]), + paths: FxHashMap::from_iter([( + Id(2), + ItemSummary { + crate_id: 0, + path: vec!["microcore".to_owned(), "i32".to_owned()], + kind: ItemKind::Primitive, + }, + )]), external_crates: FxHashMap::default(), format_version: rustdoc_json_types::FORMAT_VERSION, }; - check(&krate, &[Error { - id: Id(2), - kind: ErrorKind::Custom("Id for local item in `paths` but not in `index`".to_owned()), - }]); + check( + &krate, + &[Error { + id: Id(2), + kind: ErrorKind::Custom("Id for local item in `paths` but not in `index`".to_owned()), + }], + ); } #[test] @@ -117,84 +139,96 @@ fn errors_on_missing_path() { crate_version: None, includes_private: false, index: FxHashMap::from_iter([ - (Id(0), Item { - id: Id(0), - crate_id: 0, - name: Some("foo".to_owned()), - span: None, - visibility: Visibility::Public, - docs: None, - links: FxHashMap::default(), - attrs: Vec::new(), - deprecation: None, - inner: ItemEnum::Module(Module { - is_crate: true, - items: vec![Id(1), Id(2)], - is_stripped: false, - }), - }), - (Id(1), Item { - id: Id(0), - crate_id: 0, - name: Some("Bar".to_owned()), - span: None, - visibility: Visibility::Public, - docs: None, - links: FxHashMap::default(), - attrs: Vec::new(), - deprecation: None, - inner: ItemEnum::Struct(Struct { - kind: StructKind::Unit, - generics: generics.clone(), - impls: vec![], - }), - }), - (Id(2), Item { - id: Id(0), - crate_id: 0, - name: Some("mk_bar".to_owned()), - span: None, - visibility: Visibility::Public, - docs: None, - links: FxHashMap::default(), - attrs: Vec::new(), - deprecation: None, - inner: ItemEnum::Function(Function { - sig: FunctionSignature { - inputs: vec![], - output: Some(Type::ResolvedPath(Path { - path: "Bar".to_owned(), - id: Id(1), - args: None, - })), - is_c_variadic: false, - }, - generics, - header: FunctionHeader { - is_const: false, - is_unsafe: false, - is_async: false, - abi: Abi::Rust, - }, - has_body: true, - }), - }), + ( + Id(0), + Item { + id: Id(0), + crate_id: 0, + name: Some("foo".to_owned()), + span: None, + visibility: Visibility::Public, + docs: None, + links: FxHashMap::default(), + attrs: Vec::new(), + deprecation: None, + inner: ItemEnum::Module(Module { + is_crate: true, + items: vec![Id(1), Id(2)], + is_stripped: false, + }), + }, + ), + ( + Id(1), + Item { + id: Id(0), + crate_id: 0, + name: Some("Bar".to_owned()), + span: None, + visibility: Visibility::Public, + docs: None, + links: FxHashMap::default(), + attrs: Vec::new(), + deprecation: None, + inner: ItemEnum::Struct(Struct { + kind: StructKind::Unit, + generics: generics.clone(), + impls: vec![], + }), + }, + ), + ( + Id(2), + Item { + id: Id(0), + crate_id: 0, + name: Some("mk_bar".to_owned()), + span: None, + visibility: Visibility::Public, + docs: None, + links: FxHashMap::default(), + attrs: Vec::new(), + deprecation: None, + inner: ItemEnum::Function(Function { + sig: FunctionSignature { + inputs: vec![], + output: Some(Type::ResolvedPath(Path { + path: "Bar".to_owned(), + id: Id(1), + args: None, + })), + is_c_variadic: false, + }, + generics, + header: FunctionHeader { + is_const: false, + is_unsafe: false, + is_async: false, + abi: Abi::Rust, + }, + has_body: true, + }), + }, + ), ]), - paths: FxHashMap::from_iter([(Id(0), ItemSummary { - crate_id: 0, - path: vec!["foo".to_owned()], - kind: ItemKind::Module, - })]), + paths: FxHashMap::from_iter([( + Id(0), + ItemSummary { crate_id: 0, path: vec!["foo".to_owned()], kind: ItemKind::Module }, + )]), external_crates: FxHashMap::default(), format_version: rustdoc_json_types::FORMAT_VERSION, }; - check(&krate, &[Error { - kind: ErrorKind::Custom( - r#"No entry in '$.paths' for Path { path: "Bar", id: Id(1), args: None }"#.to_owned(), - ), - id: Id(1), - }]); + check( + &krate, + &[Error { + kind: ErrorKind::Custom( + r#"No entry in '$.paths' for Path { path: "Bar", id: Id(1), args: None }"# + .to_owned(), + ), + id: Id(1), + }], + ); } #[test] @@ -204,18 +238,25 @@ fn checks_local_crate_id_is_correct() { root: Id(0), crate_version: None, includes_private: false, - index: FxHashMap::from_iter([(Id(0), Item { - id: Id(0), - crate_id: LOCAL_CRATE_ID.wrapping_add(1), - name: Some("irrelavent".to_owned()), - span: None, - visibility: Visibility::Public, - docs: None, - links: FxHashMap::default(), - attrs: Vec::new(), - deprecation: None, - inner: ItemEnum::Module(Module { is_crate: true, items: vec![], is_stripped: false }), - })]), + index: FxHashMap::from_iter([( + Id(0), + Item { + id: Id(0), + crate_id: LOCAL_CRATE_ID.wrapping_add(1), + name: Some("irrelavent".to_owned()), + span: None, + visibility: Visibility::Public, + docs: None, + links: FxHashMap::default(), + attrs: Vec::new(), + deprecation: None, + inner: ItemEnum::Module(Module { + is_crate: true, + items: vec![], + is_stripped: false, + }), + }, + )]), paths: FxHashMap::default(), external_crates: FxHashMap::default(), format_version: FORMAT_VERSION, diff --git a/src/tools/lint-docs/src/lib.rs b/src/tools/lint-docs/src/lib.rs index f6e84465780..9fd33e23204 100644 --- a/src/tools/lint-docs/src/lib.rs +++ b/src/tools/lint-docs/src/lib.rs @@ -19,24 +19,30 @@ mod groups; /// level of the lint, which will be more difficult to support, since rustc /// currently does not track that historical information. static RENAMES: &[(Level, &[(&str, &str)])] = &[ - (Level::Allow, &[ - ("single-use-lifetime", "single-use-lifetimes"), - ("elided-lifetime-in-path", "elided-lifetimes-in-paths"), - ("async-idents", "keyword-idents"), - ("disjoint-capture-migration", "rust-2021-incompatible-closure-captures"), - ("keyword-idents", "keyword-idents-2018"), - ("or-patterns-back-compat", "rust-2021-incompatible-or-patterns"), - ]), - (Level::Warn, &[ - ("bare-trait-object", "bare-trait-objects"), - ("unstable-name-collision", "unstable-name-collisions"), - ("unused-doc-comment", "unused-doc-comments"), - ("redundant-semicolon", "redundant-semicolons"), - ("overlapping-patterns", "overlapping-range-endpoints"), - ("non-fmt-panic", "non-fmt-panics"), - ("unused-tuple-struct-fields", "dead-code"), - ("static-mut-ref", "static-mut-refs"), - ]), + ( + Level::Allow, + &[ + ("single-use-lifetime", "single-use-lifetimes"), + ("elided-lifetime-in-path", "elided-lifetimes-in-paths"), + ("async-idents", "keyword-idents"), + ("disjoint-capture-migration", "rust-2021-incompatible-closure-captures"), + ("keyword-idents", "keyword-idents-2018"), + ("or-patterns-back-compat", "rust-2021-incompatible-or-patterns"), + ], + ), + ( + Level::Warn, + &[ + ("bare-trait-object", "bare-trait-objects"), + ("unstable-name-collision", "unstable-name-collisions"), + ("unused-doc-comment", "unused-doc-comments"), + ("redundant-semicolon", "redundant-semicolons"), + ("overlapping-patterns", "overlapping-range-endpoints"), + ("non-fmt-panic", "non-fmt-panics"), + ("unused-tuple-struct-fields", "dead-code"), + ("static-mut-ref", "static-mut-refs"), + ], + ), (Level::Deny, &[("exceeding-bitshifts", "arithmetic-overflow")]), ]; diff --git a/src/tools/rust-installer/src/compression.rs b/src/tools/rust-installer/src/compression.rs index 96c48657c46..df3a98ae789 100644 --- a/src/tools/rust-installer/src/compression.rs +++ b/src/tools/rust-installer/src/compression.rs @@ -81,14 +81,17 @@ impl CompressionFormat { let file = crate::util::create_new_file(path)?; Ok(match self { - CompressionFormat::Gz => Box::new(GzEncoder::new(file, match profile { - CompressionProfile::Fast => flate2::Compression::fast(), - CompressionProfile::Balanced => flate2::Compression::new(6), - CompressionProfile::Best => flate2::Compression::best(), - CompressionProfile::NoOp => panic!( - "compression profile 'no-op' should not call `CompressionFormat::encode`." - ), - })), + CompressionFormat::Gz => Box::new(GzEncoder::new( + file, + match profile { + CompressionProfile::Fast => flate2::Compression::fast(), + CompressionProfile::Balanced => flate2::Compression::new(6), + CompressionProfile::Best => flate2::Compression::best(), + CompressionProfile::NoOp => panic!( + "compression profile 'no-op' should not call `CompressionFormat::encode`." + ), + }, + )), CompressionFormat::Xz => { let encoder = match profile { CompressionProfile::NoOp => panic!( diff --git a/src/tools/tidy/src/ext_tool_checks.rs b/src/tools/tidy/src/ext_tool_checks.rs index 2a4cff1d12e..4f9a20fa9e2 100644 --- a/src/tools/tidy/src/ext_tool_checks.rs +++ b/src/tools/tidy/src/ext_tool_checks.rs @@ -95,10 +95,14 @@ fn check_impl( if res.is_err() && show_diff { eprintln!("\npython linting failed! Printing diff suggestions:"); - let _ = run_ruff(root_path, outdir, py_path, &cfg_args, &file_args, &[ - "check".as_ref(), - "--diff".as_ref(), - ]); + let _ = run_ruff( + root_path, + outdir, + py_path, + &cfg_args, + &file_args, + &["check".as_ref(), "--diff".as_ref()], + ); } // Rethrow error let _ = res?; @@ -120,10 +124,14 @@ fn check_impl( if show_diff { eprintln!("\npython formatting does not match! Printing diff:"); - let _ = run_ruff(root_path, outdir, py_path, &cfg_args, &file_args, &[ - "format".as_ref(), - "--diff".as_ref(), - ]); + let _ = run_ruff( + root_path, + outdir, + py_path, + &cfg_args, + &file_args, + &["format".as_ref(), "--diff".as_ref()], + ); } eprintln!("rerun tidy with `--extra-checks=py:fmt --bless` to reformat Python code"); } @@ -148,10 +156,11 @@ fn check_impl( let files; if file_args_clang_format.is_empty() { let llvm_wrapper = root_path.join("compiler/rustc_llvm/llvm-wrapper"); - files = find_with_extension(root_path, Some(llvm_wrapper.as_path()), &[ - OsStr::new("h"), - OsStr::new("cpp"), - ])?; + files = find_with_extension( + root_path, + Some(llvm_wrapper.as_path()), + &[OsStr::new("h"), OsStr::new("cpp")], + )?; file_args_clang_format.extend(files.iter().map(|p| p.as_os_str())); } let args = merge_args(&cfg_args_clang_format, &file_args_clang_format); diff --git a/src/tools/tidy/src/known_bug.rs b/src/tools/tidy/src/known_bug.rs index a8771654144..e1921715ab9 100644 --- a/src/tools/tidy/src/known_bug.rs +++ b/src/tools/tidy/src/known_bug.rs @@ -14,13 +14,10 @@ pub fn check(filepath: &Path, bad: &mut bool) { let test_path_segments_str = test_path_segments.iter().map(|s| s.as_str()).collect::>(); - if !matches!(test_path_segments_str[..], [ - .., - "tests", - "crashes", - "auxiliary", - _aux_file_rs - ]) && !contents.lines().any(|line| line.starts_with("//@ known-bug: ")) + if !matches!( + test_path_segments_str[..], + [.., "tests", "crashes", "auxiliary", _aux_file_rs] + ) && !contents.lines().any(|line| line.starts_with("//@ known-bug: ")) { tidy_error!( bad, diff --git a/src/tools/unicode-table-generator/src/raw_emitter.rs b/src/tools/unicode-table-generator/src/raw_emitter.rs index 46010692fe5..ee94d3c93a6 100644 --- a/src/tools/unicode-table-generator/src/raw_emitter.rs +++ b/src/tools/unicode-table-generator/src/raw_emitter.rs @@ -355,12 +355,15 @@ impl Canonicalized { let unique_mapping = unique_mapping .into_iter() .map(|(key, value)| { - (key, match value { - UniqueMapping::Canonicalized(idx) => { - u8::try_from(canonical_words.len() + idx).unwrap() - } - UniqueMapping::Canonical(idx) => u8::try_from(idx).unwrap(), - }) + ( + key, + match value { + UniqueMapping::Canonicalized(idx) => { + u8::try_from(canonical_words.len() + idx).unwrap() + } + UniqueMapping::Canonical(idx) => u8::try_from(idx).unwrap(), + }, + ) }) .collect::>(); @@ -375,21 +378,24 @@ impl Canonicalized { let canonicalized_words = canonicalized_words .into_iter() .map(|v| { - (u8::try_from(v.0).unwrap(), match v.1 { - Mapping::RotateAndInvert(amount) => { - assert_eq!(amount, amount & LOWER_6); - 1 << 6 | (amount as u8) - } - Mapping::Rotate(amount) => { - assert_eq!(amount, amount & LOWER_6); - amount as u8 - } - Mapping::Invert => 1 << 6, - Mapping::ShiftRight(shift_by) => { - assert_eq!(shift_by, shift_by & LOWER_6); - 1 << 7 | (shift_by as u8) - } - }) + ( + u8::try_from(v.0).unwrap(), + match v.1 { + Mapping::RotateAndInvert(amount) => { + assert_eq!(amount, amount & LOWER_6); + 1 << 6 | (amount as u8) + } + Mapping::Rotate(amount) => { + assert_eq!(amount, amount & LOWER_6); + amount as u8 + } + Mapping::Invert => 1 << 6, + Mapping::ShiftRight(shift_by) => { + assert_eq!(shift_by, shift_by & LOWER_6); + 1 << 7 | (shift_by as u8) + } + }, + ) }) .collect::>(); Canonicalized { unique_mapping, canonical_words, canonicalized_words } diff --git a/tests/run-make/wasm-export-all-symbols/rmake.rs b/tests/run-make/wasm-export-all-symbols/rmake.rs index 0c0a785c67c..4148cc29ec2 100644 --- a/tests/run-make/wasm-export-all-symbols/rmake.rs +++ b/tests/run-make/wasm-export-all-symbols/rmake.rs @@ -20,13 +20,16 @@ fn test(args: &[&str]) { rustc().input("main.rs").target("wasm32-wasip1").args(args).run(); verify_exports(Path::new("foo.wasm"), &[("foo", Func), ("FOO", Global), ("memory", Memory)]); - verify_exports(Path::new("main.wasm"), &[ - ("foo", Func), - ("FOO", Global), - ("_start", Func), - ("__main_void", Func), - ("memory", Memory), - ]); + verify_exports( + Path::new("main.wasm"), + &[ + ("foo", Func), + ("FOO", Global), + ("_start", Func), + ("__main_void", Func), + ("memory", Memory), + ], + ); } fn verify_exports(path: &Path, exports: &[(&str, wasmparser::ExternalKind)]) {