diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index ec76a1a42ef..8612a40923a 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -27,3 +27,5 @@ ec2cc761bc7067712ecc7734502f703fe3b024c8 84ac80f1921afc243d71fd0caaa4f2838c294102 # bless mir-opt tests to add `copy` 99cb0c6bc399fb94a0ddde7e9b38e9c00d523bad +# reformat with rustfmt edition 2024 +c682aa162b0d41e21cc6748f4fecfe01efb69d1f diff --git a/.gitmodules b/.gitmodules index 2082ec9ef45..33ea0f53cf1 100644 --- a/.gitmodules +++ b/.gitmodules @@ -33,7 +33,7 @@ [submodule "src/llvm-project"] path = src/llvm-project url = https://github.com/rust-lang/llvm-project.git - branch = rustc/19.1-2024-07-30 + branch = rustc/19.1-2024-09-17 shallow = true [submodule "src/doc/embedded-book"] path = src/doc/embedded-book diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 01593d34c97..620a051eeb7 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -999,8 +999,8 @@ fn univariant_biased< if repr.can_randomize_type_layout() && cfg!(feature = "randomize") { #[cfg(feature = "randomize")] { - use rand::seq::SliceRandom; use rand::SeedableRng; + use rand::seq::SliceRandom; // `ReprOptions.field_shuffle_seed` is a deterministic seed we can use to randomize field // ordering. let mut rng = diff --git a/compiler/rustc_abi/src/lib.rs b/compiler/rustc_abi/src/lib.rs index 904c5933a18..fa7c98a7fa0 100644 --- a/compiler/rustc_abi/src/lib.rs +++ b/compiler/rustc_abi/src/lib.rs @@ -1138,13 +1138,10 @@ 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/src/ast.rs b/compiler/rustc_ast/src/ast.rs index ac65b7b22bc..37f429cce44 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -21,19 +21,19 @@ use std::borrow::Cow; use std::{cmp, fmt, mem}; +pub use GenericArgs::*; +pub use UnsafeSource::*; pub use rustc_ast_ir::{Movability, Mutability}; use rustc_data_structures::packed::Pu128; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::sync::Lrc; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_span::source_map::{respan, Spanned}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; pub use rustc_span::AttrId; -use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; -use thin_vec::{thin_vec, ThinVec}; -pub use GenericArgs::*; -pub use UnsafeSource::*; +use rustc_span::source_map::{Spanned, respan}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; +use thin_vec::{ThinVec, thin_vec}; pub use crate::format::*; use crate::ptr::P; @@ -288,7 +288,7 @@ pub fn as_angle_bracketed_args(&self) -> AngleBracketedArgs { } } -pub use crate::node_id::{NodeId, CRATE_NODE_ID, DUMMY_NODE_ID}; +pub use crate::node_id::{CRATE_NODE_ID, DUMMY_NODE_ID, NodeId}; /// Modifiers on a trait bound like `~const`, `?` and `!`. #[derive(Copy, Clone, PartialEq, Eq, Encodable, Decodable, Debug)] @@ -1187,8 +1187,8 @@ impl Expr { /// `min_const_generics` as more complex expressions are not supported. /// /// Does not ensure that the path resolves to a const param, the caller should check this. - pub fn is_potential_trivial_const_arg(&self) -> bool { - let this = self.maybe_unwrap_block(); + pub fn is_potential_trivial_const_arg(&self, strip_identity_block: bool) -> bool { + let this = if strip_identity_block { self.maybe_unwrap_block().1 } else { self }; if let ExprKind::Path(None, path) = &this.kind && path.is_potential_trivial_const_arg() @@ -1199,14 +1199,15 @@ pub fn is_potential_trivial_const_arg(&self) -> bool { } } - pub fn maybe_unwrap_block(&self) -> &Expr { + /// Returns an expression with (when possible) *one* outter brace removed + pub fn maybe_unwrap_block(&self) -> (bool, &Expr) { if let ExprKind::Block(block, None) = &self.kind && let [stmt] = block.stmts.as_slice() && let StmtKind::Expr(expr) = &stmt.kind { - expr + (true, expr) } else { - self + (false, self) } } diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 94a00ab1a04..124d0acfa49 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -4,15 +4,15 @@ use std::sync::atomic::{AtomicU32, Ordering}; use rustc_index::bit_set::GrowableBitSet; -use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; -use smallvec::{smallvec, SmallVec}; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, Symbol, sym}; +use smallvec::{SmallVec, smallvec}; +use thin_vec::{ThinVec, thin_vec}; use crate::ast::{ - AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, AttrVec, Attribute, DelimArgs, - Expr, ExprKind, LitKind, MetaItem, MetaItemKind, MetaItemLit, NestedMetaItem, NormalAttr, Path, - PathSegment, Safety, DUMMY_NODE_ID, + AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, AttrVec, Attribute, DUMMY_NODE_ID, + DelimArgs, Expr, ExprKind, LitKind, MetaItem, MetaItemKind, MetaItemLit, NestedMetaItem, + NormalAttr, Path, PathSegment, Safety, }; use crate::ptr::P; use crate::token::{self, CommentKind, Delimiter, Token}; diff --git a/compiler/rustc_ast/src/entry.rs b/compiler/rustc_ast/src/entry.rs index 53276e0847a..45c4caca6e9 100644 --- a/compiler/rustc_ast/src/entry.rs +++ b/compiler/rustc_ast/src/entry.rs @@ -1,7 +1,7 @@ -use rustc_span::symbol::sym; use rustc_span::Symbol; +use rustc_span::symbol::sym; -use crate::{attr, Attribute}; +use crate::{Attribute, attr}; #[derive(Debug)] pub enum EntryPointType { diff --git a/compiler/rustc_ast/src/expand/allocator.rs b/compiler/rustc_ast/src/expand/allocator.rs index 1723501d0fe..bee7dfb61da 100644 --- a/compiler/rustc_ast/src/expand/allocator.rs +++ b/compiler/rustc_ast/src/expand/allocator.rs @@ -1,5 +1,5 @@ use rustc_macros::HashStable_Generic; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; #[derive(Clone, Debug, Copy, Eq, PartialEq, HashStable_Generic)] pub enum AllocatorKind { diff --git a/compiler/rustc_ast/src/format.rs b/compiler/rustc_ast/src/format.rs index e72d32d9b75..d5900d83e4d 100644 --- a/compiler/rustc_ast/src/format.rs +++ b/compiler/rustc_ast/src/format.rs @@ -1,10 +1,10 @@ use rustc_data_structures::fx::FxHashMap; use rustc_macros::{Decodable, Encodable}; -use rustc_span::symbol::{Ident, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Ident, Symbol}; -use crate::ptr::P; use crate::Expr; +use crate::ptr::P; // Definitions: // diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index 1bef51aa73f..104f84f26e0 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -13,10 +13,10 @@ use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_data_structures::sync::Lrc; +use rustc_span::Span; use rustc_span::source_map::Spanned; use rustc_span::symbol::Ident; -use rustc_span::Span; -use smallvec::{smallvec, Array, SmallVec}; +use smallvec::{Array, SmallVec, smallvec}; use thin_vec::ThinVec; use crate::ast::*; diff --git a/compiler/rustc_ast/src/token.rs b/compiler/rustc_ast/src/token.rs index a0082a41713..1d6abbef06c 100644 --- a/compiler/rustc_ast/src/token.rs +++ b/compiler/rustc_ast/src/token.rs @@ -1,21 +1,21 @@ use std::borrow::Cow; use std::fmt; -use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_data_structures::sync::Lrc; -use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_span::edition::Edition; -use rustc_span::symbol::{kw, sym}; -#[allow(clippy::useless_attribute)] // FIXME: following use of `hidden_glob_reexports` incorrectly triggers `useless_attribute` lint. -#[allow(hidden_glob_reexports)] -use rustc_span::symbol::{Ident, Symbol}; -use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; pub use BinOpToken::*; pub use LitKind::*; pub use Nonterminal::*; pub use NtExprKind::*; pub use NtPatKind::*; pub use TokenKind::*; +use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; +use rustc_data_structures::sync::Lrc; +use rustc_macros::{Decodable, Encodable, HashStable_Generic}; +use rustc_span::edition::Edition; +#[allow(clippy::useless_attribute)] // FIXME: following use of `hidden_glob_reexports` incorrectly triggers `useless_attribute` lint. +#[allow(hidden_glob_reexports)] +use rustc_span::symbol::{Ident, Symbol}; +use rustc_span::symbol::{kw, sym}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use crate::ast; use crate::ptr::P; @@ -385,35 +385,41 @@ pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { Literal(Lit::new(kind, symbol, suffix)) } - /// An approximation to proc-macro-style single-character operators used by rustc parser. - /// If the operator token can be broken into two tokens, the first of which is single-character, - /// then this function performs that operation, otherwise it returns `None`. - pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { - Some(match *self { - Le => (Lt, Eq), - EqEq => (Eq, Eq), - Ne => (Not, Eq), - Ge => (Gt, Eq), - AndAnd => (BinOp(And), BinOp(And)), - OrOr => (BinOp(Or), BinOp(Or)), - BinOp(Shl) => (Lt, Lt), - BinOp(Shr) => (Gt, Gt), - BinOpEq(Plus) => (BinOp(Plus), Eq), - BinOpEq(Minus) => (BinOp(Minus), Eq), - BinOpEq(Star) => (BinOp(Star), Eq), - BinOpEq(Slash) => (BinOp(Slash), Eq), - BinOpEq(Percent) => (BinOp(Percent), Eq), - BinOpEq(Caret) => (BinOp(Caret), Eq), - BinOpEq(And) => (BinOp(And), Eq), - BinOpEq(Or) => (BinOp(Or), Eq), - BinOpEq(Shl) => (Lt, Le), - BinOpEq(Shr) => (Gt, Ge), - DotDot => (Dot, Dot), - DotDotDot => (Dot, DotDot), - PathSep => (Colon, Colon), - RArrow => (BinOp(Minus), Gt), - LArrow => (Lt, BinOp(Minus)), - FatArrow => (Eq, Gt), + /// An approximation to proc-macro-style single-character operators used by + /// rustc parser. If the operator token can be broken into two tokens, the + /// first of which has `n` (1 or 2) chars, then this function performs that + /// operation, otherwise it returns `None`. + pub fn break_two_token_op(&self, n: u32) -> Option<(TokenKind, TokenKind)> { + assert!(n == 1 || n == 2); + Some(match (self, n) { + (Le, 1) => (Lt, Eq), + (EqEq, 1) => (Eq, Eq), + (Ne, 1) => (Not, Eq), + (Ge, 1) => (Gt, Eq), + (AndAnd, 1) => (BinOp(And), BinOp(And)), + (OrOr, 1) => (BinOp(Or), BinOp(Or)), + (BinOp(Shl), 1) => (Lt, Lt), + (BinOp(Shr), 1) => (Gt, Gt), + (BinOpEq(Plus), 1) => (BinOp(Plus), Eq), + (BinOpEq(Minus), 1) => (BinOp(Minus), Eq), + (BinOpEq(Star), 1) => (BinOp(Star), Eq), + (BinOpEq(Slash), 1) => (BinOp(Slash), Eq), + (BinOpEq(Percent), 1) => (BinOp(Percent), Eq), + (BinOpEq(Caret), 1) => (BinOp(Caret), Eq), + (BinOpEq(And), 1) => (BinOp(And), Eq), + (BinOpEq(Or), 1) => (BinOp(Or), Eq), + (BinOpEq(Shl), 1) => (Lt, Le), // `<` + `<=` + (BinOpEq(Shl), 2) => (BinOp(Shl), Eq), // `<<` + `=` + (BinOpEq(Shr), 1) => (Gt, Ge), // `>` + `>=` + (BinOpEq(Shr), 2) => (BinOp(Shr), Eq), // `>>` + `=` + (DotDot, 1) => (Dot, Dot), + (DotDotDot, 1) => (Dot, DotDot), // `.` + `..` + (DotDotDot, 2) => (DotDot, Dot), // `..` + `.` + (DotDotEq, 2) => (DotDot, Eq), + (PathSep, 1) => (Colon, Colon), + (RArrow, 1) => (BinOp(Minus), Gt), + (LArrow, 1) => (Lt, BinOp(Minus)), + (FatArrow, 1) => (Eq, Gt), _ => return None, }) } diff --git a/compiler/rustc_ast/src/tokenstream.rs b/compiler/rustc_ast/src/tokenstream.rs index fc1dd2caf68..d5c2bc1c7f6 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -20,7 +20,7 @@ use rustc_data_structures::sync::{self, Lrc}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_serialize::{Decodable, Encodable}; -use rustc_span::{sym, Span, SpanDecoder, SpanEncoder, Symbol, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span, SpanDecoder, SpanEncoder, Symbol, sym}; use crate::ast::{AttrStyle, StmtKind}; use crate::ast_traits::{HasAttrs, HasTokens}; diff --git a/compiler/rustc_ast/src/util/literal.rs b/compiler/rustc_ast/src/util/literal.rs index 3bd2a80d361..498df5a7144 100644 --- a/compiler/rustc_ast/src/util/literal.rs +++ b/compiler/rustc_ast/src/util/literal.rs @@ -3,10 +3,10 @@ use std::{ascii, fmt, str}; use rustc_lexer::unescape::{ - byte_from_char, unescape_byte, unescape_char, unescape_mixed, unescape_unicode, MixedUnit, Mode, + MixedUnit, Mode, byte_from_char, unescape_byte, unescape_char, unescape_mixed, unescape_unicode, }; -use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, kw, sym}; use tracing::debug; use crate::ast::{self, LitKind, MetaItemLit, StrStyle}; diff --git a/compiler/rustc_ast/src/visit.rs b/compiler/rustc_ast/src/visit.rs index bae7ad93f90..9f9c3d8c392 100644 --- a/compiler/rustc_ast/src/visit.rs +++ b/compiler/rustc_ast/src/visit.rs @@ -15,8 +15,8 @@ pub use rustc_ast_ir::visit::VisitorResult; pub use rustc_ast_ir::{try_visit, visit_opt, walk_list, walk_visitable_list}; -use rustc_span::symbol::Ident; use rustc_span::Span; +use rustc_span::symbol::Ident; use crate::ast::*; use crate::ptr::P; diff --git a/compiler/rustc_ast_lowering/src/asm.rs b/compiler/rustc_ast_lowering/src/asm.rs index 6c966c9f73a..88cdb2ec363 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -8,9 +8,10 @@ use rustc_hir::def::{DefKind, Res}; use rustc_session::parse::feature_err; use rustc_span::symbol::kw; -use rustc_span::{sym, Span}; +use rustc_span::{Span, sym}; use rustc_target::asm; +use super::LoweringContext; use super::errors::{ AbiSpecifiedMultipleTimes, AttSyntaxOnlyX86, ClobberAbiNotSupported, InlineAsmUnsupportedTarget, InvalidAbiClobberAbi, InvalidAsmTemplateModifierConst, @@ -18,10 +19,9 @@ InvalidAsmTemplateModifierRegClassSub, InvalidAsmTemplateModifierSym, InvalidRegister, InvalidRegisterClass, RegisterClassOnlyClobber, RegisterConflict, }; -use super::LoweringContext; use crate::{ - fluent_generated as fluent, AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, - ParamMode, ResolverAstLoweringExt, + AllowReturnTypeNotation, ImplTraitContext, ImplTraitPosition, ParamMode, + ResolverAstLoweringExt, fluent_generated as fluent, }; impl<'a, 'hir> LoweringContext<'a, 'hir> { @@ -221,7 +221,7 @@ pub(crate) fn lower_inline_asm( let parent_def_id = self.current_def_id_parent; let node_id = self.next_node_id(); // HACK(min_generic_const_args): see lower_anon_const - if !expr.is_potential_trivial_const_arg() { + if !expr.is_potential_trivial_const_arg(true) { self.create_def( parent_def_id, node_id, diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index 97483e85f77..3b85f1737bd 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -46,8 +46,8 @@ use rustc_hir::def_id::DefId; use rustc_middle::span_bug; use rustc_middle::ty::{Asyncness, ResolverAstLowering}; -use rustc_span::symbol::Ident; use rustc_span::Span; +use rustc_span::symbol::Ident; use rustc_target::spec::abi; use {rustc_ast as ast, rustc_hir as hir}; diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 974144cc8d9..52372bbf991 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -4,14 +4,14 @@ use rustc_ast::*; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; -use rustc_hir::def::{DefKind, Res}; use rustc_hir::HirId; +use rustc_hir::def::{DefKind, Res}; use rustc_middle::span_bug; use rustc_session::errors::report_lit_error; -use rustc_span::source_map::{respan, Spanned}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{DesugaringKind, Span, DUMMY_SP}; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::source_map::{Spanned, respan}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, DesugaringKind, Span}; +use thin_vec::{ThinVec, thin_vec}; use super::errors::{ AsyncCoroutinesNotSupported, AwaitOnlyInAsyncFnAndBlocks, BaseExpressionDoubleDot, @@ -23,7 +23,7 @@ GenericArgsMode, ImplTraitContext, LoweringContext, ParamMode, ResolverAstLoweringExt, }; use crate::errors::YieldInClosure; -use crate::{fluent_generated, AllowReturnTypeNotation, FnDeclKind, ImplTraitPosition}; +use crate::{AllowReturnTypeNotation, FnDeclKind, ImplTraitPosition, fluent_generated}; impl<'hir> LoweringContext<'_, 'hir> { fn lower_exprs(&mut self, exprs: &[AstP]) -> &'hir [hir::Expr<'hir>] { @@ -389,7 +389,7 @@ fn lower_legacy_const_generics( let node_id = self.next_node_id(); // HACK(min_generic_const_args): see lower_anon_const - if !arg.is_potential_trivial_const_arg() { + if !arg.is_potential_trivial_const_arg(true) { // Add a definition for the in-band const def. self.create_def(parent_def_id, node_id, kw::Empty, DefKind::AnonConst, f.span); } @@ -725,18 +725,15 @@ pub(super) fn maybe_forward_track_caller( span, Some(self.allow_gen_future.clone()), ); - 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 8c742d2aaf4..653116e1fe0 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -6,8 +6,8 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_hir as hir; use rustc_session::config::FmtDebug; -use rustc_span::symbol::{kw, Ident}; -use rustc_span::{sym, Span, Symbol}; +use rustc_span::symbol::{Ident, kw}; +use rustc_span::{Span, Symbol, sym}; use super::LoweringContext; @@ -363,16 +363,13 @@ 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/index.rs b/compiler/rustc_ast_lowering/src/index.rs index f90a0612db6..e77c0fb3a3e 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -6,7 +6,7 @@ use rustc_index::IndexVec; use rustc_middle::span_bug; use rustc_middle::ty::TyCtxt; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; /// A visitor that walks over the HIR and collects `Node`s into a HIR map. diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index 73c604bf28a..7bb3b2fa290 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -3,17 +3,17 @@ use rustc_ast::*; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; -use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; use rustc_hir::PredicateOrigin; +use rustc_hir::def::{DefKind, Res}; +use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::span_bug; use rustc_middle::ty::{ResolverAstLowering, TyCtxt}; use rustc_span::edit_distance::find_best_match_for_name; -use rustc_span::symbol::{kw, sym, Ident}; +use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{DesugaringKind, Span, Symbol}; use rustc_target::spec::abi; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; use tracing::instrument; @@ -281,16 +281,13 @@ fn lower_item_kind( ); 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, - }, - fn_kind: None, + Some(ty) => this.lower_ty(ty, ImplTraitContext::OpaqueTy { + origin: hir::OpaqueTyOrigin::TyAlias { + parent: this.local_def_id(id), + in_assoc_ty: false, }, - ), + fn_kind: None, + }), }, ); hir::ItemKind::TyAlias(ty, generics) @@ -981,16 +978,13 @@ fn lower_impl_item( 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, - }, - fn_kind: None, + let ty = this.lower_ty(ty, ImplTraitContext::OpaqueTy { + origin: hir::OpaqueTyOrigin::TyAlias { + parent: this.local_def_id(i.id), + in_assoc_ty: true, }, - ); + fn_kind: None, + }); hir::ImplItemKind::Type(ty) } }, @@ -1129,13 +1123,10 @@ fn lower_block_expr_opt(&mut self, span: Span, block: Option<&Block>) -> hir::Ex 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")), + }) }) } @@ -1515,10 +1506,10 @@ fn lower_generics( for bound in &bound_pred.bounds { if !matches!( *bound, - GenericBound::Trait( - _, - TraitBoundModifiers { polarity: BoundPolarity::Maybe(_), .. } - ) + GenericBound::Trait(_, TraitBoundModifiers { + polarity: BoundPolarity::Maybe(_), + .. + }) ) { continue; } @@ -1619,16 +1610,13 @@ fn lower_generics( self.children.push((anon_const_did, hir::MaybeOwner::NonOwner(const_id))); let const_body = self.lower_body(|this| { - ( - &[], - hir::Expr { - hir_id: const_expr_id, - kind: hir::ExprKind::Lit( - this.arena.alloc(hir::Lit { node: LitKind::Bool(true), span }), - ), - span, - }, - ) + (&[], hir::Expr { + hir_id: const_expr_id, + kind: hir::ExprKind::Lit( + this.arena.alloc(hir::Lit { node: LitKind::Bool(true), span }), + ), + span, + }) }); let default_ac = self.arena.alloc(hir::AnonConst { diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index d13e26d2510..c6cb7aa7dd5 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -53,7 +53,7 @@ use rustc_data_structures::sync::Lrc; use rustc_errors::{DiagArgFromDisplay, DiagCtxtHandle, StashKey}; use rustc_hir::def::{DefKind, LifetimeRes, Namespace, PartialRes, PerNS, Res}; -use rustc_hir::def_id::{LocalDefId, LocalDefIdMap, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalDefIdMap}; use rustc_hir::{ self as hir, ConstArg, GenericArg, HirId, ItemLocalMap, MissingLifetimeKind, ParamName, TraitCandidate, @@ -63,9 +63,9 @@ use rustc_middle::span_bug; use rustc_middle::ty::{ResolverAstLowering, TyCtxt}; use rustc_session::parse::{add_feature_diagnostics, feature_err}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{DesugaringKind, Span, DUMMY_SP}; -use smallvec::{smallvec, SmallVec}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, DesugaringKind, Span}; +use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; use tracing::{debug, instrument, trace}; @@ -2466,7 +2466,7 @@ fn lower_anon_const_to_const_arg_direct(&mut self, anon: &AnonConst) -> hir::Con /// See [`hir::ConstArg`] for when to use this function vs /// [`Self::lower_anon_const_to_const_arg`]. fn lower_anon_const_to_anon_const(&mut self, c: &AnonConst) -> &'hir hir::AnonConst { - if c.value.is_potential_trivial_const_arg() { + if c.value.is_potential_trivial_const_arg(true) { // HACK(min_generic_const_args): see DefCollector::visit_anon_const // Over there, we guess if this is a bare param and only create a def if // we think it's not. However we may can guess wrong (see there for example) diff --git a/compiler/rustc_ast_lowering/src/lifetime_collector.rs b/compiler/rustc_ast_lowering/src/lifetime_collector.rs index 76c957afa54..1e82ba5db8a 100644 --- a/compiler/rustc_ast_lowering/src/lifetime_collector.rs +++ b/compiler/rustc_ast_lowering/src/lifetime_collector.rs @@ -4,8 +4,8 @@ use rustc_hir::def::{DefKind, LifetimeRes, Res}; use rustc_middle::span_bug; use rustc_middle::ty::ResolverAstLowering; -use rustc_span::symbol::{kw, Ident}; use rustc_span::Span; +use rustc_span::symbol::{Ident, kw}; use super::ResolverAstLoweringExt; diff --git a/compiler/rustc_ast_lowering/src/pat.rs b/compiler/rustc_ast_lowering/src/pat.rs index 584d94ebe2d..760f84564f1 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -3,9 +3,9 @@ use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; use rustc_hir::def::Res; +use rustc_span::Span; use rustc_span::source_map::Spanned; use rustc_span::symbol::Ident; -use rustc_span::Span; use super::errors::{ ArbitraryExpressionInPattern, ExtraDoubleDot, MisplacedDoubleDot, SubTupleBinding, diff --git a/compiler/rustc_ast_lowering/src/path.rs b/compiler/rustc_ast_lowering/src/path.rs index 03c8097e4c3..e60488fdc8c 100644 --- a/compiler/rustc_ast_lowering/src/path.rs +++ b/compiler/rustc_ast_lowering/src/path.rs @@ -1,14 +1,14 @@ use rustc_ast::{self as ast, *}; use rustc_data_structures::sync::Lrc; use rustc_hir as hir; +use rustc_hir::GenericArg; use rustc_hir::def::{DefKind, PartialRes, Res}; use rustc_hir::def_id::DefId; -use rustc_hir::GenericArg; use rustc_middle::span_bug; use rustc_session::parse::add_feature_diagnostics; -use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::{BytePos, DesugaringKind, Span, Symbol, DUMMY_SP}; -use smallvec::{smallvec, SmallVec}; +use rustc_span::symbol::{Ident, kw, sym}; +use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Span, Symbol}; +use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; use super::errors::{ diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 93881f5ed42..229d04f8de2 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -21,21 +21,21 @@ use itertools::{Either, Itertools}; use rustc_ast::ptr::P; -use rustc_ast::visit::{walk_list, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor}; +use rustc_ast::visit::{AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, walk_list}; use rustc_ast::*; use rustc_ast_pretty::pprust::{self, State}; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::DiagCtxtHandle; use rustc_feature::Features; use rustc_parse::validate_attr; +use rustc_session::Session; use rustc_session::lint::builtin::{ DEPRECATED_WHERE_CLAUSE_LOCATION, MISSING_ABI, MISSING_UNSAFE_ON_EXTERN, PATTERNS_IN_FNS_WITHOUT_BODY, }; use rustc_session::lint::{BuiltinLintDiag, LintBuffer}; -use rustc_session::Session; -use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; +use rustc_span::symbol::{Ident, kw, sym}; use rustc_target::spec::abi; use thin_vec::thin_vec; diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index cfc534acd98..614a99a6e19 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -1,12 +1,12 @@ use rustc_ast as ast; use rustc_ast::visit::{self, AssocCtxt, FnCtxt, FnKind, Visitor}; -use rustc_ast::{attr, token, NodeId, PatKind}; -use rustc_feature::{AttributeGate, BuiltinAttribute, Features, GateIssue, BUILTIN_ATTRIBUTE_MAP}; -use rustc_session::parse::{feature_err, feature_err_issue, feature_warn}; +use rustc_ast::{NodeId, PatKind, attr, token}; +use rustc_feature::{AttributeGate, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute, Features, GateIssue}; use rustc_session::Session; +use rustc_session::parse::{feature_err, feature_err_issue, feature_warn}; +use rustc_span::Span; use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; -use rustc_span::Span; use rustc_target::spec::abi; use thin_vec::ThinVec; diff --git a/compiler/rustc_ast_passes/src/node_count.rs b/compiler/rustc_ast_passes/src/node_count.rs index c61640de6f7..e22e99f6e4d 100644 --- a/compiler/rustc_ast_passes/src/node_count.rs +++ b/compiler/rustc_ast_passes/src/node_count.rs @@ -2,8 +2,8 @@ use rustc_ast::visit::*; use rustc_ast::*; -use rustc_span::symbol::Ident; use rustc_span::Span; +use rustc_span::symbol::Ident; pub struct NodeCounter { pub count: usize, diff --git a/compiler/rustc_ast_pretty/src/pp/convenience.rs b/compiler/rustc_ast_pretty/src/pp/convenience.rs index 7559b181f7d..a1c07bb07e4 100644 --- a/compiler/rustc_ast_pretty/src/pp/convenience.rs +++ b/compiler/rustc_ast_pretty/src/pp/convenience.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use crate::pp::{BeginToken, BreakToken, Breaks, IndentStyle, Printer, Token, SIZE_INFINITY}; +use crate::pp::{BeginToken, BreakToken, Breaks, IndentStyle, Printer, SIZE_INFINITY, Token}; impl Printer { /// "raw box" diff --git a/compiler/rustc_ast_pretty/src/pprust/mod.rs b/compiler/rustc_ast_pretty/src/pprust/mod.rs index cfcc28ba76f..726ceebe3c5 100644 --- a/compiler/rustc_ast_pretty/src/pprust/mod.rs +++ b/compiler/rustc_ast_pretty/src/pprust/mod.rs @@ -7,7 +7,7 @@ use rustc_ast as ast; use rustc_ast::token::{Nonterminal, Token, TokenKind}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; -pub use state::{print_crate, AnnNode, Comments, PpAnn, PrintState, State}; +pub use state::{AnnNode, Comments, PpAnn, PrintState, State, print_crate}; pub fn nonterminal_to_string(nt: &Nonterminal) -> String { State::new().nonterminal_to_string(nt) diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 3b1449d9a91..7e07ccf28a0 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -18,14 +18,14 @@ use rustc_ast::util::classify; use rustc_ast::util::comments::{Comment, CommentStyle}; use rustc_ast::{ - self as ast, attr, AttrArgs, AttrArgsEq, BindingMode, BlockCheckMode, ByRef, DelimArgs, - GenericArg, GenericBound, InlineAsmOperand, InlineAsmOptions, InlineAsmRegOrRegClass, - InlineAsmTemplatePiece, PatKind, RangeEnd, RangeSyntax, Safety, SelfKind, Term, + self as ast, AttrArgs, AttrArgsEq, BindingMode, BlockCheckMode, ByRef, DelimArgs, GenericArg, + GenericBound, InlineAsmOperand, InlineAsmOptions, InlineAsmRegOrRegClass, + InlineAsmTemplatePiece, PatKind, RangeEnd, RangeSyntax, Safety, SelfKind, Term, attr, }; use rustc_span::edition::Edition; use rustc_span::source_map::{SourceMap, Spanned}; -use rustc_span::symbol::{kw, sym, Ident, IdentPrinter, Symbol}; -use rustc_span::{BytePos, CharPos, FileName, Pos, Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, IdentPrinter, Symbol, kw, sym}; +use rustc_span::{BytePos, CharPos, DUMMY_SP, FileName, Pos, Span}; use thin_vec::ThinVec; use crate::pp::Breaks::{Consistent, Inconsistent}; @@ -292,9 +292,9 @@ pub fn print_crate<'a>( /// - #73345: `#[allow(unused)]` must be printed rather than `# [allow(unused)]` /// fn space_between(tt1: &TokenTree, tt2: &TokenTree) -> bool { - use token::*; use Delimiter::*; use TokenTree::{Delimited as Del, Token as Tok}; + use token::*; fn is_punct(tt: &TokenTree) -> bool { matches!(tt, TokenTree::Token(tok, _) if tok.is_punct()) diff --git a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs index b13c89c435d..893bfaf8f71 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/expr.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/expr.rs @@ -7,13 +7,13 @@ use rustc_ast::util::literal::escape_byte_str_symbol; use rustc_ast::util::parser::{self, AssocOp, Fixity}; use rustc_ast::{ - self as ast, token, BlockCheckMode, FormatAlignment, FormatArgPosition, FormatArgsPiece, - FormatCount, FormatDebugHex, FormatSign, FormatTrait, + self as ast, BlockCheckMode, FormatAlignment, FormatArgPosition, FormatArgsPiece, FormatCount, + FormatDebugHex, FormatSign, FormatTrait, token, }; use crate::pp::Breaks::Inconsistent; use crate::pprust::state::fixup::FixupContext; -use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; +use crate::pprust::state::{AnnNode, INDENT_UNIT, PrintState, State}; impl<'a> State<'a> { fn print_else(&mut self, els: Option<&ast::Expr>) { diff --git a/compiler/rustc_ast_pretty/src/pprust/state/fixup.rs b/compiler/rustc_ast_pretty/src/pprust/state/fixup.rs index c9baca72485..50fd12a4e8b 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/fixup.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/fixup.rs @@ -1,5 +1,5 @@ -use rustc_ast::util::{classify, parser}; use rustc_ast::Expr; +use rustc_ast::util::{classify, parser}; #[derive(Copy, Clone, Debug)] pub(crate) struct FixupContext { diff --git a/compiler/rustc_ast_pretty/src/pprust/state/item.rs b/compiler/rustc_ast_pretty/src/pprust/state/item.rs index 85a0b3b2022..8217b6df5b4 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state/item.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state/item.rs @@ -1,13 +1,13 @@ use ast::StaticItem; use itertools::{Itertools, Position}; use rustc_ast as ast; -use rustc_ast::ptr::P; use rustc_ast::ModKind; +use rustc_ast::ptr::P; use rustc_span::symbol::Ident; use crate::pp::Breaks::Inconsistent; use crate::pprust::state::fixup::FixupContext; -use crate::pprust::state::{AnnNode, PrintState, State, INDENT_UNIT}; +use crate::pprust::state::{AnnNode, INDENT_UNIT, PrintState, State}; enum DelegationKind<'a> { Single, diff --git a/compiler/rustc_ast_pretty/src/pprust/tests.rs b/compiler/rustc_ast_pretty/src/pprust/tests.rs index 3fefc523f88..01e5dff34b7 100644 --- a/compiler/rustc_ast_pretty/src/pprust/tests.rs +++ b/compiler/rustc_ast_pretty/src/pprust/tests.rs @@ -1,6 +1,6 @@ use rustc_ast as ast; use rustc_span::symbol::Ident; -use rustc_span::{create_default_session_globals_then, DUMMY_SP}; +use rustc_span::{DUMMY_SP, create_default_session_globals_then}; use thin_vec::ThinVec; use super::*; diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index 309049b98f0..dcc4cf2478f 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -4,21 +4,21 @@ use rustc_abi::Align; use rustc_ast::{ - self as ast, attr, Attribute, LitKind, MetaItem, MetaItemKind, MetaItemLit, NestedMetaItem, - NodeId, + self as ast, Attribute, LitKind, MetaItem, MetaItemKind, MetaItemLit, NestedMetaItem, NodeId, + attr, }; use rustc_ast_pretty::pprust; use rustc_errors::ErrorGuaranteed; -use rustc_feature::{find_gated_cfg, is_builtin_attr_name, Features, GatedCfg}; +use rustc_feature::{Features, GatedCfg, find_gated_cfg, is_builtin_attr_name}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_session::config::ExpectedValues; -use rustc_session::lint::builtin::UNEXPECTED_CFGS; use rustc_session::lint::BuiltinLintDiag; +use rustc_session::lint::builtin::UNEXPECTED_CFGS; use rustc_session::parse::feature_err; use rustc_session::{RustcVersion, Session}; -use rustc_span::hygiene::Transparency; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_span::hygiene::Transparency; +use rustc_span::symbol::{Symbol, sym}; use crate::fluent_generated; use crate::session_diagnostics::{self, IncorrectReprFormatGenericCause}; diff --git a/compiler/rustc_attr/src/lib.rs b/compiler/rustc_attr/src/lib.rs index 0dad6372389..bb207c5c952 100644 --- a/compiler/rustc_attr/src/lib.rs +++ b/compiler/rustc_attr/src/lib.rs @@ -15,11 +15,11 @@ mod builtin; mod session_diagnostics; -pub use builtin::*; -pub use rustc_ast::attr::*; -pub(crate) use rustc_session::HashStableContext; pub use IntType::*; pub use ReprAttr::*; pub use StabilityLevel::*; +pub use builtin::*; +pub use rustc_ast::attr::*; +pub(crate) use rustc_session::HashStableContext; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_attr/src/session_diagnostics.rs b/compiler/rustc_attr/src/session_diagnostics.rs index 234a0ef28a2..959a5a4bba7 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -6,7 +6,7 @@ use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol}; -use crate::{fluent_generated as fluent, UnsupportedLiteralReason}; +use crate::{UnsupportedLiteralReason, fluent_generated as fluent}; #[derive(Diagnostic)] #[diag(attr_expected_one_cfg_pattern, code = E0536)] @@ -203,20 +203,16 @@ 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_unsupported_literal_generic, - UnsupportedLiteralReason::CfgString => fluent::attr_unsupported_literal_cfg_string, - UnsupportedLiteralReason::DeprecatedString => { - fluent::attr_unsupported_literal_deprecated_string - } - UnsupportedLiteralReason::DeprecatedKvPair => { - fluent::attr_unsupported_literal_deprecated_kv_pair - } - }, - ); + let mut diag = Diag::new(dcx, level, match self.reason { + UnsupportedLiteralReason::Generic => fluent::attr_unsupported_literal_generic, + UnsupportedLiteralReason::CfgString => fluent::attr_unsupported_literal_cfg_string, + UnsupportedLiteralReason::DeprecatedString => { + fluent::attr_unsupported_literal_deprecated_string + } + UnsupportedLiteralReason::DeprecatedKvPair => { + fluent::attr_unsupported_literal_deprecated_kv_pair + } + }); diag.span(self.span); diag.code(E0565); if self.is_bytestr { diff --git a/compiler/rustc_borrowck/src/borrow_set.rs b/compiler/rustc_borrowck/src/borrow_set.rs index fbda44550a1..a8ade54732f 100644 --- a/compiler/rustc_borrowck/src/borrow_set.rs +++ b/compiler/rustc_borrowck/src/borrow_set.rs @@ -4,15 +4,15 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_index::bit_set::BitSet; use rustc_middle::mir::visit::{MutatingUseContext, NonUseContext, PlaceContext, Visitor}; -use rustc_middle::mir::{self, traversal, Body, Local, Location}; +use rustc_middle::mir::{self, Body, Local, Location, traversal}; use rustc_middle::span_bug; use rustc_middle::ty::{RegionVid, TyCtxt}; use rustc_mir_dataflow::move_paths::MoveData; use tracing::debug; +use crate::BorrowIndex; use crate::path_utils::allow_two_phase_borrow; use crate::place_ext::PlaceExt; -use crate::BorrowIndex; pub struct BorrowSet<'tcx> { /// The fundamental map relating bitvector indexes to the borrows diff --git a/compiler/rustc_borrowck/src/borrowck_errors.rs b/compiler/rustc_borrowck/src/borrowck_errors.rs index 3a7e407f3e7..30e94b0bec7 100644 --- a/compiler/rustc_borrowck/src/borrowck_errors.rs +++ b/compiler/rustc_borrowck/src/borrowck_errors.rs @@ -2,7 +2,7 @@ #![allow(rustc::untranslatable_diagnostic)] use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, Applicability, Diag, DiagCtxtHandle}; +use rustc_errors::{Applicability, Diag, DiagCtxtHandle, struct_span_code_err}; use rustc_hir as hir; use rustc_middle::span_bug; use rustc_middle::ty::{self, Ty, TyCtxt}; diff --git a/compiler/rustc_borrowck/src/consumers.rs b/compiler/rustc_borrowck/src/consumers.rs index 8f560635cb3..c994c4dc1e4 100644 --- a/compiler/rustc_borrowck/src/consumers.rs +++ b/compiler/rustc_borrowck/src/consumers.rs @@ -8,12 +8,12 @@ use rustc_middle::ty::TyCtxt; pub use super::constraints::OutlivesConstraint; -pub use super::dataflow::{calculate_borrows_out_of_scope_at_location, BorrowIndex, Borrows}; +pub use super::dataflow::{BorrowIndex, Borrows, calculate_borrows_out_of_scope_at_location}; pub use super::facts::{AllFacts as PoloniusInput, RustcFacts}; pub use super::location::{LocationTable, RichLocation}; pub use super::nll::PoloniusOutput; pub use super::place_ext::PlaceExt; -pub use super::places_conflict::{places_conflict, PlaceConflictBias}; +pub use super::places_conflict::{PlaceConflictBias, places_conflict}; pub use super::region_infer::RegionInferenceContext; use crate::borrow_set::BorrowSet; diff --git a/compiler/rustc_borrowck/src/dataflow.rs b/compiler/rustc_borrowck/src/dataflow.rs index 5e1043ec817..4af5a10f581 100644 --- a/compiler/rustc_borrowck/src/dataflow.rs +++ b/compiler/rustc_borrowck/src/dataflow.rs @@ -12,7 +12,7 @@ use rustc_mir_dataflow::{Analysis, AnalysisDomain, Forward, GenKill, Results, ResultsVisitable}; use tracing::debug; -use crate::{places_conflict, BorrowSet, PlaceConflictBias, PlaceExt, RegionInferenceContext}; +use crate::{BorrowSet, PlaceConflictBias, PlaceExt, RegionInferenceContext, places_conflict}; /// The results of the dataflow analyses used by the borrow checker. pub(crate) struct BorrowckResults<'a, 'tcx> { diff --git a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs index ee28e556cbc..40a6d506ffa 100644 --- a/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/bound_region_errors.rs @@ -14,18 +14,18 @@ self, RePlaceholder, Region, RegionVid, Ty, TyCtxt, TypeFoldable, UniverseIndex, }; use rustc_span::Span; -use rustc_trait_selection::error_reporting::infer::nice_region_error::NiceRegionError; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; -use rustc_trait_selection::traits::query::type_op; +use rustc_trait_selection::error_reporting::infer::nice_region_error::NiceRegionError; use rustc_trait_selection::traits::ObligationCtxt; +use rustc_trait_selection::traits::query::type_op; use rustc_traits::{type_op_ascribe_user_type_with_span, type_op_prove_predicate_with_cause}; use tracing::{debug, instrument}; +use crate::MirBorrowckCtxt; use crate::region_infer::values::RegionElement; use crate::session_diagnostics::{ HigherRankedErrorCause, HigherRankedLifetimeError, HigherRankedSubtypeError, }; -use crate::MirBorrowckCtxt; #[derive(Clone)] pub(crate) struct UniverseInfo<'tcx>(UniverseInfoInner<'tcx>); @@ -176,25 +176,24 @@ fn report_error( 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 c7a5d516ad7..60ea0d1edbf 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -11,10 +11,10 @@ use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, Applicability, Diag, MultiSpan}; +use rustc_errors::{Applicability, Diag, MultiSpan, struct_span_code_err}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::intravisit::{walk_block, walk_expr, Map, Visitor}; +use rustc_hir::intravisit::{Map, Visitor, walk_block, walk_expr}; use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource, LangItem, PatField}; use rustc_middle::bug; use rustc_middle::hir::nested_filter::OnlyBodies; @@ -27,17 +27,17 @@ }; use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{ - self, suggest_constraining_type_params, PredicateKind, Ty, TyCtxt, TypeSuperVisitable, - TypeVisitor, Upcast, + self, PredicateKind, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor, Upcast, + suggest_constraining_type_params, }; use rustc_middle::util::CallKind; use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex}; use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::hygiene::DesugaringKind; -use rustc_span::symbol::{kw, sym, Ident}; +use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{BytePos, Span, Symbol}; -use rustc_trait_selection::error_reporting::traits::FindExprBySpan; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; +use rustc_trait_selection::error_reporting::traits::FindExprBySpan; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{Obligation, ObligationCause, ObligationCtxt}; use tracing::{debug, instrument}; @@ -46,9 +46,9 @@ use super::{DescribePlaceOpt, RegionName, RegionNameSource, UseSpans}; use crate::borrow_set::{BorrowData, TwoPhaseActivation}; use crate::diagnostics::conflict_errors::StorageDeadOrDrop::LocalStorageDead; -use crate::diagnostics::{find_all_local_uses, CapturedMessageOpt, Instance}; +use crate::diagnostics::{CapturedMessageOpt, Instance, find_all_local_uses}; use crate::prefixes::IsPrefixOf; -use crate::{borrowck_errors, InitializationRequiringAction, MirBorrowckCtxt, WriteKind}; +use crate::{InitializationRequiringAction, MirBorrowckCtxt, WriteKind, borrowck_errors}; #[derive(Debug)] struct MoveSite { @@ -145,10 +145,10 @@ pub(crate) fn report_use_of_moved_or_uninitialized( 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 @@ -266,10 +266,10 @@ pub(crate) fn report_use_of_moved_or_uninitialized( } } - 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(), @@ -689,17 +689,17 @@ fn report_use_of_uninitialized( } 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/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index d9b5fd8b5c1..7077d78f459 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -17,12 +17,12 @@ }; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::{self, RegionVid, Ty, TyCtxt}; -use rustc_span::symbol::{kw, Symbol}; -use rustc_span::{sym, DesugaringKind, Span}; +use rustc_span::symbol::{Symbol, kw}; +use rustc_span::{DesugaringKind, Span, sym}; use rustc_trait_selection::error_reporting::traits::FindExprBySpan; use tracing::{debug, instrument}; -use super::{find_use, RegionName, UseSpans}; +use super::{RegionName, UseSpans, find_use}; use crate::borrow_set::BorrowData; use crate::nll::ConstraintDescription; use crate::region_infer::{BlameConstraint, Cause, ExtraConstraintInfo}; diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index e52ddfa3eb5..801c7af2de7 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -15,22 +15,22 @@ }; use rustc_middle::ty::print::Print; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; -use rustc_middle::util::{call_kind, CallDesugaringKind}; +use rustc_middle::util::{CallDesugaringKind, call_kind}; use rustc_mir_dataflow::move_paths::{InitLocation, LookupResult}; use rustc_span::def_id::LocalDefId; use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; -use rustc_span::{Span, Symbol, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span, Symbol}; use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{ - type_known_to_meet_bound_modulo_regions, FulfillmentErrorCode, + FulfillmentErrorCode, type_known_to_meet_bound_modulo_regions, }; use tracing::debug; -use super::borrow_set::BorrowData; use super::MirBorrowckCtxt; +use super::borrow_set::BorrowData; use crate::fluent_generated as fluent; use crate::session_diagnostics::{ CaptureArgLabel, CaptureReasonLabel, CaptureReasonNote, CaptureReasonSuggest, CaptureVarCause, @@ -177,10 +177,10 @@ pub(super) fn describe_any_place(&self, place_ref: PlaceRef<'tcx>) -> String { /// 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/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 5a9eba34d07..98417e8c7a3 100644 --- a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs @@ -12,9 +12,9 @@ use rustc_trait_selection::error_reporting::traits::FindExprBySpan; use tracing::debug; +use crate::MirBorrowckCtxt; use crate::diagnostics::{CapturedMessageOpt, DescribePlaceOpt, UseSpans}; use crate::prefixes::PrefixSet; -use crate::MirBorrowckCtxt; #[derive(Debug)] pub(crate) enum IllegalMoveOriginKind<'tcx> { diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 2bbafb0163e..20ecc665b1e 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -14,8 +14,8 @@ PlaceRef, ProjectionElem, }; use rustc_middle::ty::{self, InstanceKind, Ty, TyCtxt, Upcast}; -use rustc_span::symbol::{kw, Symbol}; -use rustc_span::{sym, BytePos, DesugaringKind, Span}; +use rustc_span::symbol::{Symbol, kw}; +use rustc_span::{BytePos, DesugaringKind, Span, sym}; use rustc_target::abi::FieldIdx; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::InferCtxtExt; @@ -24,7 +24,7 @@ use crate::diagnostics::BorrowedContentSource; use crate::util::FindAssignments; -use crate::{session_diagnostics, MirBorrowckCtxt}; +use crate::{MirBorrowckCtxt, session_diagnostics}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum AccessKind { diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 57c3a0843a6..ca0a3c66130 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -3,26 +3,26 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan}; use rustc_hir as hir; -use rustc_hir::def::Res::Def; -use rustc_hir::def_id::DefId; -use rustc_hir::intravisit::Visitor; use rustc_hir::GenericBound::Trait; use rustc_hir::QPath::Resolved; use rustc_hir::WherePredicate::BoundPredicate; +use rustc_hir::def::Res::Def; +use rustc_hir::def_id::DefId; +use rustc_hir::intravisit::Visitor; use rustc_hir::{PolyTraitRef, TyKind, WhereBoundPredicate}; use rustc_infer::infer::{NllRegionVariableOrigin, RelateParamBound}; use rustc_middle::bug; use rustc_middle::hir::place::PlaceBase; use rustc_middle::mir::{ConstraintCategory, ReturnConstraint}; use rustc_middle::ty::{self, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeVisitor}; -use rustc_span::symbol::{kw, Ident}; use rustc_span::Span; +use rustc_span::symbol::{Ident, kw}; +use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::infer::nice_region_error::{ - self, find_anon_type, find_param_with_region, suggest_adding_lifetime_params, - HirTraitObjectVisitor, NiceRegionError, TraitObjectVisitor, + self, HirTraitObjectVisitor, NiceRegionError, TraitObjectVisitor, find_anon_type, + find_param_with_region, suggest_adding_lifetime_params, }; use rustc_trait_selection::error_reporting::infer::region::unexpected_hidden_region_diagnostic; -use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{Obligation, ObligationCtxt}; use tracing::{debug, instrument, trace}; @@ -36,7 +36,7 @@ LifetimeReturnCategoryErr, RequireStaticErr, VarHereDenote, }; use crate::universal_regions::DefiningTy; -use crate::{borrowck_errors, fluent_generated as fluent, MirBorrowckCtxt}; +use crate::{MirBorrowckCtxt, borrowck_errors, fluent_generated as fluent}; impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> { fn description(&self) -> &'static str { @@ -1108,15 +1108,12 @@ fn suggest_deref_closure_return(&self, diag: &mut Diag<'_>) { 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/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 58fcda2571c..2f22e1532c1 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -11,13 +11,13 @@ use rustc_middle::ty::print::RegionHighlightMode; use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, RegionVid, Ty}; use rustc_middle::{bug, span_bug}; -use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use tracing::{debug, instrument}; -use crate::universal_regions::DefiningTy; use crate::MirBorrowckCtxt; +use crate::universal_regions::DefiningTy; /// A name for a particular region used in emitting diagnostics. This name could be a generated /// name like `'1`, a name used by the user like `'a`, or a name like `'static`. diff --git a/compiler/rustc_borrowck/src/diagnostics/var_name.rs b/compiler/rustc_borrowck/src/diagnostics/var_name.rs index 2a4fa1e0019..bda70241267 100644 --- a/compiler/rustc_borrowck/src/diagnostics/var_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/var_name.rs @@ -1,8 +1,8 @@ use rustc_index::IndexSlice; use rustc_middle::mir::{Body, Local}; use rustc_middle::ty::{self, RegionVid, TyCtxt}; -use rustc_span::symbol::Symbol; use rustc_span::Span; +use rustc_span::symbol::Symbol; use tracing::debug; use crate::region_infer::RegionInferenceContext; diff --git a/compiler/rustc_borrowck/src/facts.rs b/compiler/rustc_borrowck/src/facts.rs index 94b50448576..713452796c6 100644 --- a/compiler/rustc_borrowck/src/facts.rs +++ b/compiler/rustc_borrowck/src/facts.rs @@ -10,8 +10,8 @@ use rustc_middle::ty::{RegionVid, TyCtxt}; use rustc_mir_dataflow::move_paths::MovePathIndex; -use crate::location::{LocationIndex, LocationTable}; use crate::BorrowIndex; +use crate::location::{LocationIndex, LocationTable}; #[derive(Copy, Clone, Debug)] pub struct RustcFacts; diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 58e73030749..733fabe557e 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -37,13 +37,13 @@ use rustc_middle::query::Providers; use rustc_middle::ty::{self, ParamEnv, RegionVid, TyCtxt}; use rustc_middle::{bug, span_bug}; +use rustc_mir_dataflow::Analysis; use rustc_mir_dataflow::impls::{ EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces, }; use rustc_mir_dataflow::move_paths::{ InitIndex, InitLocation, LookupResult, MoveData, MoveOutIndex, MovePathIndex, }; -use rustc_mir_dataflow::Analysis; use rustc_session::lint::builtin::UNUSED_MUT; use rustc_span::{Span, Symbol}; use rustc_target::abi::FieldIdx; @@ -86,7 +86,7 @@ use dataflow::{BorrowIndex, BorrowckDomain, BorrowckResults, Borrows}; use nll::PoloniusOutput; use place_ext::PlaceExt; -use places_conflict::{places_conflict, PlaceConflictBias}; +use places_conflict::{PlaceConflictBias, places_conflict}; use region_infer::RegionInferenceContext; use renumber::RegionCtxt; @@ -1612,13 +1612,9 @@ fn check_movable_place(&mut self, location: Location, place: Place<'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/nll.rs b/compiler/rustc_borrowck/src/nll.rs index 8575eb9e9a5..d85af52b01e 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -9,17 +9,17 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_hir::def_id::LocalDefId; use rustc_index::IndexSlice; -use rustc_middle::mir::pretty::{dump_mir_with_options, PrettyPrintMirOptions}; +use rustc_middle::mir::pretty::{PrettyPrintMirOptions, dump_mir_with_options}; use rustc_middle::mir::{ - create_dump_file, dump_enabled, dump_mir, Body, ClosureOutlivesSubject, - ClosureRegionRequirements, PassWhere, Promoted, + Body, ClosureOutlivesSubject, ClosureRegionRequirements, PassWhere, Promoted, create_dump_file, + dump_enabled, dump_mir, }; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, OpaqueHiddenType, TyCtxt}; +use rustc_mir_dataflow::ResultsCursor; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::MoveData; use rustc_mir_dataflow::points::DenseLocationMap; -use rustc_mir_dataflow::ResultsCursor; use rustc_session::config::MirIncludeSpans; use rustc_span::symbol::sym; use tracing::{debug, instrument}; @@ -32,7 +32,7 @@ use crate::region_infer::RegionInferenceContext; use crate::type_check::{self, MirTypeckRegionConstraints, MirTypeckResults}; use crate::universal_regions::UniversalRegions; -use crate::{polonius, renumber, BorrowckInferCtxt}; +use crate::{BorrowckInferCtxt, polonius, renumber}; pub type PoloniusOutput = Output; diff --git a/compiler/rustc_borrowck/src/path_utils.rs b/compiler/rustc_borrowck/src/path_utils.rs index f387d5cfedc..1ba41cd5244 100644 --- a/compiler/rustc_borrowck/src/path_utils.rs +++ b/compiler/rustc_borrowck/src/path_utils.rs @@ -5,7 +5,7 @@ use tracing::debug; use crate::borrow_set::{BorrowData, BorrowSet, TwoPhaseActivation}; -use crate::{places_conflict, AccessDepth, BorrowIndex}; +use crate::{AccessDepth, BorrowIndex, places_conflict}; /// Returns `true` if the borrow represented by `kind` is /// allowed to be split into separate Reservation and diff --git a/compiler/rustc_borrowck/src/region_infer/mod.rs b/compiler/rustc_borrowck/src/region_infer/mod.rs index d6bb006cd7e..c62ea870acf 100644 --- a/compiler/rustc_borrowck/src/region_infer/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/mod.rs @@ -23,6 +23,7 @@ use rustc_span::Span; use tracing::{debug, instrument, trace}; +use crate::BorrowckInferCtxt; use crate::constraints::graph::{self, NormalConstraintGraph, RegionGraph}; use crate::constraints::{ConstraintSccIndex, OutlivesConstraint, OutlivesConstraintSet}; use crate::dataflow::BorrowIndex; @@ -33,10 +34,9 @@ use crate::region_infer::values::{ LivenessValues, PlaceholderIndices, RegionElement, RegionValues, ToElementIndex, }; -use crate::type_check::free_region_relations::UniversalRegionRelations; use crate::type_check::Locations; +use crate::type_check::free_region_relations::UniversalRegionRelations; use crate::universal_regions::UniversalRegions; -use crate::BorrowckInferCtxt; mod dump_mir; mod graphviz; diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index f97f3dfe29f..3cf21d4a36b 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -1,8 +1,8 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_errors::ErrorGuaranteed; +use rustc_hir::OpaqueTyOrigin; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; -use rustc_hir::OpaqueTyOrigin; use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin, TyCtxtInferExt as _}; use rustc_infer::traits::{Obligation, ObligationCause}; use rustc_macros::extension; @@ -165,10 +165,10 @@ pub(crate) fn infer_opaque_types( // 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/region_infer/reverse_sccs.rs b/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs index 3cc5fa4404e..cfd5a92787e 100644 --- a/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs +++ b/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs @@ -5,8 +5,8 @@ use rustc_data_structures::graph::vec_graph::VecGraph; use rustc_middle::ty::RegionVid; -use crate::constraints::ConstraintSccIndex; use crate::RegionInferenceContext; +use crate::constraints::ConstraintSccIndex; pub(crate) struct ReverseSccGraph { graph: VecGraph, diff --git a/compiler/rustc_borrowck/src/region_infer/values.rs b/compiler/rustc_borrowck/src/region_infer/values.rs index 30dc062ae7c..b95fe5b5028 100644 --- a/compiler/rustc_borrowck/src/region_infer/values.rs +++ b/compiler/rustc_borrowck/src/region_infer/values.rs @@ -2,9 +2,9 @@ use std::rc::Rc; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; +use rustc_index::Idx; use rustc_index::bit_set::SparseBitMatrix; use rustc_index::interval::{IntervalSet, SparseIntervalMatrix}; -use rustc_index::Idx; use rustc_middle::mir::{BasicBlock, Location}; use rustc_middle::ty::{self, RegionVid}; use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex}; diff --git a/compiler/rustc_borrowck/src/session_diagnostics.rs b/compiler/rustc_borrowck/src/session_diagnostics.rs index b6c6960d4ca..627444a4ce5 100644 --- a/compiler/rustc_borrowck/src/session_diagnostics.rs +++ b/compiler/rustc_borrowck/src/session_diagnostics.rs @@ -1,5 +1,5 @@ -use rustc_errors::codes::*; use rustc_errors::MultiSpan; +use rustc_errors::codes::*; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::{GenericArg, Ty}; use rustc_span::Span; diff --git a/compiler/rustc_borrowck/src/type_check/canonical.rs b/compiler/rustc_borrowck/src/type_check/canonical.rs index 4b15ce8873d..0c6f8cd7b5b 100644 --- a/compiler/rustc_borrowck/src/type_check/canonical.rs +++ b/compiler/rustc_borrowck/src/type_check/canonical.rs @@ -5,11 +5,11 @@ use rustc_middle::bug; use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, Upcast}; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; +use rustc_trait_selection::traits::ObligationCause; use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp; use rustc_trait_selection::traits::query::type_op::{self, TypeOpOutput}; -use rustc_trait_selection::traits::ObligationCause; use tracing::{debug, instrument}; use super::{Locations, NormalizeLocation, TypeChecker}; diff --git a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs index 0f1d79a2c35..fc1600ea4a6 100644 --- a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs +++ b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs @@ -6,13 +6,13 @@ use rustc_infer::infer::{self, InferCtxt, SubregionOrigin}; use rustc_middle::bug; use rustc_middle::mir::{ClosureOutlivesSubject, ClosureRegionRequirements, ConstraintCategory}; -use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{self, GenericArgKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use rustc_span::Span; +use rustc_trait_selection::traits::ScrubbedTraitError; use rustc_trait_selection::traits::query::type_op::custom::CustomTypeOp; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; -use rustc_trait_selection::traits::ScrubbedTraitError; use tracing::{debug, instrument}; use crate::constraints::OutlivesConstraint; diff --git a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs index c711190cb97..6977fed59ed 100644 --- a/compiler/rustc_borrowck/src/type_check/free_region_relations.rs +++ b/compiler/rustc_borrowck/src/type_check/free_region_relations.rs @@ -6,10 +6,10 @@ use rustc_infer::infer::canonical::QueryRegionConstraints; use rustc_infer::infer::outlives::env::RegionBoundPairs; use rustc_infer::infer::region_constraints::GenericKind; -use rustc_infer::infer::{outlives, InferCtxt}; +use rustc_infer::infer::{InferCtxt, outlives}; use rustc_middle::mir::ConstraintCategory; -use rustc_middle::traits::query::OutlivesBound; use rustc_middle::traits::ObligationCause; +use rustc_middle::traits::query::OutlivesBound; use rustc_middle::ty::{self, RegionVid, Ty, TypeVisitableExt}; use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; @@ -18,7 +18,7 @@ use tracing::{debug, instrument}; use type_op::TypeOpOutput; -use crate::type_check::{constraint_conversion, Locations, MirTypeckRegionConstraints}; +use crate::type_check::{Locations, MirTypeckRegionConstraints, constraint_conversion}; use crate::universal_regions::UniversalRegions; #[derive(Debug)] diff --git a/compiler/rustc_borrowck/src/type_check/input_output.rs b/compiler/rustc_borrowck/src/type_check/input_output.rs index 56f8464628c..141f251244b 100644 --- a/compiler/rustc_borrowck/src/type_check/input_output.rs +++ b/compiler/rustc_borrowck/src/type_check/input_output.rs @@ -77,20 +77,17 @@ pub(super) fn check_signature_annotation(&mut self, body: &Body<'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/liveness/mod.rs b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs index a73467824de..d4900d21f8f 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs @@ -7,10 +7,10 @@ use rustc_middle::span_bug; use rustc_middle::ty::visit::TypeVisitable; use rustc_middle::ty::{GenericArgsRef, Region, RegionVid, Ty, TyCtxt}; +use rustc_mir_dataflow::ResultsCursor; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::MoveData; use rustc_mir_dataflow::points::DenseLocationMap; -use rustc_mir_dataflow::ResultsCursor; use tracing::debug; use super::TypeChecker; diff --git a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs index 1ac27573453..8cbe3ac6701 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/trace.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/trace.rs @@ -8,10 +8,10 @@ use rustc_middle::mir::{BasicBlock, Body, ConstraintCategory, Local, Location}; use rustc_middle::traits::query::DropckOutlivesResult; use rustc_middle::ty::{Ty, TyCtxt, TypeVisitable, TypeVisitableExt}; +use rustc_mir_dataflow::ResultsCursor; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::{HasMoveData, MoveData, MovePathIndex}; use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex}; -use rustc_mir_dataflow::ResultsCursor; use rustc_span::DUMMY_SP; use rustc_trait_selection::traits::query::type_op::outlives::DropckOutlives; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 3e5a6ad85fa..4056b423548 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -31,20 +31,20 @@ UserType, UserTypeAnnotationIndex, }; use rustc_middle::{bug, span_bug}; +use rustc_mir_dataflow::ResultsCursor; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::MoveData; use rustc_mir_dataflow::points::DenseLocationMap; -use rustc_mir_dataflow::ResultsCursor; use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; -use rustc_span::{Span, DUMMY_SP}; -use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; +use rustc_span::{DUMMY_SP, Span}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx}; +use rustc_trait_selection::traits::PredicateObligation; use rustc_trait_selection::traits::query::type_op::custom::{ - scrape_region_constraints, CustomTypeOp, + CustomTypeOp, scrape_region_constraints, }; use rustc_trait_selection::traits::query::type_op::{TypeOp, TypeOpOutput}; -use rustc_trait_selection::traits::PredicateObligation; use tracing::{debug, instrument, trace}; use crate::borrow_set::BorrowSet; @@ -53,13 +53,13 @@ use crate::facts::AllFacts; use crate::location::LocationTable; use crate::member_constraints::MemberConstraintSet; -use crate::region_infer::values::{LivenessValues, PlaceholderIndex, PlaceholderIndices}; use crate::region_infer::TypeTest; +use crate::region_infer::values::{LivenessValues, PlaceholderIndex, PlaceholderIndices}; use crate::renumber::RegionCtxt; use crate::session_diagnostics::{MoveUnsized, SimdIntrinsicArgConst}; use crate::type_check::free_region_relations::{CreateResult, UniversalRegionRelations}; use crate::universal_regions::{DefiningTy, UniversalRegions}; -use crate::{path_utils, BorrowckInferCtxt}; +use crate::{BorrowckInferCtxt, path_utils}; macro_rules! span_mirbug { ($context:expr, $elem:expr, $($message:tt)*) => ({ @@ -1944,11 +1944,10 @@ fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: L } &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, @@ -1961,11 +1960,10 @@ fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: L 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/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index 71892a67ffc..bf079e813f1 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -4,12 +4,12 @@ PredicateEmittingRelation, Relate, RelateResult, StructurallyRelateAliases, TypeRelation, }; use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin}; -use rustc_infer::traits::solve::Goal; use rustc_infer::traits::Obligation; +use rustc_infer::traits::solve::Goal; use rustc_middle::mir::ConstraintCategory; use rustc_middle::span_bug; -use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; +use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::fold::FnMutDelegate; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::symbol::sym; diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index c3edbcb50cc..fa44ffcd17d 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -20,9 +20,9 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_errors::Diag; +use rustc_hir::BodyOwnerKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; -use rustc_hir::BodyOwnerKind; use rustc_index::IndexVec; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_macros::extension; @@ -37,8 +37,8 @@ use rustc_span::{ErrorGuaranteed, Symbol}; use tracing::{debug, instrument}; -use crate::renumber::RegionCtxt; use crate::BorrowckInferCtxt; +use crate::renumber::RegionCtxt; #[derive(Debug)] pub(crate) struct UniversalRegions<'tcx> { @@ -629,10 +629,10 @@ fn defining_ty(&self) -> DefiningTy<'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 1df2812e0c8..0caad997b9d 100644 --- a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs +++ b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs @@ -3,9 +3,9 @@ self as ast, Fn, FnHeader, FnSig, Generics, ItemKind, Safety, Stmt, StmtKind, TyKind, }; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, kw, sym}; +use thin_vec::{ThinVec, thin_vec}; use crate::errors; use crate::util::check_builtin_macro_attribute; @@ -68,11 +68,10 @@ 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/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index 0e1ec3b3cad..94e40da8c92 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -1,16 +1,16 @@ use ast::token::IdentIsRaw; use lint::BuiltinLintDiag; +use rustc_ast::AsmMacro; use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter}; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::AsmMacro; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_errors::PResult; use rustc_expand::base::*; use rustc_index::bit_set::GrowableBitSet; use rustc_parse::parser::Parser; use rustc_session::lint; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use rustc_span::{ErrorGuaranteed, InnerSpan, Span}; use rustc_target::asm::InlineAsmArch; use smallvec::smallvec; diff --git a/compiler/rustc_builtin_macros/src/assert.rs b/compiler/rustc_builtin_macros/src/assert.rs index 99f433c0851..71449350985 100644 --- a/compiler/rustc_builtin_macros/src/assert.rs +++ b/compiler/rustc_builtin_macros/src/assert.rs @@ -3,13 +3,13 @@ use rustc_ast::ptr::P; use rustc_ast::token::Delimiter; use rustc_ast::tokenstream::{DelimSpan, TokenStream}; -use rustc_ast::{token, DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp}; +use rustc_ast::{DelimArgs, Expr, ExprKind, MacCall, Path, PathSegment, UnOp, token}; use rustc_ast_pretty::pprust; use rustc_errors::PResult; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_parse::parser::Parser; -use rustc_span::symbol::{sym, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, Symbol, sym}; +use rustc_span::{DUMMY_SP, Span}; use thin_vec::thin_vec; use crate::edition_panic::use_panic_2021; diff --git a/compiler/rustc_builtin_macros/src/assert/context.rs b/compiler/rustc_builtin_macros/src/assert/context.rs index 2cd5b9d68a0..70fa4d00c0f 100644 --- a/compiler/rustc_builtin_macros/src/assert/context.rs +++ b/compiler/rustc_builtin_macros/src/assert/context.rs @@ -2,15 +2,15 @@ use rustc_ast::token::{self, Delimiter, IdentIsRaw}; use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree}; use rustc_ast::{ - BinOpKind, BorrowKind, DelimArgs, Expr, ExprKind, ItemKind, MacCall, MethodCall, Mutability, - Path, PathSegment, Stmt, StructRest, UnOp, UseTree, UseTreeKind, DUMMY_NODE_ID, + BinOpKind, BorrowKind, DUMMY_NODE_ID, DelimArgs, Expr, ExprKind, ItemKind, MacCall, MethodCall, + Mutability, Path, PathSegment, Stmt, StructRest, UnOp, UseTree, UseTreeKind, }; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashSet; use rustc_expand::base::ExtCtxt; -use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, Symbol, sym}; +use thin_vec::{ThinVec, thin_vec}; pub(super) struct Context<'cx, 'a> { // An optimization. diff --git a/compiler/rustc_builtin_macros/src/cfg_accessible.rs b/compiler/rustc_builtin_macros/src/cfg_accessible.rs index 3d3bd3aea05..23578781a83 100644 --- a/compiler/rustc_builtin_macros/src/cfg_accessible.rs +++ b/compiler/rustc_builtin_macros/src/cfg_accessible.rs @@ -4,8 +4,8 @@ use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier}; use rustc_feature::AttributeTemplate; use rustc_parse::validate_attr; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use crate::errors; diff --git a/compiler/rustc_builtin_macros/src/cfg_eval.rs b/compiler/rustc_builtin_macros/src/cfg_eval.rs index 4b05c144d37..b686a8cf935 100644 --- a/compiler/rustc_builtin_macros/src/cfg_eval.rs +++ b/compiler/rustc_builtin_macros/src/cfg_eval.rs @@ -4,7 +4,7 @@ use rustc_ast::mut_visit::MutVisitor; use rustc_ast::ptr::P; use rustc_ast::visit::{AssocCtxt, Visitor}; -use rustc_ast::{mut_visit, visit, Attribute, HasAttrs, HasTokens, NodeId}; +use rustc_ast::{Attribute, HasAttrs, HasTokens, NodeId, mut_visit, visit}; use rustc_errors::PResult; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_expand::config::StripUnconfigured; @@ -12,8 +12,8 @@ use rustc_feature::Features; use rustc_parse::parser::{ForceCollect, Parser}; use rustc_session::Session; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use smallvec::SmallVec; use tracing::instrument; diff --git a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs index 66fa74da60d..6afd8c4b43b 100644 --- a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs +++ b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs @@ -1,7 +1,7 @@ //! Attributes injected into the crate root from command line using `-Z crate-attr`. use rustc_ast::attr::mk_attr; -use rustc_ast::{self as ast, token, AttrItem, AttrStyle}; +use rustc_ast::{self as ast, AttrItem, AttrStyle, token}; use rustc_parse::parser::ForceCollect; use rustc_parse::{new_parser_from_source_str, unwrap_or_emit_fatal}; use rustc_session::parse::ParseSess; diff --git a/compiler/rustc_builtin_macros/src/concat_bytes.rs b/compiler/rustc_builtin_macros/src/concat_bytes.rs index 196bf906dc0..456f2b9ab31 100644 --- a/compiler/rustc_builtin_macros/src/concat_bytes.rs +++ b/compiler/rustc_builtin_macros/src/concat_bytes.rs @@ -1,6 +1,6 @@ use rustc_ast::ptr::P; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{token, ExprKind, LitIntType, LitKind, UintTy}; +use rustc_ast::{ExprKind, LitIntType, LitKind, UintTy, token}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; use rustc_session::errors::report_lit_error; use rustc_span::{ErrorGuaranteed, Span}; diff --git a/compiler/rustc_builtin_macros/src/concat_idents.rs b/compiler/rustc_builtin_macros/src/concat_idents.rs index 13729a9d250..b459cc3007d 100644 --- a/compiler/rustc_builtin_macros/src/concat_idents.rs +++ b/compiler/rustc_builtin_macros/src/concat_idents.rs @@ -1,10 +1,10 @@ use rustc_ast::ptr::P; use rustc_ast::token::{self, Token}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; -use rustc_ast::{AttrVec, Expr, ExprKind, Path, Ty, TyKind, DUMMY_NODE_ID}; +use rustc_ast::{AttrVec, DUMMY_NODE_ID, Expr, ExprKind, Path, Ty, TyKind}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacResult, MacroExpanderResult}; -use rustc_span::symbol::{Ident, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Ident, Symbol}; use crate::errors; diff --git a/compiler/rustc_builtin_macros/src/derive.rs b/compiler/rustc_builtin_macros/src/derive.rs index e8704bc2f63..4be2d209ae7 100644 --- a/compiler/rustc_builtin_macros/src/derive.rs +++ b/compiler/rustc_builtin_macros/src/derive.rs @@ -6,7 +6,7 @@ use rustc_feature::AttributeTemplate; use rustc_parse::validate_attr; use rustc_session::Session; -use rustc_span::symbol::{sym, Ident}; +use rustc_span::symbol::{Ident, sym}; use rustc_span::{ErrorGuaranteed, Span}; use crate::cfg_eval::cfg_eval; diff --git a/compiler/rustc_builtin_macros/src/deriving/clone.rs b/compiler/rustc_builtin_macros/src/deriving/clone.rs index 22beca4ea9a..dde696fca61 100644 --- a/compiler/rustc_builtin_macros/src/deriving/clone.rs +++ b/compiler/rustc_builtin_macros/src/deriving/clone.rs @@ -1,9 +1,9 @@ use rustc_ast::{self as ast, Generics, ItemKind, MetaItem, VariantData}; use rustc_data_structures::fx::FxHashSet; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, kw, sym}; +use thin_vec::{ThinVec, thin_vec}; use crate::deriving::generic::ty::*; use crate::deriving::generic::*; @@ -115,13 +115,10 @@ fn cs_clone_simple( // type parameters. } else if !field.ty.kind.is_anon_adt() { // 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, + ]); } } }; @@ -130,13 +127,10 @@ 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 a5e12174796..bd6f4eb8d99 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/eq.rs @@ -1,9 +1,9 @@ use rustc_ast::{self as ast, MetaItem}; use rustc_data_structures::fx::FxHashSet; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::sym; use rustc_span::Span; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::sym; +use thin_vec::{ThinVec, thin_vec}; use crate::deriving::generic::ty::*; use crate::deriving::generic::*; @@ -66,13 +66,10 @@ 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/cmp/ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs index 705c41175e7..433cbfaa6cb 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/ord.rs @@ -1,7 +1,7 @@ use rustc_ast::MetaItem; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use rustc_span::symbol::{Ident, sym}; use thin_vec::thin_vec; use crate::deriving::generic::ty::*; diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs index f6299589e0f..ae1e5f4a219 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_eq.rs @@ -1,8 +1,8 @@ use rustc_ast::ptr::P; use rustc_ast::{BinOpKind, BorrowKind, Expr, ExprKind, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use thin_vec::thin_vec; use crate::deriving::generic::ty::*; diff --git a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs index a51f98f5396..99a98325053 100644 --- a/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs +++ b/compiler/rustc_builtin_macros/src/deriving/cmp/partial_ord.rs @@ -1,7 +1,7 @@ use rustc_ast::{ExprKind, ItemKind, MetaItem, PatKind}; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use rustc_span::symbol::{Ident, sym}; use thin_vec::thin_vec; use crate::deriving::generic::ty::*; diff --git a/compiler/rustc_builtin_macros/src/deriving/debug.rs b/compiler/rustc_builtin_macros/src/deriving/debug.rs index 57d9c076150..06a598cf3b0 100644 --- a/compiler/rustc_builtin_macros/src/deriving/debug.rs +++ b/compiler/rustc_builtin_macros/src/deriving/debug.rs @@ -1,9 +1,9 @@ use rustc_ast::{self as ast, EnumDef, MetaItem}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_session::config::FmtDebug; -use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, Symbol, sym}; +use thin_vec::{ThinVec, thin_vec}; use crate::deriving::generic::ty::*; use crate::deriving::generic::*; diff --git a/compiler/rustc_builtin_macros/src/deriving/decodable.rs b/compiler/rustc_builtin_macros/src/deriving/decodable.rs index 89300a36d1b..686424770fc 100644 --- a/compiler/rustc_builtin_macros/src/deriving/decodable.rs +++ b/compiler/rustc_builtin_macros/src/deriving/decodable.rs @@ -3,9 +3,9 @@ use rustc_ast::ptr::P; use rustc_ast::{self as ast, Expr, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, Symbol, sym}; +use thin_vec::{ThinVec, thin_vec}; use crate::deriving::generic::ty::*; use crate::deriving::generic::*; @@ -32,10 +32,11 @@ pub(crate) fn expand_deriving_rustc_decodable( methods: vec![MethodDef { name: sym::decode, generics: Bounds { - bounds: vec![( - typaram, - vec![Path::new_(vec![krate, sym::Decoder], vec![], PathKind::Global)], - )], + bounds: vec![(typaram, vec![Path::new_( + vec![krate, sym::Decoder], + vec![], + PathKind::Global, + )])], }, explicit_self: false, nonself_args: vec![( @@ -94,32 +95,24 @@ fn decodable_substructure( decode_static_fields(cx, trait_span, path, summary, |cx, span, name, field| { cx.expr_try( span, - cx.expr_call_global( - span, - fn_read_struct_field_path.clone(), - thin_vec![ - blkdecoder.clone(), - cx.expr_str(span, name), - cx.expr_usize(span, field), - exprdecode.clone(), - ], - ), + cx.expr_call_global(span, fn_read_struct_field_path.clone(), thin_vec![ + blkdecoder.clone(), + cx.expr_str(span, name), + cx.expr_usize(span, field), + exprdecode.clone(), + ]), ) }); let result = cx.expr_ok(trait_span, result); let fn_read_struct_path: Vec<_> = cx.def_site_path(&[sym::rustc_serialize, sym::Decoder, sym::read_struct]); - cx.expr_call_global( - trait_span, - fn_read_struct_path, - thin_vec![ - decoder, - cx.expr_str(trait_span, substr.type_ident.name), - cx.expr_usize(trait_span, nfields), - cx.lambda1(trait_span, result, blkarg), - ], - ) + cx.expr_call_global(trait_span, fn_read_struct_path, thin_vec![ + decoder, + cx.expr_str(trait_span, substr.type_ident.name), + cx.expr_usize(trait_span, nfields), + cx.lambda1(trait_span, result, blkarg), + ]) } StaticEnum(_, fields) => { let variant = Ident::new(sym::i, trait_span); @@ -160,23 +153,19 @@ fn decodable_substructure( let variant_array_ref = cx.expr_array_ref(trait_span, variants); let fn_read_enum_variant_path: Vec<_> = cx.def_site_path(&[sym::rustc_serialize, sym::Decoder, sym::read_enum_variant]); - let result = cx.expr_call_global( - trait_span, - fn_read_enum_variant_path, - thin_vec![blkdecoder, variant_array_ref, lambda], - ); + let result = cx.expr_call_global(trait_span, fn_read_enum_variant_path, thin_vec![ + blkdecoder, + variant_array_ref, + lambda + ]); let fn_read_enum_path: Vec<_> = cx.def_site_path(&[sym::rustc_serialize, sym::Decoder, sym::read_enum]); - cx.expr_call_global( - trait_span, - fn_read_enum_path, - thin_vec![ - decoder, - cx.expr_str(trait_span, substr.type_ident.name), - cx.lambda1(trait_span, result, blkarg), - ], - ) + cx.expr_call_global(trait_span, fn_read_enum_path, thin_vec![ + decoder, + cx.expr_str(trait_span, substr.type_ident.name), + cx.lambda1(trait_span, result, blkarg), + ]) } _ => cx.dcx().bug("expected StaticEnum or StaticStruct in derive(Decodable)"), }; diff --git a/compiler/rustc_builtin_macros/src/deriving/default.rs b/compiler/rustc_builtin_macros/src/deriving/default.rs index afc55ddd230..652e6f7740f 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -2,12 +2,12 @@ use rustc_ast as ast; use rustc_ast::visit::visit_opt; -use rustc_ast::{attr, EnumDef, VariantData}; +use rustc_ast::{EnumDef, VariantData, attr}; use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt}; -use rustc_span::symbol::{kw, sym, Ident}; +use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{ErrorGuaranteed, Span}; use smallvec::SmallVec; -use thin_vec::{thin_vec, ThinVec}; +use thin_vec::{ThinVec, thin_vec}; use crate::deriving::generic::ty::*; use crate::deriving::generic::*; @@ -93,10 +93,10 @@ fn default_enum_substructure( } { Ok(default_variant) => { // We now know there is exactly one unit variant with exactly one `#[default]` attribute. - cx.expr_path(cx.path( - default_variant.span, - vec![Ident::new(kw::SelfUpper, default_variant.span), default_variant.ident], - )) + cx.expr_path(cx.path(default_variant.span, vec![ + Ident::new(kw::SelfUpper, default_variant.span), + default_variant.ident, + ])) } Err(guar) => DummyResult::raw_expr(trait_span, Some(guar)), }; diff --git a/compiler/rustc_builtin_macros/src/deriving/encodable.rs b/compiler/rustc_builtin_macros/src/deriving/encodable.rs index 9c26d05f811..5c7583f2a77 100644 --- a/compiler/rustc_builtin_macros/src/deriving/encodable.rs +++ b/compiler/rustc_builtin_macros/src/deriving/encodable.rs @@ -87,9 +87,9 @@ use rustc_ast::{AttrVec, ExprKind, MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, Symbol, sym}; +use thin_vec::{ThinVec, thin_vec}; use crate::deriving::generic::ty::*; use crate::deriving::generic::*; @@ -116,10 +116,11 @@ pub(crate) fn expand_deriving_rustc_encodable( methods: vec![MethodDef { name: sym::encode, generics: Bounds { - bounds: vec![( - typaram, - vec![Path::new_(vec![krate, sym::Encoder], vec![], PathKind::Global)], - )], + bounds: vec![(typaram, vec![Path::new_( + vec![krate, sym::Encoder], + vec![], + PathKind::Global, + )])], }, explicit_self: true, nonself_args: vec![( @@ -157,14 +158,11 @@ fn encodable_substructure( // throw an underscore in front to suppress unused variable warnings let blkarg = Ident::new(sym::_e, trait_span); let blkencoder = cx.expr_ident(trait_span, blkarg); - let fn_path = cx.expr_path(cx.path_global( - trait_span, - vec![ - Ident::new(krate, trait_span), - Ident::new(sym::Encodable, trait_span), - Ident::new(sym::encode, trait_span), - ], - )); + let fn_path = cx.expr_path(cx.path_global(trait_span, vec![ + Ident::new(krate, trait_span), + Ident::new(sym::Encodable, trait_span), + Ident::new(sym::encode, trait_span), + ])); match substr.fields { Struct(_, fields) => { @@ -180,16 +178,12 @@ fn encodable_substructure( let enc = cx.expr_call(span, fn_path.clone(), thin_vec![self_ref, blkencoder.clone()]); let lambda = cx.lambda1(span, enc, blkarg); - let call = cx.expr_call_global( - span, - fn_emit_struct_field_path.clone(), - thin_vec![ - blkencoder.clone(), - cx.expr_str(span, name), - cx.expr_usize(span, i), - lambda, - ], - ); + let call = cx.expr_call_global(span, fn_emit_struct_field_path.clone(), thin_vec![ + blkencoder.clone(), + cx.expr_str(span, name), + cx.expr_usize(span, i), + lambda, + ]); // last call doesn't need a try! let last = fields.len() - 1; @@ -214,16 +208,12 @@ fn encodable_substructure( let fn_emit_struct_path = cx.def_site_path(&[sym::rustc_serialize, sym::Encoder, sym::emit_struct]); - let expr = cx.expr_call_global( - trait_span, - fn_emit_struct_path, - thin_vec![ - encoder, - cx.expr_str(trait_span, substr.type_ident.name), - cx.expr_usize(trait_span, fields.len()), - blk, - ], - ); + let expr = cx.expr_call_global(trait_span, fn_emit_struct_path, thin_vec![ + encoder, + cx.expr_str(trait_span, substr.type_ident.name), + cx.expr_usize(trait_span, fields.len()), + blk, + ]); BlockOrExpr::new_expr(expr) } @@ -243,11 +233,8 @@ fn encodable_substructure( let last = fields.len() - 1; for (i, &FieldInfo { ref self_expr, span, .. }) in fields.iter().enumerate() { let self_ref = cx.expr_addr_of(span, self_expr.clone()); - let enc = cx.expr_call( - span, - fn_path.clone(), - thin_vec![self_ref, blkencoder.clone()], - ); + let enc = cx + .expr_call(span, fn_path.clone(), thin_vec![self_ref, blkencoder.clone()]); let lambda = cx.lambda1(span, enc, blkarg); let call = cx.expr_call_global( @@ -274,26 +261,22 @@ fn encodable_substructure( let fn_emit_enum_variant_path: Vec<_> = cx.def_site_path(&[sym::rustc_serialize, sym::Encoder, sym::emit_enum_variant]); - let call = cx.expr_call_global( - trait_span, - fn_emit_enum_variant_path, - thin_vec![ - blkencoder, - name, - cx.expr_usize(trait_span, *idx), - cx.expr_usize(trait_span, fields.len()), - blk, - ], - ); + let call = cx.expr_call_global(trait_span, fn_emit_enum_variant_path, thin_vec![ + blkencoder, + name, + cx.expr_usize(trait_span, *idx), + cx.expr_usize(trait_span, fields.len()), + blk, + ]); let blk = cx.lambda1(trait_span, call, blkarg); let fn_emit_enum_path: Vec<_> = cx.def_site_path(&[sym::rustc_serialize, sym::Encoder, sym::emit_enum]); - let expr = cx.expr_call_global( - trait_span, - fn_emit_enum_path, - thin_vec![encoder, cx.expr_str(trait_span, substr.type_ident.name), blk], - ); + let expr = cx.expr_call_global(trait_span, fn_emit_enum_path, thin_vec![ + encoder, + cx.expr_str(trait_span, substr.type_ident.name), + blk + ]); BlockOrExpr::new_mixed(thin_vec![me], Some(expr)) } diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index 289e92a69b2..82baaca9a46 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -178,6 +178,8 @@ use std::ops::Not; use std::{iter, vec}; +pub(crate) use StaticFields::*; +pub(crate) use SubstructureFields::*; use rustc_ast::ptr::P; use rustc_ast::{ self as ast, BindingMode, ByRef, EnumDef, Expr, GenericArg, GenericParamKind, Generics, @@ -185,12 +187,10 @@ }; use rustc_attr as attr; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, Span}; +use thin_vec::{ThinVec, thin_vec}; use ty::{Bounds, Path, Ref, Self_, Ty}; -pub(crate) use StaticFields::*; -pub(crate) use SubstructureFields::*; use crate::{deriving, errors}; @@ -1228,12 +1228,10 @@ fn expand_enum_method_body<'b>( 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/deriving/generic/ty.rs b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs index 42855e255a8..b118cbfbd91 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs @@ -1,14 +1,14 @@ //! A mini version of ast::Ty, which is easier to use, and features an explicit `Self` type to use //! when specifying impls to be derived. +pub(crate) use Ty::*; use rustc_ast::ptr::P; use rustc_ast::{self as ast, Expr, GenericArg, GenericParamKind, Generics, SelfKind}; use rustc_expand::base::ExtCtxt; use rustc_span::source_map::respan; -use rustc_span::symbol::{kw, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, Symbol, kw}; +use rustc_span::{DUMMY_SP, Span}; use thin_vec::ThinVec; -pub(crate) use Ty::*; /// A path, e.g., `::std::option::Option::` (global). Has support /// for type parameters. diff --git a/compiler/rustc_builtin_macros/src/deriving/hash.rs b/compiler/rustc_builtin_macros/src/deriving/hash.rs index 4fa6686b7b3..2d1f5b70f77 100644 --- a/compiler/rustc_builtin_macros/src/deriving/hash.rs +++ b/compiler/rustc_builtin_macros/src/deriving/hash.rs @@ -1,7 +1,7 @@ use rustc_ast::{MetaItem, Mutability}; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use thin_vec::thin_vec; use crate::deriving::generic::ty::*; diff --git a/compiler/rustc_builtin_macros/src/deriving/mod.rs b/compiler/rustc_builtin_macros/src/deriving/mod.rs index 32936ac183d..d5ee5e430d5 100644 --- a/compiler/rustc_builtin_macros/src/deriving/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/mod.rs @@ -4,9 +4,9 @@ use rustc_ast::ptr::P; use rustc_ast::{GenericArg, MetaItem}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, MultiItemModifier}; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Symbol, sym}; +use thin_vec::{ThinVec, thin_vec}; macro path_local($x:ident) { generic::ty::Path::new_local(sym::$x) diff --git a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs index bc41d33a609..12749e87dcb 100644 --- a/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs +++ b/compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs @@ -1,5 +1,5 @@ -use ast::ptr::P; use ast::HasAttrs; +use ast::ptr::P; use rustc_ast::mut_visit::MutVisitor; use rustc_ast::visit::BoundKind; use rustc_ast::{ @@ -9,9 +9,9 @@ use rustc_attr as attr; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::{sym, Ident}; +use rustc_span::symbol::{Ident, sym}; use rustc_span::{Span, Symbol}; -use thin_vec::{thin_vec, ThinVec}; +use thin_vec::{ThinVec, thin_vec}; macro_rules! path { ($span:expr, $($part:ident)::*) => { vec![$(Ident::new(sym::$part, $span),)*] } diff --git a/compiler/rustc_builtin_macros/src/edition_panic.rs b/compiler/rustc_builtin_macros/src/edition_panic.rs index cc385bade47..c4164a7db9a 100644 --- a/compiler/rustc_builtin_macros/src/edition_panic.rs +++ b/compiler/rustc_builtin_macros/src/edition_panic.rs @@ -3,9 +3,9 @@ use rustc_ast::tokenstream::{DelimSpan, TokenStream}; use rustc_ast::*; use rustc_expand::base::*; +use rustc_span::Span; use rustc_span::edition::Edition; use rustc_span::symbol::sym; -use rustc_span::Span; /// This expands to either /// - `$crate::panic::panic_2015!(...)` or diff --git a/compiler/rustc_builtin_macros/src/env.rs b/compiler/rustc_builtin_macros/src/env.rs index 1a4fc65f0a8..25583cda5a2 100644 --- a/compiler/rustc_builtin_macros/src/env.rs +++ b/compiler/rustc_builtin_macros/src/env.rs @@ -10,8 +10,8 @@ use rustc_ast::tokenstream::TokenStream; use rustc_ast::{AstDeref, ExprKind, GenericArg, Mutability}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacEager, MacroExpanderResult}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use thin_vec::thin_vec; use crate::errors; @@ -58,11 +58,11 @@ pub(crate) fn expand_option_env<'cx>( ))], )) } - Some(value) => cx.expr_call_global( - sp, - cx.std_path(&[sym::option, sym::Option, sym::Some]), - thin_vec![cx.expr_str(sp, value)], - ), + Some(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.rs b/compiler/rustc_builtin_macros/src/format.rs index f99530cad18..9501e93bad5 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -2,9 +2,10 @@ use rustc_ast::ptr::P; use rustc_ast::tokenstream::TokenStream; use rustc_ast::{ - token, Expr, ExprKind, FormatAlignment, FormatArgPosition, FormatArgPositionKind, FormatArgs, + Expr, ExprKind, FormatAlignment, FormatArgPosition, FormatArgPositionKind, FormatArgs, FormatArgsPiece, FormatArgument, FormatArgumentKind, FormatArguments, FormatCount, FormatDebugHex, FormatOptions, FormatPlaceholder, FormatSign, FormatTrait, Recovered, StmtKind, + token, }; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{Applicability, Diag, MultiSpan, PResult, SingleLabelManySpans}; diff --git a/compiler/rustc_builtin_macros/src/format_foreign.rs b/compiler/rustc_builtin_macros/src/format_foreign.rs index 866ec72f116..71320e6d5ad 100644 --- a/compiler/rustc_builtin_macros/src/format_foreign.rs +++ b/compiler/rustc_builtin_macros/src/format_foreign.rs @@ -183,14 +183,10 @@ pub(crate) fn translate(&self) -> Result> { 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 df773910dbc..8fe06df48e5 100644 --- a/compiler/rustc_builtin_macros/src/format_foreign/printf/tests.rs +++ b/compiler/rustc_builtin_macros/src/format_foreign/printf/tests.rs @@ -1,4 +1,4 @@ -use super::{iter_subs, parse_next_substitution as pns, Format as F, Num as N, Substitution as S}; +use super::{Format as F, Num as N, Substitution as S, iter_subs, parse_next_substitution as pns}; macro_rules! assert_eq_pnsat { ($lhs:expr, $rhs:expr) => { @@ -99,10 +99,12 @@ macro_rules! assert_pns_eq_sub { 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 93a7afcd6e8..dd2ee2b6ca9 100644 --- a/compiler/rustc_builtin_macros/src/format_foreign/shell/tests.rs +++ b/compiler/rustc_builtin_macros/src/format_foreign/shell/tests.rs @@ -1,4 +1,4 @@ -use super::{parse_next_substitution as pns, Substitution as S}; +use super::{Substitution as S, parse_next_substitution as pns}; macro_rules! assert_eq_pnsat { ($lhs:expr, $rhs:expr) => { @@ -38,10 +38,11 @@ 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/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs index 66df393b501..b4b18409a18 100644 --- a/compiler/rustc_builtin_macros/src/global_allocator.rs +++ b/compiler/rustc_builtin_macros/src/global_allocator.rs @@ -1,5 +1,5 @@ use rustc_ast::expand::allocator::{ - global_fn_name, AllocatorMethod, AllocatorMethodInput, AllocatorTy, ALLOCATOR_METHODS, + ALLOCATOR_METHODS, AllocatorMethod, AllocatorMethodInput, AllocatorTy, global_fn_name, }; use rustc_ast::ptr::P; use rustc_ast::{ @@ -7,9 +7,9 @@ Stmt, StmtKind, Ty, TyKind, }; use rustc_expand::base::{Annotatable, ExtCtxt}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use thin_vec::{ThinVec, thin_vec}; use crate::errors; use crate::util::check_builtin_macro_attribute; diff --git a/compiler/rustc_builtin_macros/src/pattern_type.rs b/compiler/rustc_builtin_macros/src/pattern_type.rs index 869d203f68e..90b5f097b32 100644 --- a/compiler/rustc_builtin_macros/src/pattern_type.rs +++ b/compiler/rustc_builtin_macros/src/pattern_type.rs @@ -1,9 +1,9 @@ use rustc_ast::ptr::P; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{ast, Pat, Ty}; +use rustc_ast::{Pat, Ty, ast}; use rustc_errors::PResult; use rustc_expand::base::{self, DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; -use rustc_span::{sym, Span}; +use rustc_span::{Span, sym}; pub(crate) fn expand<'cx>( cx: &'cx mut ExtCtxt<'_>, diff --git a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs index 6b2b2b90457..d6603af101a 100644 --- a/compiler/rustc_builtin_macros/src/proc_macro_harness.rs +++ b/compiler/rustc_builtin_macros/src/proc_macro_harness.rs @@ -2,19 +2,19 @@ use rustc_ast::ptr::P; use rustc_ast::visit::{self, Visitor}; -use rustc_ast::{self as ast, attr, NodeId}; +use rustc_ast::{self as ast, NodeId, attr}; use rustc_ast_pretty::pprust; use rustc_errors::DiagCtxtHandle; -use rustc_expand::base::{parse_macro_name_and_helper_attrs, ExtCtxt, ResolverExpand}; +use rustc_expand::base::{ExtCtxt, ResolverExpand, parse_macro_name_and_helper_attrs}; use rustc_expand::expand::{AstFragment, ExpansionConfig}; use rustc_feature::Features; use rustc_session::Session; use rustc_span::hygiene::AstPass; use rustc_span::source_map::SourceMap; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, Span}; use smallvec::smallvec; -use thin_vec::{thin_vec, ThinVec}; +use thin_vec::{ThinVec, thin_vec}; use crate::errors; @@ -302,29 +302,25 @@ 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) => { cx.resolver.declare_proc_macro(cd.id); - cx.expr_call( - span, - proc_macro_ty_method_path(cx, custom_derive), - thin_vec![ - cx.expr_str(span, cd.trait_name), - cx.expr_array_ref( - span, - cd.attrs - .iter() - .map(|&s| cx.expr_str(span, s)) - .collect::>(), - ), - local_path(cx, cd.function_name), - ], - ) + cx.expr_call(span, proc_macro_ty_method_path(cx, custom_derive), thin_vec![ + cx.expr_str(span, cd.trait_name), + cx.expr_array_ref( + span, + cd.attrs.iter().map(|&s| cx.expr_str(span, s)).collect::>(), + ), + local_path(cx, cd.function_name), + ]) } ProcMacro::Attr(ca) | ProcMacro::Bang(ca) => { cx.resolver.declare_proc_macro(ca.id); @@ -334,14 +330,10 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P { ProcMacro::Derive(_) => unreachable!(), }; - cx.expr_call( - 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(span, proc_macro_ty_method_path(cx, ident), thin_vec![ + cx.expr_str(span, ca.function_name.name), + local_path(cx, ca.function_name), + ]) } } }) @@ -355,9 +347,12 @@ 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/source_util.rs b/compiler/rustc_builtin_macros/src/source_util.rs index 9554d97829e..946fbe918e6 100644 --- a/compiler/rustc_builtin_macros/src/source_util.rs +++ b/compiler/rustc_builtin_macros/src/source_util.rs @@ -8,7 +8,7 @@ use rustc_ast_pretty::pprust; use rustc_data_structures::sync::Lrc; use rustc_expand::base::{ - resolve_path, DummyResult, ExpandResult, ExtCtxt, MacEager, MacResult, MacroExpanderResult, + DummyResult, ExpandResult, ExtCtxt, MacEager, MacResult, MacroExpanderResult, resolve_path, }; use rustc_expand::module::DirOwnership; use rustc_lint_defs::BuiltinLintDiag; @@ -73,8 +73,8 @@ pub(crate) fn expand_file( let topmost = cx.expansion_cause().unwrap_or(sp); let loc = cx.source_map().lookup_char_pos(topmost.lo()); - use rustc_session::config::RemapPathScopeComponents; use rustc_session::RemapFileNameExt; + use rustc_session::config::RemapPathScopeComponents; ExpandResult::Ready(MacEager::expr(cx.expr_str( topmost, Symbol::intern( diff --git a/compiler/rustc_builtin_macros/src/standard_library_imports.rs b/compiler/rustc_builtin_macros/src/standard_library_imports.rs index 9bcd793c450..a3fc53344ab 100644 --- a/compiler/rustc_builtin_macros/src/standard_library_imports.rs +++ b/compiler/rustc_builtin_macros/src/standard_library_imports.rs @@ -3,10 +3,10 @@ use rustc_expand::expand::ExpansionConfig; use rustc_feature::Features; use rustc_session::Session; +use rustc_span::DUMMY_SP; use rustc_span::edition::Edition::*; use rustc_span::hygiene::AstPass; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::DUMMY_SP; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use thin_vec::thin_vec; pub fn inject( diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index 40dc75339ef..664e935ee14 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -5,13 +5,13 @@ use std::iter; use rustc_ast::ptr::P; -use rustc_ast::{self as ast, attr, GenericParamKind}; +use rustc_ast::{self as ast, GenericParamKind, attr}; use rustc_ast_pretty::pprust; use rustc_errors::{Applicability, Diag, Level}; use rustc_expand::base::*; -use rustc_span::symbol::{sym, Ident, Symbol}; +use rustc_span::symbol::{Ident, Symbol, sym}; use rustc_span::{ErrorGuaranteed, FileNameDisplayPreference, Span}; -use thin_vec::{thin_vec, ThinVec}; +use thin_vec::{ThinVec, thin_vec}; use tracing::debug; use crate::errors; @@ -170,26 +170,20 @@ 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 @@ -209,55 +203,39 @@ 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("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("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)], - ), - ], + 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("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("assert_test_result")), - thin_vec![ - // $test_fn() - cx.expr_call( - ret_ty_sp, - cx.expr_path(cx.path(sp, vec![item.ident])), - ThinVec::new(), - ), // ) - ], - ), // } - )), // ) - ], - ) + ret_ty_sp, + cx.expr_path(cx.path(sp, vec![item.ident])), + ThinVec::new(), + ), // ) + ],), // } + )), // ) + ]) }; let test_path_symbol = Symbol::intern(&item_path( @@ -268,122 +246,107 @@ 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", - cx.expr_struct( - sp, - test_path("TestDesc"), - thin_vec![ - // name: "path::to::test" - field( - "name", - cx.expr_call( - sp, - cx.expr_path(test_path("StaticTestName")), - thin_vec![cx.expr_str(sp, test_path_symbol)], - ), + cx.expr_struct(sp, test_path("TestDesc"), thin_vec![ + // name: "path::to::test" + field( + "name", + cx.expr_call( + sp, + cx.expr_path(test_path("StaticTestName")), + thin_vec![cx.expr_str(sp, test_path_symbol)], ), - // ignore: true | false - field("ignore", cx.expr_bool(sp, should_ignore(&item)),), - // ignore_message: Some("...") | None - field( - "ignore_message", - if let Some(msg) = should_ignore_message(&item) { - cx.expr_some(sp, cx.expr_str(sp, msg)) - } else { - cx.expr_none(sp) - }, + ), + // ignore: true | false + field("ignore", cx.expr_bool(sp, should_ignore(&item)),), + // ignore_message: Some("...") | None + field( + "ignore_message", + if let Some(msg) = should_ignore_message(&item) { + cx.expr_some(sp, cx.expr_str(sp, msg)) + } else { + cx.expr_none(sp) + }, + ), + // source_file: + field("source_file", cx.expr_str(sp, location_info.0)), + // start_line: start line of the test fn identifier. + field("start_line", cx.expr_usize(sp, location_info.1)), + // start_col: start column of the test fn identifier. + field("start_col", cx.expr_usize(sp, location_info.2)), + // end_line: end line of the test fn identifier. + field("end_line", cx.expr_usize(sp, location_info.3)), + // end_col: end column of the test fn identifier. + field("end_col", cx.expr_usize(sp, location_info.4)), + // compile_fail: true | false + field("compile_fail", cx.expr_bool(sp, false)), + // no_run: true | false + field("no_run", cx.expr_bool(sp, false)), + // should_panic: ... + field("should_panic", match should_panic(cx, &item) { + // test::ShouldPanic::No + ShouldPanic::No => { + cx.expr_path(should_panic_path("No")) + } + // test::ShouldPanic::Yes + ShouldPanic::Yes(None) => { + cx.expr_path(should_panic_path("Yes")) + } + // test::ShouldPanic::YesWithMessage("...") + ShouldPanic::Yes(Some(sym)) => cx.expr_call( + sp, + cx.expr_path(should_panic_path("YesWithMessage")), + thin_vec![cx.expr_str(sp, sym)], ), - // source_file: - field("source_file", cx.expr_str(sp, location_info.0)), - // start_line: start line of the test fn identifier. - field("start_line", cx.expr_usize(sp, location_info.1)), - // start_col: start column of the test fn identifier. - field("start_col", cx.expr_usize(sp, location_info.2)), - // end_line: end line of the test fn identifier. - field("end_line", cx.expr_usize(sp, location_info.3)), - // end_col: end column of the test fn identifier. - field("end_col", cx.expr_usize(sp, location_info.4)), - // compile_fail: true | false - field("compile_fail", cx.expr_bool(sp, false)), - // no_run: true | false - field("no_run", cx.expr_bool(sp, false)), - // should_panic: ... - field( - "should_panic", - match should_panic(cx, &item) { - // test::ShouldPanic::No - ShouldPanic::No => { - cx.expr_path(should_panic_path("No")) - } - // test::ShouldPanic::Yes - ShouldPanic::Yes(None) => { - cx.expr_path(should_panic_path("Yes")) - } - // test::ShouldPanic::YesWithMessage("...") - ShouldPanic::Yes(Some(sym)) => cx.expr_call( - sp, - cx.expr_path(should_panic_path("YesWithMessage")), - thin_vec![cx.expr_str(sp, sym)], - ), - }, - ), - // test_type: ... - field( - "test_type", - match test_type(cx) { - // test::TestType::UnitTest - TestType::UnitTest => { - cx.expr_path(test_type_path("UnitTest")) - } - // test::TestType::IntegrationTest - TestType::IntegrationTest => { - cx.expr_path(test_type_path("IntegrationTest")) - } - // test::TestPath::Unknown - TestType::Unknown => { - cx.expr_path(test_type_path("Unknown")) - } - }, - ), - // }, - ], - ), + },), + // test_type: ... + field("test_type", match test_type(cx) { + // test::TestType::UnitTest + TestType::UnitTest => { + cx.expr_path(test_type_path("UnitTest")) + } + // test::TestType::IntegrationTest + TestType::IntegrationTest => { + cx.expr_path(test_type_path("IntegrationTest")) + } + // test::TestPath::Unknown + TestType::Unknown => { + cx.expr_path(test_type_path("Unknown")) + } + },), + // }, + ],), ), // 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_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index 400557ca260..95348453308 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -6,21 +6,21 @@ use rustc_ast::entry::EntryPointType; use rustc_ast::mut_visit::*; use rustc_ast::ptr::P; -use rustc_ast::visit::{walk_item, Visitor}; -use rustc_ast::{attr, ModKind}; +use rustc_ast::visit::{Visitor, walk_item}; +use rustc_ast::{ModKind, attr}; use rustc_errors::DiagCtxtHandle; use rustc_expand::base::{ExtCtxt, ResolverExpand}; use rustc_expand::expand::{AstFragment, ExpansionConfig}; use rustc_feature::Features; use rustc_lint_defs::BuiltinLintDiag; -use rustc_session::lint::builtin::UNNAMEABLE_TEST_ITEMS; use rustc_session::Session; +use rustc_session::lint::builtin::UNNAMEABLE_TEST_ITEMS; use rustc_span::hygiene::{AstPass, SyntaxContext, Transparency}; -use rustc_span::symbol::{sym, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, Symbol, sym}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::spec::PanicStrategy; -use smallvec::{smallvec, SmallVec}; -use thin_vec::{thin_vec, ThinVec}; +use smallvec::{SmallVec, smallvec}; +use thin_vec::{ThinVec, thin_vec}; use tracing::debug; use crate::errors; diff --git a/compiler/rustc_builtin_macros/src/trace_macros.rs b/compiler/rustc_builtin_macros/src/trace_macros.rs index bd9ebc355e1..e624d1da66b 100644 --- a/compiler/rustc_builtin_macros/src/trace_macros.rs +++ b/compiler/rustc_builtin_macros/src/trace_macros.rs @@ -1,7 +1,7 @@ use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_expand::base::{DummyResult, ExpandResult, ExtCtxt, MacroExpanderResult}; -use rustc_span::symbol::kw; use rustc_span::Span; +use rustc_span::symbol::kw; use crate::errors; diff --git a/compiler/rustc_builtin_macros/src/util.rs b/compiler/rustc_builtin_macros/src/util.rs index 0bcd5aef28b..d7b03a43ecb 100644 --- a/compiler/rustc_builtin_macros/src/util.rs +++ b/compiler/rustc_builtin_macros/src/util.rs @@ -1,12 +1,12 @@ use rustc_ast::ptr::P; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{self as ast, attr, token, AttrStyle, Attribute, MetaItem}; +use rustc_ast::{self as ast, AttrStyle, Attribute, MetaItem, attr, token}; use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt}; use rustc_expand::expand::AstFragment; use rustc_feature::AttributeTemplate; -use rustc_lint_defs::builtin::DUPLICATE_MACRO_ATTRIBUTES; use rustc_lint_defs::BuiltinLintDiag; +use rustc_lint_defs::builtin::DUPLICATE_MACRO_ATTRIBUTES; use rustc_parse::{parser, validate_attr}; use rustc_session::errors::report_lit_error; use rustc_span::{BytePos, Span, Symbol}; diff --git a/compiler/rustc_codegen_cranelift/.cirrus.yml b/compiler/rustc_codegen_cranelift/.cirrus.yml index 5a464bfac36..1ec99eb3d17 100644 --- a/compiler/rustc_codegen_cranelift/.cirrus.yml +++ b/compiler/rustc_codegen_cranelift/.cirrus.yml @@ -3,7 +3,7 @@ task: freebsd_instance: image: freebsd-13-2-release-amd64 setup_rust_script: - - pkg install -y git bash binutils + - pkg install -y git-tiny binutils - curl https://sh.rustup.rs -sSf --output rustup.sh - sh rustup.sh --default-toolchain none -y --profile=minimal target_cache: diff --git a/compiler/rustc_codegen_cranelift/.github/workflows/main.yml b/compiler/rustc_codegen_cranelift/.github/workflows/main.yml index 896a5c34c3e..2ee94146c1a 100644 --- a/compiler/rustc_codegen_cranelift/.github/workflows/main.yml +++ b/compiler/rustc_codegen_cranelift/.github/workflows/main.yml @@ -279,8 +279,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 if: ${{ github.ref == 'refs/heads/master' }} - # FIXME add the bench job back to the dependency list once rust-lang/rust#125493 gets merged - needs: [rustfmt, test, dist] + needs: [rustfmt, test, bench, dist] permissions: contents: write # for creating the dev tag and release diff --git a/compiler/rustc_codegen_cranelift/Cargo.lock b/compiler/rustc_codegen_cranelift/Cargo.lock index 02d4d98dc42..1c2ca95b075 100644 --- a/compiler/rustc_codegen_cranelift/Cargo.lock +++ b/compiler/rustc_codegen_cranelift/Cargo.lock @@ -46,24 +46,24 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "cranelift-bforest" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "effa84ab2023f7138045ece6b326588c17447ca22e66db71ec15cb0a6c0c4ad2" +checksum = "b80c3a50b9c4c7e5b5f73c0ed746687774fc9e36ef652b110da8daebf0c6e0e6" dependencies = [ "cranelift-entity", ] [[package]] name = "cranelift-bitset" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "38a1dfc50dca188a15d938867c4400589530bcb0138f7022aae6d059d1d8c309" +checksum = "38778758c2ca918b05acb2199134e0c561fb577c50574259b26190b6c2d95ded" [[package]] name = "cranelift-codegen" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "821c20c639350158ecca928dc2a244d0d1c9cef2377a378fc62a445a286eb1ca" +checksum = "58258667ad10e468bfc13a8d620f50dfcd4bb35d668123e97defa2549b9ad397" dependencies = [ "bumpalo", "cranelift-bforest", @@ -84,42 +84,42 @@ dependencies = [ [[package]] name = "cranelift-codegen-meta" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "064473f2fd59b44fa2c9aaa60de1f9c44db5e13521e28bc85d2b92ee535ef625" +checksum = "043f0b702e529dcb07ff92bd7d40e7d5317b5493595172c5eb0983343751ee06" dependencies = [ "cranelift-codegen-shared", ] [[package]] name = "cranelift-codegen-shared" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0f39b9ebfd2febdc2acfb9a0fca110665bcd5a6839502576307735ed07b2177" +checksum = "7763578888ab53eca5ce7da141953f828e82c2bfadcffc106d10d1866094ffbb" [[package]] name = "cranelift-control" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94e125c189c3a1ca8dfe209fc6f46edba058a6d24e0b92aff69459a15f4711e7" +checksum = "32db15f08c05df570f11e8ab33cb1ec449a64b37c8a3498377b77650bef33d8b" dependencies = [ "arbitrary", ] [[package]] name = "cranelift-entity" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea62eb109baec2247e1a6fa7b74c0f584b1e76e289cfd7017385b4b031fc8450" +checksum = "5289cdb399381a27e7bbfa1b42185916007c3d49aeef70b1d01cb4caa8010130" dependencies = [ "cranelift-bitset", ] [[package]] name = "cranelift-frontend" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "722b089357aacb6c7528b2e59a5fe00917d61ce63448b25a3e477a5b7819fac8" +checksum = "31ba8ab24eb9470477e98ddfa3c799a649ac5a0d9a2042868c4c952133c234e8" dependencies = [ "cranelift-codegen", "log", @@ -129,15 +129,15 @@ dependencies = [ [[package]] name = "cranelift-isle" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4b5005a48288e7fc2a2991a377831c534e26929b063c379c018060727785a9b" +checksum = "2b72a3c5c166a70426dcb209bdd0bb71a787c1ea76023dc0974fbabca770e8f9" [[package]] name = "cranelift-jit" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f843932baf8d1025c5f114b929eda172d74b7163d058e0de2597c308b567c7e9" +checksum = "df32578a47582e49b4fc1f9a5786839d9be1fedaa9f00bea7612c54425663c6b" dependencies = [ "anyhow", "cranelift-codegen", @@ -155,9 +155,9 @@ dependencies = [ [[package]] name = "cranelift-module" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "449819ef1c4af139cf1b9717916fcaea0e23248853d3e95135139773a842d3eb" +checksum = "96094a758cdb543c9143f70817cd31069fecd49f50981a0fac06820ac011dc2f" dependencies = [ "anyhow", "cranelift-codegen", @@ -166,9 +166,9 @@ dependencies = [ [[package]] name = "cranelift-native" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ae2d48f38081a9e679ad795bd36bb29bedeb5552fc1c195185bf9885fa1b16e" +checksum = "46a42424c956bbc31fc5c2706073df896156c5420ae8fa2a5d48dbc7b295d71b" dependencies = [ "cranelift-codegen", "libc", @@ -177,9 +177,9 @@ dependencies = [ [[package]] name = "cranelift-object" -version = "0.110.1" +version = "0.111.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3a39ee2cfd0ec485eca76f6b4dc17701a280fa406bc05137bb43f1635ed12c9f" +checksum = "1cf5e2484ab47fe38a3150747cdd2016535f13542a925acca152b63383a6591b" dependencies = [ "anyhow", "cranelift-codegen", @@ -213,9 +213,9 @@ checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" [[package]] name = "gimli" -version = "0.28.1" +version = "0.29.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4271d37baee1b8c7e4b708028c57d816cf9d2434acb33a549475f78c181f6253" +checksum = "40ecd4077b5ae9fd2e9e169b102c6c330d0605168eb0e8bf79952b256dbefffd" dependencies = [ "fallible-iterator", "indexmap", @@ -403,9 +403,9 @@ dependencies = [ [[package]] name = "target-lexicon" -version = "0.12.15" +version = "0.12.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4873307b7c257eddcb50c9bedf158eb669578359fb28428bef438fec8e6ba7c2" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" [[package]] name = "unicode-ident" @@ -421,9 +421,9 @@ checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" [[package]] name = "wasmtime-jit-icache-coherence" -version = "23.0.1" +version = "24.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fddf3e2980fb1d123d1fcac55189e417fdd3dba4f62139b5a0a1f9efe5669d5" +checksum = "d15de8429db996f0d17a4163a35eccc3f874cbfb50f29c379951ea1bbb39452e" dependencies = [ "anyhow", "cfg-if", diff --git a/compiler/rustc_codegen_cranelift/Cargo.toml b/compiler/rustc_codegen_cranelift/Cargo.toml index a0df502dadc..6594ffb5d66 100644 --- a/compiler/rustc_codegen_cranelift/Cargo.toml +++ b/compiler/rustc_codegen_cranelift/Cargo.toml @@ -8,14 +8,14 @@ crate-type = ["dylib"] [dependencies] # These have to be in sync with each other -cranelift-codegen = { version = "0.110.1", default-features = false, features = ["std", "unwind", "all-arch"] } -cranelift-frontend = { version = "0.110.1" } -cranelift-module = { version = "0.110.1" } -cranelift-native = { version = "0.110.1" } -cranelift-jit = { version = "0.110.1", optional = true } -cranelift-object = { version = "0.110.1" } +cranelift-codegen = { version = "0.111.0", default-features = false, features = ["std", "unwind", "all-arch"] } +cranelift-frontend = { version = "0.111.0" } +cranelift-module = { version = "0.111.0" } +cranelift-native = { version = "0.111.0" } +cranelift-jit = { version = "0.111.0", optional = true } +cranelift-object = { version = "0.111.0" } target-lexicon = "0.12.0" -gimli = { version = "0.28", default-features = false, features = ["write"]} +gimli = { version = "0.29", default-features = false, features = ["write"] } object = { version = "0.36", default-features = false, features = ["std", "read_core", "write", "archive", "coff", "elf", "macho", "pe"] } indexmap = "2.0.0" diff --git a/compiler/rustc_codegen_cranelift/build_system/abi_cafe.rs b/compiler/rustc_codegen_cranelift/build_system/abi_cafe.rs index e3f1162445b..9292778806a 100644 --- a/compiler/rustc_codegen_cranelift/build_system/abi_cafe.rs +++ b/compiler/rustc_codegen_cranelift/build_system/abi_cafe.rs @@ -1,7 +1,7 @@ use crate::path::{Dirs, RelPath}; use crate::prepare::GitRepo; -use crate::utils::{spawn_and_wait, CargoProject, Compiler}; -use crate::{build_sysroot, CodegenBackend, SysrootKind}; +use crate::utils::{CargoProject, Compiler, spawn_and_wait}; +use crate::{CodegenBackend, SysrootKind, build_sysroot}; static ABI_CAFE_REPO: GitRepo = GitRepo::github( "Gankra", @@ -14,7 +14,6 @@ static ABI_CAFE: CargoProject = CargoProject::new(&ABI_CAFE_REPO.source_dir(), "abi_cafe_target"); pub(crate) fn run( - channel: &str, sysroot_kind: SysrootKind, dirs: &Dirs, cg_clif_dylib: &CodegenBackend, @@ -28,7 +27,6 @@ pub(crate) fn run( eprintln!("Building sysroot for abi-cafe"); build_sysroot::build_sysroot( dirs, - channel, sysroot_kind, cg_clif_dylib, bootstrap_host_compiler, @@ -38,12 +36,11 @@ pub(crate) fn run( eprintln!("Running abi-cafe"); - let pairs = ["rustc_calls_cgclif", "cgclif_calls_rustc", "cgclif_calls_cc", "cc_calls_cgclif"]; - let pairs = + let pairs: &[_] = if cfg!(not(any(target_os = "macos", all(target_os = "windows", target_env = "msvc")))) { - &pairs[..] + &["rustc_calls_cgclif", "cgclif_calls_rustc", "cgclif_calls_cc", "cc_calls_cgclif"] } else { - &pairs[..2] + &["rustc_calls_cgclif", "cgclif_calls_rustc"] }; let mut cmd = ABI_CAFE.run(bootstrap_host_compiler, dirs); diff --git a/compiler/rustc_codegen_cranelift/build_system/bench.rs b/compiler/rustc_codegen_cranelift/build_system/bench.rs index 6c64faaa256..ebeb6772250 100644 --- a/compiler/rustc_codegen_cranelift/build_system/bench.rs +++ b/compiler/rustc_codegen_cranelift/build_system/bench.rs @@ -1,11 +1,12 @@ use std::env; use std::io::Write; use std::path::Path; +use std::process::Command; use crate::path::{Dirs, RelPath}; use crate::prepare::GitRepo; use crate::rustc_info::get_file_name; -use crate::utils::{hyperfine_command, spawn_and_wait, Compiler}; +use crate::utils::{Compiler, spawn_and_wait}; static SIMPLE_RAYTRACER_REPO: GitRepo = GitRepo::github( "ebobby", @@ -128,3 +129,37 @@ fn benchmark_simple_raytracer(dirs: &Dirs, bootstrap_host_compiler: &Compiler) { gha_step_summary.write_all(b"\n").unwrap(); } } + +#[must_use] +fn hyperfine_command( + warmup: u64, + runs: u64, + prepare: Option<&str>, + cmds: &[(&str, &str)], + markdown_export: &Path, +) -> Command { + let mut bench = Command::new("hyperfine"); + + bench.arg("--export-markdown").arg(markdown_export); + + if warmup != 0 { + bench.arg("--warmup").arg(warmup.to_string()); + } + + if runs != 0 { + bench.arg("--runs").arg(runs.to_string()); + } + + if let Some(prepare) = prepare { + bench.arg("--prepare").arg(prepare); + } + + for &(name, cmd) in cmds { + if name != "" { + bench.arg("-n").arg(name); + } + bench.arg(cmd); + } + + bench +} diff --git a/compiler/rustc_codegen_cranelift/build_system/build_backend.rs b/compiler/rustc_codegen_cranelift/build_system/build_backend.rs index 129713e574a..02da89f737c 100644 --- a/compiler/rustc_codegen_cranelift/build_system/build_backend.rs +++ b/compiler/rustc_codegen_cranelift/build_system/build_backend.rs @@ -6,11 +6,10 @@ use crate::shared_utils::{rustflags_from_env, rustflags_to_cmd_env}; use crate::utils::{CargoProject, Compiler, LogGroup}; -pub(crate) static CG_CLIF: CargoProject = CargoProject::new(&RelPath::SOURCE, "cg_clif"); +static CG_CLIF: CargoProject = CargoProject::new(&RelPath::SOURCE, "cg_clif"); pub(crate) fn build_backend( dirs: &Dirs, - channel: &str, bootstrap_host_compiler: &Compiler, use_unstable_features: bool, ) -> PathBuf { @@ -19,8 +18,8 @@ pub(crate) fn build_backend( let mut cmd = CG_CLIF.build(&bootstrap_host_compiler, dirs); let mut rustflags = rustflags_from_env("RUSTFLAGS"); - rustflags.push("-Zallow-features=rustc_private".to_owned()); + rustflags_to_cmd_env(&mut cmd, "RUSTFLAGS", &rustflags); if env::var("CG_CLIF_EXPENSIVE_CHECKS").is_ok() { // Enabling debug assertions implicitly enables the clif ir verifier @@ -32,15 +31,7 @@ pub(crate) fn build_backend( cmd.arg("--features").arg("unstable-features"); } - match channel { - "debug" => {} - "release" => { - cmd.arg("--release"); - } - _ => unreachable!(), - } - - rustflags_to_cmd_env(&mut cmd, "RUSTFLAGS", &rustflags); + cmd.arg("--release"); eprintln!("[BUILD] rustc_codegen_cranelift"); crate::utils::spawn_and_wait(cmd); @@ -48,6 +39,6 @@ pub(crate) fn build_backend( CG_CLIF .target_dir(dirs) .join(&bootstrap_host_compiler.triple) - .join(channel) + .join("release") .join(get_file_name(&bootstrap_host_compiler.rustc, "rustc_codegen_cranelift", "dylib")) } diff --git a/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs b/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs index e41f6c5e709..82558999afa 100644 --- a/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs +++ b/compiler/rustc_codegen_cranelift/build_system/build_sysroot.rs @@ -3,19 +3,15 @@ use std::{env, fs}; use crate::path::{Dirs, RelPath}; -use crate::rustc_info::get_file_name; +use crate::prepare::apply_patches; +use crate::rustc_info::{get_default_sysroot, get_file_name}; use crate::utils::{ - remove_dir_if_exists, spawn_and_wait, try_hard_link, CargoProject, Compiler, LogGroup, + CargoProject, Compiler, LogGroup, ensure_empty_dir, spawn_and_wait, try_hard_link, }; -use crate::{config, CodegenBackend, SysrootKind}; - -static DIST_DIR: RelPath = RelPath::DIST; -static BIN_DIR: RelPath = RelPath::DIST.join("bin"); -static LIB_DIR: RelPath = RelPath::DIST.join("lib"); +use crate::{CodegenBackend, SysrootKind, config}; pub(crate) fn build_sysroot( dirs: &Dirs, - channel: &str, sysroot_kind: SysrootKind, cg_clif_dylib_src: &CodegenBackend, bootstrap_host_compiler: &Compiler, @@ -26,9 +22,11 @@ pub(crate) fn build_sysroot( eprintln!("[BUILD] sysroot {:?}", sysroot_kind); - DIST_DIR.ensure_fresh(dirs); - BIN_DIR.ensure_exists(dirs); - LIB_DIR.ensure_exists(dirs); + let dist_dir = RelPath::DIST.to_path(dirs); + + ensure_empty_dir(&dist_dir); + fs::create_dir_all(dist_dir.join("bin")).unwrap(); + fs::create_dir_all(dist_dir.join("lib")).unwrap(); let is_native = bootstrap_host_compiler.triple == target_triple; @@ -38,11 +36,10 @@ pub(crate) fn build_sysroot( let cg_clif_dylib_path = if cfg!(windows) { // Windows doesn't have rpath support, so the cg_clif dylib needs to be next to the // binaries. - BIN_DIR + dist_dir.join("bin") } else { - LIB_DIR + dist_dir.join("lib") } - .to_path(dirs) .join(src_path.file_name().unwrap()); try_hard_link(src_path, &cg_clif_dylib_path); CodegenBackend::Local(cg_clif_dylib_path) @@ -56,7 +53,7 @@ pub(crate) fn build_sysroot( let wrapper_name = wrapper_base_name.replace("____", wrapper); let mut build_cargo_wrapper_cmd = Command::new(&bootstrap_host_compiler.rustc); - let wrapper_path = DIST_DIR.to_path(dirs).join(&wrapper_name); + let wrapper_path = dist_dir.join(&wrapper_name); build_cargo_wrapper_cmd .arg(RelPath::SCRIPTS.to_path(dirs).join(&format!("{wrapper}.rs"))) .arg("-o") @@ -79,22 +76,20 @@ pub(crate) fn build_sysroot( build_cargo_wrapper_cmd.env("BUILTIN_BACKEND", name); } spawn_and_wait(build_cargo_wrapper_cmd); - try_hard_link(wrapper_path, BIN_DIR.to_path(dirs).join(wrapper_name)); + try_hard_link(wrapper_path, dist_dir.join("bin").join(wrapper_name)); } let host = build_sysroot_for_triple( dirs, - channel, bootstrap_host_compiler.clone(), &cg_clif_dylib_path, sysroot_kind, ); - host.install_into_sysroot(&DIST_DIR.to_path(dirs)); + host.install_into_sysroot(&dist_dir); if !is_native { build_sysroot_for_triple( dirs, - channel, { let mut bootstrap_target_compiler = bootstrap_host_compiler.clone(); bootstrap_target_compiler.triple = target_triple.clone(); @@ -104,7 +99,7 @@ pub(crate) fn build_sysroot( &cg_clif_dylib_path, sysroot_kind, ) - .install_into_sysroot(&DIST_DIR.to_path(dirs)); + .install_into_sysroot(&dist_dir); } // Copy std for the host to the lib dir. This is necessary for the jit mode to find @@ -112,16 +107,13 @@ pub(crate) fn build_sysroot( for lib in host.libs { let filename = lib.file_name().unwrap().to_str().unwrap(); if filename.contains("std-") && !filename.contains(".rlib") { - try_hard_link(&lib, LIB_DIR.to_path(dirs).join(lib.file_name().unwrap())); + try_hard_link(&lib, dist_dir.join("lib").join(lib.file_name().unwrap())); } } let mut target_compiler = { - let dirs: &Dirs = &dirs; - let rustc_clif = - RelPath::DIST.to_path(&dirs).join(wrapper_base_name.replace("____", "rustc-clif")); - let rustdoc_clif = - RelPath::DIST.to_path(&dirs).join(wrapper_base_name.replace("____", "rustdoc-clif")); + let rustc_clif = dist_dir.join(wrapper_base_name.replace("____", "rustc-clif")); + let rustdoc_clif = dist_dir.join(wrapper_base_name.replace("____", "rustdoc-clif")); Compiler { cargo: bootstrap_host_compiler.cargo.clone(), @@ -139,6 +131,7 @@ pub(crate) fn build_sysroot( target_compiler } +#[must_use] struct SysrootTarget { triple: String, libs: Vec, @@ -159,15 +152,13 @@ fn install_into_sysroot(&self, sysroot: &Path) { } } -pub(crate) static STDLIB_SRC: RelPath = RelPath::BUILD.join("stdlib"); -pub(crate) static STANDARD_LIBRARY: CargoProject = +static STDLIB_SRC: RelPath = RelPath::BUILD.join("stdlib"); +static STANDARD_LIBRARY: CargoProject = CargoProject::new(&STDLIB_SRC.join("library/sysroot"), "stdlib_target"); -pub(crate) static RTSTARTUP_SYSROOT: RelPath = RelPath::BUILD.join("rtstartup"); +static RTSTARTUP_SYSROOT: RelPath = RelPath::BUILD.join("rtstartup"); -#[must_use] fn build_sysroot_for_triple( dirs: &Dirs, - channel: &str, compiler: Compiler, cg_clif_dylib_path: &CodegenBackend, sysroot_kind: SysrootKind, @@ -176,13 +167,10 @@ fn build_sysroot_for_triple( SysrootKind::None => build_rtstartup(dirs, &compiler) .unwrap_or(SysrootTarget { triple: compiler.triple, libs: vec![] }), SysrootKind::Llvm => build_llvm_sysroot_for_triple(compiler), - SysrootKind::Clif => { - build_clif_sysroot_for_triple(dirs, channel, compiler, cg_clif_dylib_path) - } + SysrootKind::Clif => build_clif_sysroot_for_triple(dirs, compiler, cg_clif_dylib_path), } } -#[must_use] fn build_llvm_sysroot_for_triple(compiler: Compiler) -> SysrootTarget { let default_sysroot = crate::rustc_info::get_default_sysroot(&compiler.rustc); @@ -216,10 +204,8 @@ fn build_llvm_sysroot_for_triple(compiler: Compiler) -> SysrootTarget { target_libs } -#[must_use] fn build_clif_sysroot_for_triple( dirs: &Dirs, - channel: &str, mut compiler: Compiler, cg_clif_dylib_path: &CodegenBackend, ) -> SysrootTarget { @@ -231,12 +217,12 @@ fn build_clif_sysroot_for_triple( target_libs.libs.extend(rtstartup_target_libs.libs); } - let build_dir = STANDARD_LIBRARY.target_dir(dirs).join(&compiler.triple).join(channel); + let build_dir = STANDARD_LIBRARY.target_dir(dirs).join(&compiler.triple).join("release"); if !config::get_bool("keep_sysroot") { // Cleanup the deps dir, but keep build scripts and the incremental cache for faster // recompilation as they are not affected by changes in cg_clif. - remove_dir_if_exists(&build_dir.join("deps")); + ensure_empty_dir(&build_dir.join("deps")); } // Build sysroot @@ -252,12 +238,12 @@ fn build_clif_sysroot_for_triple( // Necessary for MinGW to find rsbegin.o and rsend.o rustflags.push("--sysroot".to_owned()); rustflags.push(RTSTARTUP_SYSROOT.to_path(dirs).to_str().unwrap().to_owned()); - if channel == "release" { - // Incremental compilation by default disables mir inlining. This leads to both a decent - // compile perf and a significant runtime perf regression. As such forcefully enable mir - // inlining. - rustflags.push("-Zinline-mir".to_owned()); - } + + // Incremental compilation by default disables mir inlining. This leads to both a decent + // compile perf and a significant runtime perf regression. As such forcefully enable mir + // inlining. + rustflags.push("-Zinline-mir".to_owned()); + if let Some(prefix) = env::var_os("CG_CLIF_STDLIB_REMAP_PATH_PREFIX") { rustflags.push("--remap-path-prefix".to_owned()); rustflags.push(format!( @@ -268,9 +254,7 @@ fn build_clif_sysroot_for_triple( } compiler.rustflags.extend(rustflags); let mut build_cmd = STANDARD_LIBRARY.build(&compiler, dirs); - if channel == "release" { - build_cmd.arg("--release"); - } + build_cmd.arg("--release"); build_cmd.arg("--features").arg("backtrace panic-unwind compiler-builtins-no-f16-f128"); build_cmd.env("CARGO_PROFILE_RELEASE_DEBUG", "true"); build_cmd.env("__CARGO_DEFAULT_LIB_METADATA", "cg_clif"); @@ -296,7 +280,10 @@ fn build_clif_sysroot_for_triple( fn build_rtstartup(dirs: &Dirs, compiler: &Compiler) -> Option { if !config::get_bool("keep_sysroot") { - crate::prepare::prepare_stdlib(dirs, &compiler.rustc); + let sysroot_src_orig = get_default_sysroot(&compiler.rustc).join("lib/rustlib/src/rust"); + assert!(sysroot_src_orig.exists()); + + apply_patches(dirs, "stdlib", &sysroot_src_orig, &STDLIB_SRC.to_path(dirs)); } if !compiler.triple.ends_with("windows-gnu") { diff --git a/compiler/rustc_codegen_cranelift/build_system/main.rs b/compiler/rustc_codegen_cranelift/build_system/main.rs index 9ddeda583af..b68ac7c0926 100644 --- a/compiler/rustc_codegen_cranelift/build_system/main.rs +++ b/compiler/rustc_codegen_cranelift/build_system/main.rs @@ -81,7 +81,6 @@ fn main() { let mut out_dir = PathBuf::from("."); let mut download_dir = None; - let mut channel = "release"; let mut sysroot_kind = SysrootKind::Clif; let mut use_unstable_features = true; let mut frozen = false; @@ -99,7 +98,6 @@ fn main() { arg_error!("--download-dir requires argument"); }))); } - "--debug" => channel = "debug", "--sysroot" => { sysroot_kind = match args.next().as_deref() { Some("none") => SysrootKind::None, @@ -206,7 +204,6 @@ fn main() { } else { CodegenBackend::Local(build_backend::build_backend( &dirs, - channel, &bootstrap_host_compiler, use_unstable_features, )) @@ -218,7 +215,6 @@ fn main() { Command::Test => { tests::run_tests( &dirs, - channel, sysroot_kind, use_unstable_features, &skip_tests.iter().map(|test| &**test).collect::>(), @@ -234,7 +230,6 @@ fn main() { process::exit(1); } abi_cafe::run( - channel, sysroot_kind, &dirs, &cg_clif_dylib, @@ -245,7 +240,6 @@ fn main() { Command::Build => { build_sysroot::build_sysroot( &dirs, - channel, sysroot_kind, &cg_clif_dylib, &bootstrap_host_compiler, @@ -256,7 +250,6 @@ fn main() { Command::Bench => { build_sysroot::build_sysroot( &dirs, - channel, sysroot_kind, &cg_clif_dylib, &bootstrap_host_compiler, diff --git a/compiler/rustc_codegen_cranelift/build_system/path.rs b/compiler/rustc_codegen_cranelift/build_system/path.rs index 8572815fc55..35e7e81c528 100644 --- a/compiler/rustc_codegen_cranelift/build_system/path.rs +++ b/compiler/rustc_codegen_cranelift/build_system/path.rs @@ -1,7 +1,7 @@ use std::fs; use std::path::PathBuf; -use crate::utils::remove_dir_if_exists; +use crate::utils::ensure_empty_dir; #[derive(Debug, Clone)] pub(crate) struct Dirs { @@ -64,7 +64,6 @@ pub(crate) fn ensure_exists(&self, dirs: &Dirs) { pub(crate) fn ensure_fresh(&self, dirs: &Dirs) { let path = self.to_path(dirs); - remove_dir_if_exists(&path); - fs::create_dir_all(path).unwrap(); + ensure_empty_dir(&path); } } diff --git a/compiler/rustc_codegen_cranelift/build_system/prepare.rs b/compiler/rustc_codegen_cranelift/build_system/prepare.rs index be0bed0f4e6..30bd7ae26a1 100644 --- a/compiler/rustc_codegen_cranelift/build_system/prepare.rs +++ b/compiler/rustc_codegen_cranelift/build_system/prepare.rs @@ -4,12 +4,8 @@ use std::path::{Path, PathBuf}; use std::process::Command; -use crate::build_sysroot::STDLIB_SRC; use crate::path::{Dirs, RelPath}; -use crate::rustc_info::get_default_sysroot; -use crate::utils::{ - copy_dir_recursively, git_command, remove_dir_if_exists, retry_spawn_and_wait, spawn_and_wait, -}; +use crate::utils::{copy_dir_recursively, ensure_empty_dir, spawn_and_wait}; pub(crate) fn prepare(dirs: &Dirs) { RelPath::DOWNLOAD.ensure_exists(dirs); @@ -17,13 +13,6 @@ pub(crate) fn prepare(dirs: &Dirs) { crate::tests::REGEX_REPO.fetch(dirs); } -pub(crate) fn prepare_stdlib(dirs: &Dirs, rustc: &Path) { - let sysroot_src_orig = get_default_sysroot(rustc).join("lib/rustlib/src/rust"); - assert!(sysroot_src_orig.exists()); - - apply_patches(dirs, "stdlib", &sysroot_src_orig, &STDLIB_SRC.to_path(dirs)); -} - pub(crate) struct GitRepo { url: GitRepoUrl, rev: &'static str, @@ -119,7 +108,11 @@ pub(crate) fn fetch(&self, dirs: &Dirs) { match self.url { GitRepoUrl::Github { user, repo } => { - clone_repo_shallow_github(dirs, &download_dir, user, repo, self.rev); + clone_repo( + &download_dir, + &format!("https://github.com/{}/{}.git", user, repo), + self.rev, + ); } } @@ -154,7 +147,6 @@ pub(crate) fn patch(&self, dirs: &Dirs) { } } -#[allow(dead_code)] fn clone_repo(download_dir: &Path, repo: &str, rev: &str) { eprintln!("[CLONE] {}", repo); // Ignore exit code as the repo may already have been checked out @@ -171,55 +163,6 @@ fn clone_repo(download_dir: &Path, repo: &str, rev: &str) { std::fs::remove_dir_all(download_dir.join(".git")).unwrap(); } -fn clone_repo_shallow_github(dirs: &Dirs, download_dir: &Path, user: &str, repo: &str, rev: &str) { - if cfg!(windows) { - // Older windows doesn't have tar or curl by default. Fall back to using git. - clone_repo(download_dir, &format!("https://github.com/{}/{}.git", user, repo), rev); - return; - } - - let archive_url = format!("https://github.com/{}/{}/archive/{}.tar.gz", user, repo, rev); - let archive_file = RelPath::DOWNLOAD.to_path(dirs).join(format!("{}.tar.gz", rev)); - let archive_dir = RelPath::DOWNLOAD.to_path(dirs).join(format!("{}-{}", repo, rev)); - - eprintln!("[DOWNLOAD] {}/{} from {}", user, repo, archive_url); - - // Remove previous results if they exists - let _ = std::fs::remove_file(&archive_file); - let _ = std::fs::remove_dir_all(&archive_dir); - let _ = std::fs::remove_dir_all(&download_dir); - - // Download zip archive - let mut download_cmd = Command::new("curl"); - download_cmd - .arg("--max-time") - .arg("600") - .arg("-y") - .arg("30") - .arg("-Y") - .arg("10") - .arg("--connect-timeout") - .arg("30") - .arg("--continue-at") - .arg("-") - .arg("--location") - .arg("--output") - .arg(&archive_file) - .arg(archive_url); - retry_spawn_and_wait(5, download_cmd); - - // Unpack tar archive - let mut unpack_cmd = Command::new("tar"); - unpack_cmd.arg("xf").arg(&archive_file).current_dir(RelPath::DOWNLOAD.to_path(dirs)); - spawn_and_wait(unpack_cmd); - - // Rename unpacked dir to the expected name - std::fs::rename(archive_dir, &download_dir).unwrap(); - - // Cleanup - std::fs::remove_file(archive_file).unwrap(); -} - fn init_git_repo(repo_dir: &Path) { let mut git_init_cmd = git_command(repo_dir, "init"); git_init_cmd.arg("-q"); @@ -259,8 +202,7 @@ pub(crate) fn apply_patches(dirs: &Dirs, crate_name: &str, source_dir: &Path, ta eprintln!("[COPY] {crate_name} source"); - remove_dir_if_exists(target_dir); - fs::create_dir_all(target_dir).unwrap(); + ensure_empty_dir(target_dir); if crate_name == "stdlib" { fs::create_dir(target_dir.join("library")).unwrap(); copy_dir_recursively(&source_dir.join("library"), &target_dir.join("library")); @@ -285,3 +227,22 @@ pub(crate) fn apply_patches(dirs: &Dirs, crate_name: &str, source_dir: &Path, ta spawn_and_wait(apply_patch_cmd); } } + +#[must_use] +fn git_command<'a>(repo_dir: impl Into>, cmd: &str) -> Command { + let mut git_cmd = Command::new("git"); + git_cmd + .arg("-c") + .arg("user.name=Dummy") + .arg("-c") + .arg("user.email=dummy@example.com") + .arg("-c") + .arg("core.autocrlf=false") + .arg("-c") + .arg("commit.gpgSign=false") + .arg(cmd); + if let Some(repo_dir) = repo_dir.into() { + git_cmd.current_dir(repo_dir); + } + git_cmd +} diff --git a/compiler/rustc_codegen_cranelift/build_system/tests.rs b/compiler/rustc_codegen_cranelift/build_system/tests.rs index 38c3786a94a..fd94e80f631 100644 --- a/compiler/rustc_codegen_cranelift/build_system/tests.rs +++ b/compiler/rustc_codegen_cranelift/build_system/tests.rs @@ -4,11 +4,11 @@ use std::process::Command; use crate::path::{Dirs, RelPath}; -use crate::prepare::{apply_patches, GitRepo}; +use crate::prepare::{GitRepo, apply_patches}; use crate::rustc_info::get_default_sysroot; use crate::shared_utils::rustflags_from_env; -use crate::utils::{spawn_and_wait, CargoProject, Compiler, LogGroup}; -use crate::{build_sysroot, config, CodegenBackend, SysrootKind}; +use crate::utils::{CargoProject, Compiler, LogGroup, spawn_and_wait}; +use crate::{CodegenBackend, SysrootKind, build_sysroot, config}; static BUILD_EXAMPLE_OUT_DIR: RelPath = RelPath::BUILD.join("example"); @@ -117,7 +117,7 @@ const fn jit_bin(config: &'static str, source: &'static str, args: &'static str) "rand", ); -pub(crate) static RAND: CargoProject = CargoProject::new(&RAND_REPO.source_dir(), "rand_target"); +static RAND: CargoProject = CargoProject::new(&RAND_REPO.source_dir(), "rand_target"); pub(crate) static REGEX_REPO: GitRepo = GitRepo::github( "rust-lang", @@ -127,12 +127,11 @@ const fn jit_bin(config: &'static str, source: &'static str, args: &'static str) "regex", ); -pub(crate) static REGEX: CargoProject = CargoProject::new(®EX_REPO.source_dir(), "regex_target"); +static REGEX: CargoProject = CargoProject::new(®EX_REPO.source_dir(), "regex_target"); -pub(crate) static PORTABLE_SIMD_SRC: RelPath = RelPath::BUILD.join("coretests"); +static PORTABLE_SIMD_SRC: RelPath = RelPath::BUILD.join("portable-simd"); -pub(crate) static PORTABLE_SIMD: CargoProject = - CargoProject::new(&PORTABLE_SIMD_SRC, "portable-simd_target"); +static PORTABLE_SIMD: CargoProject = CargoProject::new(&PORTABLE_SIMD_SRC, "portable-simd_target"); static LIBCORE_TESTS_SRC: RelPath = RelPath::BUILD.join("coretests"); @@ -230,13 +229,6 @@ const fn jit_bin(config: &'static str, source: &'static str, args: &'static str) if runner.is_native { let mut test_cmd = PORTABLE_SIMD.test(&runner.target_compiler, &runner.dirs); test_cmd.arg("-q"); - // FIXME remove after portable-simd update - test_cmd - .arg("--") - .arg("--skip") - .arg("core_simd::swizzle::simd_swizzle") - .arg("--skip") - .arg("core_simd::vector::Simd::lanes"); spawn_and_wait(test_cmd); } }), @@ -244,7 +236,6 @@ const fn jit_bin(config: &'static str, source: &'static str, args: &'static str) pub(crate) fn run_tests( dirs: &Dirs, - channel: &str, sysroot_kind: SysrootKind, use_unstable_features: bool, skip_tests: &[&str], @@ -260,7 +251,6 @@ pub(crate) fn run_tests( if config::get_bool("testsuite.no_sysroot") && !skip_tests.contains(&"testsuite.no_sysroot") { let target_compiler = build_sysroot::build_sysroot( dirs, - channel, SysrootKind::None, cg_clif_dylib, bootstrap_host_compiler, @@ -291,7 +281,6 @@ pub(crate) fn run_tests( if run_base_sysroot || run_extended_sysroot { let target_compiler = build_sysroot::build_sysroot( dirs, - channel, sysroot_kind, cg_clif_dylib, bootstrap_host_compiler, @@ -443,7 +432,6 @@ fn rustc_command(&self, args: I) -> Command cmd.arg("--target"); cmd.arg(&self.target_compiler.triple); cmd.arg("-Cpanic=abort"); - cmd.arg("-Zunstable-options"); cmd.arg("--check-cfg=cfg(jit)"); cmd.args(args); cmd @@ -458,26 +446,11 @@ fn run_rustc(&self, args: I) } fn run_out_command(&self, name: &str, args: &[&str]) { - let mut full_cmd = vec![]; + let mut cmd = self + .target_compiler + .run_with_runner(BUILD_EXAMPLE_OUT_DIR.to_path(&self.dirs).join(name)); - // Prepend the RUN_WRAPPER's - if !self.target_compiler.runner.is_empty() { - full_cmd.extend(self.target_compiler.runner.iter().cloned()); - } - - full_cmd.push( - BUILD_EXAMPLE_OUT_DIR.to_path(&self.dirs).join(name).to_str().unwrap().to_string(), - ); - - for arg in args { - full_cmd.push(arg.to_string()); - } - - let mut cmd_iter = full_cmd.into_iter(); - let first = cmd_iter.next().unwrap(); - - let mut cmd = Command::new(first); - cmd.args(cmd_iter); + cmd.args(args); spawn_and_wait(cmd); } diff --git a/compiler/rustc_codegen_cranelift/build_system/usage.txt b/compiler/rustc_codegen_cranelift/build_system/usage.txt index f652599447b..5c333fe2db5 100644 --- a/compiler/rustc_codegen_cranelift/build_system/usage.txt +++ b/compiler/rustc_codegen_cranelift/build_system/usage.txt @@ -2,16 +2,12 @@ The build system of cg_clif. USAGE: ./y.sh prepare [--out-dir DIR] [--download-dir DIR] - ./y.sh build [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--download-dir DIR] [--no-unstable-features] [--frozen] - ./y.sh test [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--download-dir DIR] [--no-unstable-features] [--frozen] [--skip-test TESTNAME] - ./y.sh abi-cafe [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--download-dir DIR] [--no-unstable-features] [--frozen] - ./y.sh bench [--debug] [--sysroot none|clif|llvm] [--out-dir DIR] [--download-dir DIR] [--no-unstable-features] [--frozen] + ./y.sh build [--sysroot none|clif|llvm] [--out-dir DIR] [--download-dir DIR] [--no-unstable-features] [--frozen] + ./y.sh test [--sysroot none|clif|llvm] [--out-dir DIR] [--download-dir DIR] [--no-unstable-features] [--frozen] [--skip-test TESTNAME] + ./y.sh abi-cafe [--sysroot none|clif|llvm] [--out-dir DIR] [--download-dir DIR] [--no-unstable-features] [--frozen] + ./y.sh bench [--sysroot none|clif|llvm] [--out-dir DIR] [--download-dir DIR] [--no-unstable-features] [--frozen] OPTIONS: - --debug - Build cg_clif and the standard library in debug mode rather than release mode. - Warning: An unoptimized cg_clif is very slow. - --sysroot none|clif|llvm Which sysroot libraries to use: `none` will not include any standard library in the sysroot. @@ -43,7 +39,5 @@ REQUIREMENTS: * Rustup: By default rustup is used to install the right nightly version. If you don't want to use rustup, you can manually install the nightly version indicated by rust-toolchain.toml and point the CARGO, RUSTC and RUSTDOC env vars to the right executables. - * Git: Git is used for applying patches and on Windows for downloading test repos. - * Curl and tar (non-Windows only): Used by `./y.sh prepare` to download a single commit for - repos. Git will be used to clone the whole repo when using Windows. + * Git: Git is used for downloading test repos and applying patches. * [Hyperfine](https://github.com/sharkdp/hyperfine/): Used for benchmarking with `./y.sh bench`. diff --git a/compiler/rustc_codegen_cranelift/build_system/utils.rs b/compiler/rustc_codegen_cranelift/build_system/utils.rs index 3c4b45e02cc..22a9487a202 100644 --- a/compiler/rustc_codegen_cranelift/build_system/utils.rs +++ b/compiler/rustc_codegen_cranelift/build_system/utils.rs @@ -1,3 +1,4 @@ +use std::ffi::OsStr; use std::path::{Path, PathBuf}; use std::process::{self, Command}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -59,6 +60,18 @@ pub(crate) fn set_cross_linker_and_runner(&mut self) { } } } + + pub(crate) fn run_with_runner(&self, program: impl AsRef) -> Command { + if self.runner.is_empty() { + Command::new(program) + } else { + let mut runner_iter = self.runner.iter(); + let mut cmd = Command::new(runner_iter.next().unwrap()); + cmd.args(runner_iter); + cmd.arg(program); + cmd + } + } } pub(crate) struct CargoProject { @@ -141,59 +154,6 @@ pub(crate) fn run(&self, compiler: &Compiler, dirs: &Dirs) -> Command { } } -#[must_use] -pub(crate) fn hyperfine_command( - warmup: u64, - runs: u64, - prepare: Option<&str>, - cmds: &[(&str, &str)], - markdown_export: &Path, -) -> Command { - let mut bench = Command::new("hyperfine"); - - bench.arg("--export-markdown").arg(markdown_export); - - if warmup != 0 { - bench.arg("--warmup").arg(warmup.to_string()); - } - - if runs != 0 { - bench.arg("--runs").arg(runs.to_string()); - } - - if let Some(prepare) = prepare { - bench.arg("--prepare").arg(prepare); - } - - for &(name, cmd) in cmds { - if name != "" { - bench.arg("-n").arg(name); - } - bench.arg(cmd); - } - - bench -} - -#[must_use] -pub(crate) fn git_command<'a>(repo_dir: impl Into>, cmd: &str) -> Command { - let mut git_cmd = Command::new("git"); - git_cmd - .arg("-c") - .arg("user.name=Dummy") - .arg("-c") - .arg("user.email=dummy@example.com") - .arg("-c") - .arg("core.autocrlf=false") - .arg("-c") - .arg("commit.gpgSign=false") - .arg(cmd); - if let Some(repo_dir) = repo_dir.into() { - git_cmd.current_dir(repo_dir); - } - git_cmd -} - #[track_caller] pub(crate) fn try_hard_link(src: impl AsRef, dst: impl AsRef) { let src = src.as_ref(); @@ -212,27 +172,33 @@ pub(crate) fn spawn_and_wait(mut cmd: Command) { } } -// Based on the retry function in rust's src/ci/shared.sh -#[track_caller] -pub(crate) fn retry_spawn_and_wait(tries: u64, mut cmd: Command) { - for i in 1..tries + 1 { - if i != 1 { - eprintln!("Command failed. Attempt {i}/{tries}:"); - } - if cmd.spawn().unwrap().wait().unwrap().success() { +/// Create the specified directory if it doesn't exist yet and delete all contents. +pub(crate) fn ensure_empty_dir(path: &Path) { + fs::create_dir_all(path).unwrap(); + let read_dir = match fs::read_dir(&path) { + Ok(read_dir) => read_dir, + Err(err) if err.kind() == io::ErrorKind::NotFound => { return; } - std::thread::sleep(std::time::Duration::from_secs(i * 5)); - } - eprintln!("The command has failed after {tries} attempts."); - process::exit(1); -} - -pub(crate) fn remove_dir_if_exists(path: &Path) { - match fs::remove_dir_all(&path) { - Ok(()) => {} - Err(err) if err.kind() == io::ErrorKind::NotFound => {} - Err(err) => panic!("Failed to remove {path}: {err}", path = path.display()), + Err(err) => { + panic!("Failed to read contents of {path}: {err}", path = path.display()) + } + }; + for entry in read_dir { + let entry = entry.unwrap(); + if entry.file_type().unwrap().is_dir() { + match fs::remove_dir_all(entry.path()) { + Ok(()) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(err) => panic!("Failed to remove {path}: {err}", path = entry.path().display()), + } + } else { + match fs::remove_file(entry.path()) { + Ok(()) => {} + Err(err) if err.kind() == io::ErrorKind::NotFound => {} + Err(err) => panic!("Failed to remove {path}: {err}", path = entry.path().display()), + } + } } } diff --git a/compiler/rustc_codegen_cranelift/clean_all.sh b/compiler/rustc_codegen_cranelift/clean_all.sh index 19405a53d1c..4dbd9dac94a 100755 --- a/compiler/rustc_codegen_cranelift/clean_all.sh +++ b/compiler/rustc_codegen_cranelift/clean_all.sh @@ -1,9 +1,10 @@ -#!/usr/bin/env bash +#!/bin/sh set -e -rm -rf target/ build_system/target download/ build/ dist/ y.bin y.bin.dSYM y.exe y.pdb +rm -rf target/ build_system/target download/ build/ dist/ # Kept for now in case someone updates their checkout of cg_clif before running clean_all.sh # FIXME remove at some point in the future +rm y.bin y.bin.dSYM y.exe y.pdb 2>/dev/null || true rm -rf rand/ regex/ simple-raytracer/ portable-simd/ abi-checker/ abi-cafe/ rm -rf build_sysroot/{sysroot_src/,target/,compiler-builtins/,rustc_version} diff --git a/compiler/rustc_codegen_cranelift/example/neon.rs b/compiler/rustc_codegen_cranelift/example/neon.rs index 00e437d7e54..69ce17d3d75 100644 --- a/compiler/rustc_codegen_cranelift/example/neon.rs +++ b/compiler/rustc_codegen_cranelift/example/neon.rs @@ -202,6 +202,44 @@ unsafe fn test_vqadd_u8() { assert_eq!(r, e); } +#[cfg(target_arch = "aarch64")] +unsafe fn test_vmaxq_f32() { + // AArch64 llvm intrinsic: llvm.aarch64.neon.fmax.v4f32 + let a = f32x4::from([0., -1., 2., -3.]); + let b = f32x4::from([-4., 5., -6., 7.]); + let e = f32x4::from([0., 5., 2., 7.]); + let r: f32x4 = transmute(vmaxq_f32(transmute(a), transmute(b))); + assert_eq!(r, e); +} + +#[cfg(target_arch = "aarch64")] +unsafe fn test_vminq_f32() { + // AArch64 llvm intrinsic: llvm.aarch64.neon.fmin.v4f32 + let a = f32x4::from([0., -1., 2., -3.]); + let b = f32x4::from([-4., 5., -6., 7.]); + let e = f32x4::from([-4., -1., -6., -3.]); + let r: f32x4 = transmute(vminq_f32(transmute(a), transmute(b))); + assert_eq!(r, e); +} + +#[cfg(target_arch = "aarch64")] +unsafe fn test_vaddvq_f32() { + // AArch64 llvm intrinsic: llvm.aarch64.neon.faddv.f32.v4f32 + let a = f32x4::from([0., 1., 2., 3.]); + let e = 6f32; + let r = vaddvq_f32(transmute(a)); + assert_eq!(r, e); +} + +#[cfg(target_arch = "aarch64")] +unsafe fn test_vrndnq_f32() { + // AArch64 llvm intrinsic: llvm.aarch64.neon.frintn.v4f32 + let a = f32x4::from([0.1, -1.9, 4.5, 5.5]); + let e = f32x4::from([0., -2., 4., 6.]); + let r: f32x4 = transmute(vrndnq_f32(transmute(a))); + assert_eq!(r, e); +} + #[cfg(target_arch = "aarch64")] fn main() { unsafe { @@ -229,6 +267,11 @@ fn main() { test_vqsub_u8(); test_vqadd_u8(); + + test_vmaxq_f32(); + test_vminq_f32(); + test_vaddvq_f32(); + test_vrndnq_f32(); } } diff --git a/compiler/rustc_codegen_cranelift/example/std_example.rs b/compiler/rustc_codegen_cranelift/example/std_example.rs index f27d4ef57e0..ebaa9c69c81 100644 --- a/compiler/rustc_codegen_cranelift/example/std_example.rs +++ b/compiler/rustc_codegen_cranelift/example/std_example.rs @@ -238,10 +238,9 @@ 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(); @@ -259,6 +258,9 @@ unsafe fn test_simd() { test_mm_insert_epi16(); test_mm_shuffle_epi8(); + #[cfg(not(jit))] + test_mm_cmpestri(); + test_mm256_shuffle_epi8(); test_mm256_permute2x128_si256(); test_mm256_permutevar8x32_epi32(); @@ -430,6 +432,31 @@ unsafe fn test_mm_shuffle_epi8() { assert_eq_m128i(r, expected); } +// Currently one cannot `load` a &[u8] that is less than 16 +// in length. This makes loading strings less than 16 in length +// a bit difficult. Rather than `load` and mutate the __m128i, +// it is easier to memcpy the given string to a local slice with +// length 16 and `load` the local slice. +#[cfg(not(jit))] +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "sse4.2")] +unsafe fn str_to_m128i(s: &[u8]) -> __m128i { + assert!(s.len() <= 16); + let slice = &mut [0u8; 16]; + std::ptr::copy_nonoverlapping(s.as_ptr(), slice.as_mut_ptr(), s.len()); + _mm_loadu_si128(slice.as_ptr() as *const _) +} + +#[cfg(not(jit))] +#[cfg(target_arch = "x86_64")] +#[target_feature(enable = "sse4.2")] +unsafe fn test_mm_cmpestri() { + let a = str_to_m128i(b"bar - garbage"); + let b = str_to_m128i(b"foobar"); + let i = _mm_cmpestri::<_SIDD_CMP_EQUAL_ORDERED>(a, 3, b, 6); + assert_eq!(3, i); +} + #[cfg(target_arch = "x86_64")] #[target_feature(enable = "avx2")] unsafe fn test_mm256_shuffle_epi8() { diff --git a/compiler/rustc_codegen_cranelift/patches/0001-portable-simd-Disable-broken-reduce_sum-test.patch b/compiler/rustc_codegen_cranelift/patches/0001-portable-simd-Disable-broken-reduce_sum-test.patch new file mode 100644 index 00000000000..b1fd6224632 --- /dev/null +++ b/compiler/rustc_codegen_cranelift/patches/0001-portable-simd-Disable-broken-reduce_sum-test.patch @@ -0,0 +1,26 @@ +From 5489384bc265e9e6fc2efaa63d93a4d51ebec2f5 Mon Sep 17 00:00:00 2001 +From: bjorn3 <17426603+bjorn3@users.noreply.github.com> +Date: Thu, 22 Aug 2024 19:22:58 +0000 +Subject: [PATCH] Disable broken reduce_sum test + +It was broken by an upstream change to the .sum() implementation on +float iterators. +--- + crates/core_simd/tests/ops_macros.rs | 1 + + 1 file changed, 1 insertion(+) + +diff --git a/crates/core_simd/tests/ops_macros.rs b/crates/core_simd/tests/ops_macros.rs +index aa565a1..5e6ac41 100644 +--- a/crates/core_simd/tests/ops_macros.rs ++++ b/crates/core_simd/tests/ops_macros.rs +@@ -646,6 +646,7 @@ macro_rules! impl_float_tests { + } + + fn reduce_sum() { ++ return; + test_helpers::test_1(&|x| { + test_helpers::prop_assert_biteq! ( + Vector::::from_array(x).reduce_sum(), +-- +2.34.1 + diff --git a/compiler/rustc_codegen_cranelift/patches/0022-coretests-Disable-not-compiling-tests.patch b/compiler/rustc_codegen_cranelift/patches/0022-coretests-Disable-not-compiling-tests.patch index 8c404956bcc..5117b04fd34 100644 --- a/compiler/rustc_codegen_cranelift/patches/0022-coretests-Disable-not-compiling-tests.patch +++ b/compiler/rustc_codegen_cranelift/patches/0022-coretests-Disable-not-compiling-tests.patch @@ -38,7 +38,7 @@ index 42a26ae..5ac1042 100644 @@ -1,3 +1,4 @@ +#![cfg(test)] // tidy-alphabetical-start - #![cfg_attr(bootstrap, feature(offset_of_nested))] + #![cfg_attr(bootstrap, feature(const_mut_refs))] #![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] -- 2.21.0 (Apple Git-122) diff --git a/compiler/rustc_codegen_cranelift/patches/0027-coretests-128bit-atomic-operations.patch b/compiler/rustc_codegen_cranelift/patches/0027-coretests-128bit-atomic-operations.patch index d579c9588f0..efd721d9df8 100644 --- a/compiler/rustc_codegen_cranelift/patches/0027-coretests-128bit-atomic-operations.patch +++ b/compiler/rustc_codegen_cranelift/patches/0027-coretests-128bit-atomic-operations.patch @@ -14,14 +14,13 @@ diff --git a/lib.rs b/lib.rs index 1e336bf..35e6f54 100644 --- a/lib.rs +++ b/lib.rs -@@ -1,7 +1,6 @@ +@@ -1,6 +1,5 @@ #![cfg(test)] // tidy-alphabetical-start - #![cfg_attr(bootstrap, feature(offset_of_nested))] + #![cfg_attr(bootstrap, feature(const_mut_refs))] -#![cfg_attr(target_has_atomic = "128", feature(integer_atomics))] #![cfg_attr(test, feature(cfg_match))] #![feature(alloc_layout_extra)] - #![feature(array_chunks)] diff --git a/atomic.rs b/atomic.rs index b735957..ea728b6 100644 --- a/atomic.rs diff --git a/compiler/rustc_codegen_cranelift/patches/0028-coretests-Disable-long-running-tests.patch b/compiler/rustc_codegen_cranelift/patches/0028-coretests-Disable-long-running-tests.patch index 440177018f4..d7204add7a7 100644 --- a/compiler/rustc_codegen_cranelift/patches/0028-coretests-Disable-long-running-tests.patch +++ b/compiler/rustc_codegen_cranelift/patches/0028-coretests-Disable-long-running-tests.patch @@ -43,6 +43,26 @@ index 8402833..84592e0 100644 #[test] fn test_slice_from_ptr_range() { +diff --git a/lazy.rs b/lazy.rs +index 711511e..49c8d78 100644 +--- a/lazy.rs ++++ b/lazy.rs +@@ -113,6 +113,7 @@ fn lazy_type_inference() { + let _ = LazyCell::new(|| ()); + } + ++/* + #[test] + #[should_panic = "LazyCell instance has previously been poisoned"] + fn lazy_force_mut_panic() { +@@ -123,6 +124,7 @@ fn lazy_force_mut_panic() { + .unwrap_err(); + let _ = &*lazy; + } ++*/ + + #[test] + fn lazy_force_mut() { -- 2.26.2.7.g19db9cfb68 diff --git a/compiler/rustc_codegen_cranelift/rust-toolchain b/compiler/rustc_codegen_cranelift/rust-toolchain index 96c467e091c..651770be377 100644 --- a/compiler/rustc_codegen_cranelift/rust-toolchain +++ b/compiler/rustc_codegen_cranelift/rust-toolchain @@ -1,4 +1,4 @@ [toolchain] -channel = "nightly-2024-08-09" +channel = "nightly-2024-09-23" components = ["rust-src", "rustc-dev", "llvm-tools"] profile = "minimal" diff --git a/compiler/rustc_codegen_cranelift/scripts/setup_rust_fork.sh b/compiler/rustc_codegen_cranelift/scripts/setup_rust_fork.sh index 684a5d07293..2f13b0b9cb8 100644 --- a/compiler/rustc_codegen_cranelift/scripts/setup_rust_fork.sh +++ b/compiler/rustc_codegen_cranelift/scripts/setup_rust_fork.sh @@ -25,6 +25,9 @@ git -c user.name=Dummy -c user.email=dummy@example.com -c commit.gpgSign=false \ cat > config.toml <) { + + let is_rustdoc = suite.ends_with("rustdoc-ui") || suite.ends_with("rustdoc-js"); + +- if mode == "run-make" { +- let cargo = builder.ensure(tool::Cargo { compiler, target: compiler.host }); +- cmd.arg("--cargo-path").arg(cargo); +- } +- + // Avoid depending on rustdoc when we don't need it. + if mode == "rustdoc" + || mode == "run-make" +diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs +index 414f9f3a7f1..5c18179b6fe 100644 +--- a/src/tools/compiletest/src/common.rs ++++ b/src/tools/compiletest/src/common.rs +@@ -183,9 +183,6 @@ pub struct Config { + /// The rustc executable. + pub rustc_path: PathBuf, + +- /// The cargo executable. +- pub cargo_path: Option, +- + /// The rustdoc executable. + pub rustdoc_path: Option, + +diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs +index 3339116d542..250b5084d13 100644 +--- a/src/tools/compiletest/src/lib.rs ++++ b/src/tools/compiletest/src/lib.rs +@@ -47,7 +47,6 @@ pub fn parse_config(args: Vec) -> Config { + opts.reqopt("", "compile-lib-path", "path to host shared libraries", "PATH") + .reqopt("", "run-lib-path", "path to target shared libraries", "PATH") + .reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH") +- .optopt("", "cargo-path", "path to cargo to use for compiling", "PATH") + .optopt("", "rustdoc-path", "path to rustdoc to use for compiling", "PATH") + .optopt("", "coverage-dump-path", "path to coverage-dump to use in tests", "PATH") + .reqopt("", "python", "path to python to use for doc tests", "PATH") +@@ -261,7 +260,6 @@ fn make_absolute(path: PathBuf) -> PathBuf { + compile_lib_path: make_absolute(opt_path(matches, "compile-lib-path")), + run_lib_path: make_absolute(opt_path(matches, "run-lib-path")), + rustc_path: opt_path(matches, "rustc-path"), +- cargo_path: matches.opt_str("cargo-path").map(PathBuf::from), + rustdoc_path: matches.opt_str("rustdoc-path").map(PathBuf::from), + coverage_dump_path: matches.opt_str("coverage-dump-path").map(PathBuf::from), + python: matches.opt_str("python").unwrap(), +@@ -366,7 +364,6 @@ pub fn log_config(config: &Config) { + logv(c, format!("compile_lib_path: {:?}", config.compile_lib_path)); + logv(c, format!("run_lib_path: {:?}", config.run_lib_path)); + logv(c, format!("rustc_path: {:?}", config.rustc_path.display())); +- logv(c, format!("cargo_path: {:?}", config.cargo_path)); + logv(c, format!("rustdoc_path: {:?}", config.rustdoc_path)); + logv(c, format!("src_base: {:?}", config.src_base.display())); + logv(c, format!("build_base: {:?}", config.build_base.display())); +diff --git a/src/tools/compiletest/src/runtest/run_make.rs b/src/tools/compiletest/src/runtest/run_make.rs +index 75fe6a6baaf..852568ae925 100644 +--- a/src/tools/compiletest/src/runtest/run_make.rs ++++ b/src/tools/compiletest/src/runtest/run_make.rs +@@ -61,10 +61,6 @@ fn run_rmake_legacy_test(&self) { + .env_remove("MFLAGS") + .env_remove("CARGO_MAKEFLAGS"); + +- if let Some(ref cargo) = self.config.cargo_path { +- cmd.env("CARGO", cwd.join(cargo)); +- } +- + if let Some(ref rustdoc) = self.config.rustdoc_path { + cmd.env("RUSTDOC", cwd.join(rustdoc)); + } +@@ -413,10 +409,6 @@ fn run_rmake_v2_test(&self) { + // through a specific CI runner). + .env("LLVM_COMPONENTS", &self.config.llvm_components); + +- if let Some(ref cargo) = self.config.cargo_path { +- cmd.env("CARGO", source_root.join(cargo)); +- } +- + if let Some(ref rustdoc) = self.config.rustdoc_path { + cmd.env("RUSTDOC", source_root.join(rustdoc)); + } EOF echo "[TEST] rustc test suite" diff --git a/compiler/rustc_codegen_cranelift/src/abi/mod.rs b/compiler/rustc_codegen_cranelift/src/abi/mod.rs index 8838b15d29d..892ec3e9585 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/mod.rs @@ -13,9 +13,9 @@ use rustc_codegen_ssa::base::is_call_from_compiler_builtins_to_upstream_monomorphization; use rustc_codegen_ssa::errors::CompilerBuiltinsCannotCall; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; +use rustc_middle::ty::TypeVisitableExt; use rustc_middle::ty::layout::FnAbiOf; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::TypeVisitableExt; use rustc_session::Session; use rustc_span::source_map::Spanned; use rustc_target::abi::call::{Conv, FnAbi, PassMode}; @@ -508,7 +508,10 @@ enum CallTarget { let nop_inst = fx.bcx.ins().nop(); fx.add_comment( nop_inst, - format!("virtual call; self arg pass mode: {:?}", fn_abi.args[0]), + with_no_trimmed_paths!(format!( + "virtual call; self arg pass mode: {:?}", + fn_abi.args[0] + )), ); } diff --git a/compiler/rustc_codegen_cranelift/src/abi/pass_mode.rs b/compiler/rustc_codegen_cranelift/src/abi/pass_mode.rs index 06522670029..38c322b5e04 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/pass_mode.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/pass_mode.rs @@ -4,7 +4,7 @@ use rustc_target::abi::call::{ ArgAbi, ArgAttributes, ArgExtension as RustcArgExtension, CastTarget, PassMode, Reg, RegKind, }; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use crate::prelude::*; use crate::value_and_place::assert_assignable; diff --git a/compiler/rustc_codegen_cranelift/src/abi/returning.rs b/compiler/rustc_codegen_cranelift/src/abi/returning.rs index e0f399e616e..a294c789b22 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/returning.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/returning.rs @@ -1,7 +1,7 @@ //! Return value handling use rustc_target::abi::call::{ArgAbi, PassMode}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use crate::prelude::*; diff --git a/compiler/rustc_codegen_cranelift/src/allocator.rs b/compiler/rustc_codegen_cranelift/src/allocator.rs index b4a3825e996..5e33b9d606f 100644 --- a/compiler/rustc_codegen_cranelift/src/allocator.rs +++ b/compiler/rustc_codegen_cranelift/src/allocator.rs @@ -2,8 +2,8 @@ // Adapted from rustc use rustc_ast::expand::allocator::{ - alloc_error_handler_name, default_fn_name, global_fn_name, AllocatorKind, AllocatorTy, - ALLOCATOR_METHODS, NO_ALLOC_SHIM_IS_UNSTABLE, + ALLOCATOR_METHODS, AllocatorKind, AllocatorTy, NO_ALLOC_SHIM_IS_UNSTABLE, + alloc_error_handler_name, default_fn_name, global_fn_name, }; use rustc_codegen_ssa::base::allocator_kind_for_codegen; use rustc_session::config::OomStrategy; diff --git a/compiler/rustc_codegen_cranelift/src/base.rs b/compiler/rustc_codegen_cranelift/src/base.rs index 8839829e2f5..dc342e151f3 100644 --- a/compiler/rustc_codegen_cranelift/src/base.rs +++ b/compiler/rustc_codegen_cranelift/src/base.rs @@ -1,17 +1,17 @@ //! Codegen of a single function -use cranelift_codegen::ir::UserFuncName; use cranelift_codegen::CodegenError; +use cranelift_codegen::ir::UserFuncName; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use cranelift_module::ModuleError; use rustc_ast::InlineAsmOptions; use rustc_codegen_ssa::base::is_call_from_compiler_builtins_to_upstream_monomorphization; use rustc_index::IndexVec; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; +use rustc_middle::ty::TypeVisitableExt; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::layout::FnAbiOf; use rustc_middle::ty::print::with_no_trimmed_paths; -use rustc_middle::ty::TypeVisitableExt; use crate::constant::ConstantCx; use crate::debuginfo::{FunctionDebugContext, TypeDebugContext}; diff --git a/compiler/rustc_codegen_cranelift/src/common.rs b/compiler/rustc_codegen_cranelift/src/common.rs index 22ca2070715..e78ba5a3415 100644 --- a/compiler/rustc_codegen_cranelift/src/common.rs +++ b/compiler/rustc_codegen_cranelift/src/common.rs @@ -1,10 +1,10 @@ use cranelift_codegen::isa::TargetFrontendConfig; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use rustc_index::IndexVec; +use rustc_middle::ty::TypeFoldable; use rustc_middle::ty::layout::{ self, FnAbiError, FnAbiOfHelpers, FnAbiRequest, LayoutError, LayoutOfHelpers, }; -use rustc_middle::ty::TypeFoldable; use rustc_span::source_map::Spanned; use rustc_target::abi::call::FnAbi; use rustc_target::abi::{Float, Integer, Primitive}; diff --git a/compiler/rustc_codegen_cranelift/src/constant.rs b/compiler/rustc_codegen_cranelift/src/constant.rs index 0ba163f50ae..6ba6a64c544 100644 --- a/compiler/rustc_codegen_cranelift/src/constant.rs +++ b/compiler/rustc_codegen_cranelift/src/constant.rs @@ -5,7 +5,7 @@ use cranelift_module::*; use rustc_data_structures::fx::FxHashSet; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use rustc_middle::mir::interpret::{read_target_uint, AllocId, GlobalAlloc, Scalar}; +use rustc_middle::mir::interpret::{AllocId, GlobalAlloc, Scalar, read_target_uint}; use rustc_middle::ty::{Binder, ExistentialTraitRef, ScalarInt}; use crate::prelude::*; @@ -490,6 +490,11 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant } /// Used only for intrinsic implementations that need a compile-time constant +/// +/// All uses of this function are a bug inside stdarch. [`eval_mir_constant`] +/// should be used everywhere, but for some vendor intrinsics stdarch forgets +/// to wrap the immediate argument in `const {}`, necesitating this hack to get +/// the correct value at compile time instead. pub(crate) fn mir_operand_get_const_val<'tcx>( fx: &FunctionCx<'_, '_, 'tcx>, operand: &Operand<'tcx>, diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/emit.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/emit.rs index 36af7d4450d..ccdc347af66 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/emit.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/emit.rs @@ -6,8 +6,8 @@ use gimli::{RunTimeEndian, SectionId}; use rustc_data_structures::fx::FxHashMap; -use super::object::WriteDebugInfo; use super::DebugContext; +use super::object::WriteDebugInfo; pub(super) fn address_for_func(func_id: FuncId) -> Address { let symbol = func_id.as_u32(); diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs index 78b3d5a58f4..c3d9d635084 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/line_info.rs @@ -3,15 +3,15 @@ use std::ffi::OsStr; use std::path::{Component, Path}; -use cranelift_codegen::binemit::CodeOffset; use cranelift_codegen::MachSrcLoc; +use cranelift_codegen::binemit::CodeOffset; use gimli::write::{AttributeValue, FileId, FileInfo, LineProgram, LineString, LineStringTable}; use rustc_span::{ - hygiene, FileName, Pos, SourceFile, SourceFileAndLine, SourceFileHash, SourceFileHashAlgorithm, + FileName, Pos, SourceFile, SourceFileAndLine, SourceFileHash, SourceFileHashAlgorithm, hygiene, }; -use crate::debuginfo::emit::address_for_func; use crate::debuginfo::FunctionDebugContext; +use crate::debuginfo::emit::address_for_func; use crate::prelude::*; // OPTIMIZATION: It is cheaper to do this in one pass than using `.parent()` and `.file_name()`. diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs index 1c6e471cc87..048a388731f 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs @@ -73,19 +73,16 @@ fn add_debug_reloc( } }; 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, - }, - addend: i64::try_from(symbol_offset).unwrap() + reloc.addend, + .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, + }) .unwrap(); } } diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/types.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/types.rs index 8a55a23128d..a710701e72c 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/types.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/types.rs @@ -6,7 +6,7 @@ use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, Ty, TyCtxt}; -use crate::{has_ptr_meta, DebugContext, RevealAllLayoutCx}; +use crate::{DebugContext, RevealAllLayoutCx, has_ptr_meta}; #[derive(Default)] pub(crate) struct TypeDebugContext<'tcx> { diff --git a/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs b/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs index ac7dd0bd463..9399230f292 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/unwind.rs @@ -1,11 +1,11 @@ //! Unwind info generation (`.eh_frame`) use cranelift_codegen::ir::Endianness; -use cranelift_codegen::isa::unwind::UnwindInfo; use cranelift_codegen::isa::TargetIsa; +use cranelift_codegen::isa::unwind::UnwindInfo; use cranelift_object::ObjectProduct; -use gimli::write::{CieId, EhFrame, FrameTable, Section}; use gimli::RunTimeEndian; +use gimli::write::{CieId, EhFrame, FrameTable, Section}; use super::emit::address_for_func; use super::object::WriteDebugInfo; diff --git a/compiler/rustc_codegen_cranelift/src/driver/aot.rs b/compiler/rustc_codegen_cranelift/src/driver/aot.rs index b6fee1bf24a..419efa90600 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/aot.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/aot.rs @@ -12,24 +12,24 @@ use rustc_codegen_ssa::back::metadata::create_compressed_metadata_file; use rustc_codegen_ssa::base::determine_cgu_reuse; use rustc_codegen_ssa::{ - errors as ssa_errors, CodegenResults, CompiledModule, CrateInfo, ModuleKind, + CodegenResults, CompiledModule, CrateInfo, ModuleKind, errors as ssa_errors, }; use rustc_data_structures::profiling::SelfProfilerRef; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_data_structures::sync::{par_map, IntoDynSyncSend}; -use rustc_metadata::fs::copy_to_stdout; +use rustc_data_structures::sync::{IntoDynSyncSend, par_map}; use rustc_metadata::EncodedMetadata; +use rustc_metadata::fs::copy_to_stdout; use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; use rustc_middle::mir::mono::{CodegenUnit, MonoItem}; -use rustc_session::config::{DebugInfo, OutFileName, OutputFilenames, OutputType}; use rustc_session::Session; +use rustc_session::config::{DebugInfo, OutFileName, OutputFilenames, OutputType}; +use crate::BackendConfig; use crate::concurrency_limiter::{ConcurrencyLimiter, ConcurrencyLimiterToken}; use crate::debuginfo::TypeDebugContext; use crate::global_asm::GlobalAsmConfig; use crate::prelude::*; use crate::unwind_module::UnwindModule; -use crate::BackendConfig; struct ModuleCodegenResult { module_regular: CompiledModule, diff --git a/compiler/rustc_codegen_cranelift/src/driver/jit.rs b/compiler/rustc_codegen_cranelift/src/driver/jit.rs index 12e860f676d..0d62a13b472 100644 --- a/compiler/rustc_codegen_cranelift/src/driver/jit.rs +++ b/compiler/rustc_codegen_cranelift/src/driver/jit.rs @@ -4,7 +4,7 @@ use std::cell::RefCell; use std::ffi::CString; use std::os::raw::{c_char, c_int}; -use std::sync::{mpsc, Mutex, OnceLock}; +use std::sync::{Mutex, OnceLock, mpsc}; use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use cranelift_jit::{JITBuilder, JITModule}; @@ -359,15 +359,11 @@ 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 16edec47e10..41f1b30d10b 100644 --- a/compiler/rustc_codegen_cranelift/src/inline_asm.rs +++ b/compiler/rustc_codegen_cranelift/src/inline_asm.rs @@ -869,15 +869,11 @@ 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/llvm_aarch64.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs index f0fb18608e0..39f6763d9f2 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_aarch64.rs @@ -91,6 +91,44 @@ pub(crate) fn codegen_aarch64_llvm_intrinsic_call<'tcx>( ); } + _ if intrinsic.starts_with("llvm.aarch64.neon.fmax.v") => { + intrinsic_args!(fx, args => (x, y); intrinsic); + + simd_pair_for_each_lane( + fx, + x, + y, + ret, + &|fx, _lane_ty, _res_lane_ty, x_lane, y_lane| fx.bcx.ins().fmax(x_lane, y_lane), + ); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.fmin.v") => { + intrinsic_args!(fx, args => (x, y); intrinsic); + + simd_pair_for_each_lane( + fx, + x, + y, + ret, + &|fx, _lane_ty, _res_lane_ty, x_lane, y_lane| fx.bcx.ins().fmin(x_lane, y_lane), + ); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.faddv.f32.v") => { + intrinsic_args!(fx, args => (v); intrinsic); + + simd_reduce(fx, v, None, ret, &|fx, _ty, a, b| fx.bcx.ins().fadd(a, b)); + } + + _ if intrinsic.starts_with("llvm.aarch64.neon.frintn.v") => { + intrinsic_args!(fx, args => (v); intrinsic); + + simd_for_each_lane(fx, v, ret, &|fx, _lane_ty, _res_lane_ty, lane| { + fx.bcx.ins().nearest(lane) + }); + } + _ if intrinsic.starts_with("llvm.aarch64.neon.smaxv.i") => { intrinsic_args!(fx, args => (v); intrinsic); diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs index cb003037c26..c02d31844e0 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/llvm_x86.rs @@ -3,7 +3,7 @@ use rustc_ast::ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_target::asm::*; -use crate::inline_asm::{codegen_inline_asm_inner, CInlineAsmOperand}; +use crate::inline_asm::{CInlineAsmOperand, codegen_inline_asm_inner}; use crate::intrinsics::*; use crate::prelude::*; diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index 29deac60730..19e5adc2538 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -19,11 +19,11 @@ macro_rules! intrinsic_args { use cranelift_codegen::ir::AtomicRmwOp; use rustc_middle::ty; +use rustc_middle::ty::GenericArgsRef; use rustc_middle::ty::layout::{HasParamEnv, ValidityRequirement}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; -use rustc_middle::ty::GenericArgsRef; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; pub(crate) use self::llvm::codegen_llvm_intrinsic_call; use crate::cast::clif_intcast; @@ -600,9 +600,11 @@ fn codegen_regular_intrinsic_call<'tcx>( sym::ptr_mask => { intrinsic_args!(fx, args => (ptr, mask); intrinsic); + let ptr_layout = ptr.layout(); let ptr = ptr.load_scalar(fx); let mask = mask.load_scalar(fx); - fx.bcx.ins().band(ptr, mask); + let res = fx.bcx.ins().band(ptr, mask); + ret.write_cvalue(fx, CValue::by_val(res, ptr_layout)); } sym::write_bytes | sym::volatile_set_memory => { diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs index b96abb14b2e..cbe411d78d5 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs @@ -181,11 +181,9 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( // Make sure this is actually a SIMD vector. let idx_ty = fx.monomorphize(idx.node.ty(fx.mir, fx.tcx)); - let n: u16 = if idx_ty.is_simd() - && matches!(idx_ty.simd_size_and_type(fx.tcx).1.kind(), ty::Uint(ty::UintTy::U32)) + if !idx_ty.is_simd() + || !matches!(idx_ty.simd_size_and_type(fx.tcx).1.kind(), ty::Uint(ty::UintTy::U32)) { - idx_ty.simd_size_and_type(fx.tcx).0.try_into().unwrap() - } else { fx.tcx.dcx().span_err( span, format!("simd_shuffle index must be a SIMD vector of `u32`, got `{}`", idx_ty), @@ -194,6 +192,7 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( fx.bcx.ins().trap(TrapCode::UnreachableCodeReached); return; }; + let n: u16 = idx_ty.simd_size_and_type(fx.tcx).0.try_into().unwrap(); assert_eq!(x.layout(), y.layout()); let layout = x.layout(); @@ -268,10 +267,8 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( let val = codegen_operand(fx, &val.node); // FIXME validate - let idx_const = if let Some(idx_const) = - crate::constant::mir_operand_get_const_val(fx, &idx.node) - { - idx_const + let idx_const = if let Some(idx_const) = idx.node.constant() { + crate::constant::eval_mir_constant(fx, idx_const).0.try_to_scalar_int().unwrap() } else { fx.tcx.dcx().span_fatal(span, "Index argument for `simd_insert` is not a constant"); }; @@ -304,22 +301,12 @@ pub(super) fn codegen_simd_intrinsic_call<'tcx>( return; } - let idx_const = if let Some(idx_const) = - crate::constant::mir_operand_get_const_val(fx, &idx.node) - { - idx_const + let idx_const = if let Some(idx_const) = idx.node.constant() { + crate::constant::eval_mir_constant(fx, idx_const).0.try_to_scalar_int().unwrap() } else { - fx.tcx.dcx().span_warn(span, "Index argument for `simd_extract` is not a constant"); - let trap_block = fx.bcx.create_block(); - let true_ = fx.bcx.ins().iconst(types::I8, 1); - let ret_block = fx.get_block(target); - fx.bcx.ins().brif(true_, trap_block, &[], ret_block, &[]); - fx.bcx.switch_to_block(trap_block); - crate::trap::trap_unimplemented( - fx, - "Index argument for `simd_extract` is not a constant", - ); - return; + fx.tcx + .dcx() + .span_fatal(span, "Index argument for `simd_extract` is not a constant"); }; let idx = idx_const.to_u32(); @@ -574,12 +561,9 @@ 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/lib.rs b/compiler/rustc_codegen_cranelift/src/lib.rs index f737af25b62..f6b7981395a 100644 --- a/compiler/rustc_codegen_cranelift/src/lib.rs +++ b/compiler/rustc_codegen_cranelift/src/lib.rs @@ -38,15 +38,15 @@ use cranelift_codegen::isa::TargetIsa; use cranelift_codegen::settings::{self, Configurable}; -use rustc_codegen_ssa::traits::CodegenBackend; use rustc_codegen_ssa::CodegenResults; +use rustc_codegen_ssa::traits::CodegenBackend; use rustc_data_structures::profiling::SelfProfilerRef; use rustc_errors::ErrorGuaranteed; use rustc_metadata::EncodedMetadata; use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; -use rustc_session::config::OutputFilenames; use rustc_session::Session; -use rustc_span::{sym, Symbol}; +use rustc_session::config::OutputFilenames; +use rustc_span::{Symbol, sym}; pub use crate::config::*; use crate::prelude::*; @@ -83,13 +83,13 @@ mod vtable; mod prelude { + pub(crate) use cranelift_codegen::Context; pub(crate) use cranelift_codegen::ir::condcodes::{FloatCC, IntCC}; pub(crate) use cranelift_codegen::ir::function::Function; pub(crate) use cranelift_codegen::ir::{ - types, AbiParam, Block, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc, - StackSlot, StackSlotData, StackSlotKind, TrapCode, Type, Value, + AbiParam, Block, FuncRef, Inst, InstBuilder, MemFlags, Signature, SourceLoc, StackSlot, + StackSlotData, StackSlotKind, TrapCode, Type, Value, types, }; - pub(crate) use cranelift_codegen::Context; pub(crate) use cranelift_module::{self, DataDescription, FuncId, Linkage, Module}; pub(crate) use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; pub(crate) use rustc_hir::def_id::{DefId, LOCAL_CRATE}; @@ -100,7 +100,7 @@ mod prelude { self, FloatTy, Instance, InstanceKind, IntTy, ParamEnv, Ty, TyCtxt, UintTy, }; pub(crate) use rustc_span::Span; - pub(crate) use rustc_target::abi::{Abi, FieldIdx, Scalar, Size, VariantIdx, FIRST_VARIANT}; + pub(crate) use rustc_target::abi::{Abi, FIRST_VARIANT, FieldIdx, Scalar, Size, VariantIdx}; pub(crate) use crate::abi::*; pub(crate) use crate::base::{codegen_operand, codegen_place}; diff --git a/compiler/rustc_codegen_cranelift/src/main_shim.rs b/compiler/rustc_codegen_cranelift/src/main_shim.rs index ba20a750d2b..df92bc58bf5 100644 --- a/compiler/rustc_codegen_cranelift/src/main_shim.rs +++ b/compiler/rustc_codegen_cranelift/src/main_shim.rs @@ -1,9 +1,9 @@ use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext}; use rustc_hir::LangItem; use rustc_middle::ty::{AssocKind, GenericArg}; -use rustc_session::config::{sigpipe, EntryFnType}; -use rustc_span::symbol::Ident; +use rustc_session::config::{EntryFnType, sigpipe}; use rustc_span::DUMMY_SP; +use rustc_span::symbol::Ident; use crate::prelude::*; @@ -16,13 +16,10 @@ pub(crate) fn maybe_create_entry_wrapper( is_primary_cgu: bool, ) { let (main_def_id, (is_main_fn, sigpipe)) = match tcx.entry_fn(()) { - Some((def_id, entry_ty)) => ( - def_id, - match entry_ty { - EntryFnType::Main { sigpipe } => (true, sigpipe), - EntryFnType::Start => (false, sigpipe::DEFAULT), - }, - ), + Some((def_id, entry_ty)) => (def_id, match entry_ty { + EntryFnType::Main { sigpipe } => (true, sigpipe), + EntryFnType::Start => (false, sigpipe::DEFAULT), + }), None => return, }; diff --git a/compiler/rustc_codegen_cranelift/src/pretty_clif.rs b/compiler/rustc_codegen_cranelift/src/pretty_clif.rs index 196418023d9..13877b3b1e9 100644 --- a/compiler/rustc_codegen_cranelift/src/pretty_clif.rs +++ b/compiler/rustc_codegen_cranelift/src/pretty_clif.rs @@ -59,8 +59,8 @@ use std::io::Write; use cranelift_codegen::entity::SecondaryMap; -use cranelift_codegen::ir::entities::AnyEntity; use cranelift_codegen::ir::Fact; +use cranelift_codegen::ir::entities::AnyEntity; use cranelift_codegen::write::{FuncWriter, PlainWriter}; use rustc_middle::ty::layout::FnAbiOf; use rustc_middle::ty::print::with_no_trimmed_paths; diff --git a/compiler/rustc_codegen_cranelift/src/trap.rs b/compiler/rustc_codegen_cranelift/src/trap.rs index 2fb0c2164c3..a61e1e334ec 100644 --- a/compiler/rustc_codegen_cranelift/src/trap.rs +++ b/compiler/rustc_codegen_cranelift/src/trap.rs @@ -5,15 +5,11 @@ 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_cranelift/test.sh b/compiler/rustc_codegen_cranelift/test.sh index 6357eebf026..6c07c512ef2 100755 --- a/compiler/rustc_codegen_cranelift/test.sh +++ b/compiler/rustc_codegen_cranelift/test.sh @@ -1,2 +1,2 @@ -#!/usr/bin/env bash +#!/bin/sh exec ./y.sh test "$@" diff --git a/compiler/rustc_codegen_cranelift/y.sh b/compiler/rustc_codegen_cranelift/y.sh index b9152d2cc6d..a70d457341b 100755 --- a/compiler/rustc_codegen_cranelift/y.sh +++ b/compiler/rustc_codegen_cranelift/y.sh @@ -1,4 +1,4 @@ -#!/usr/bin/env bash +#!/bin/sh set -e echo "[BUILD] build system" 1>&2 diff --git a/compiler/rustc_codegen_gcc/build_system/src/config.rs b/compiler/rustc_codegen_gcc/build_system/src/config.rs index 15ba1612167..a7980dec83b 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/config.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/config.rs @@ -3,8 +3,8 @@ use std::path::{Path, PathBuf}; use std::{env as std_env, fs}; -use boml::types::TomlValue; use boml::Toml; +use boml::types::TomlValue; use crate::utils::{ create_dir, create_symlink, get_os_name, get_sysroot_dir, run_command_with_output, diff --git a/compiler/rustc_codegen_gcc/build_system/src/test.rs b/compiler/rustc_codegen_gcc/build_system/src/test.rs index 83fa8059b1a..50e27736aac 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/test.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/test.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; use std::ffi::OsStr; -use std::fs::{remove_dir_all, File}; +use std::fs::{File, remove_dir_all}; use std::io::{BufRead, BufReader}; use std::path::{Path, PathBuf}; use std::str::FromStr; diff --git a/compiler/rustc_codegen_gcc/build_system/src/utils.rs b/compiler/rustc_codegen_gcc/build_system/src/utils.rs index e338d1b4992..401c23948e5 100644 --- a/compiler/rustc_codegen_gcc/build_system/src/utils.rs +++ b/compiler/rustc_codegen_gcc/build_system/src/utils.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; +use std::ffi::OsStr; #[cfg(unix)] use std::ffi::c_int; -use std::ffi::OsStr; use std::fmt::Debug; use std::fs; #[cfg(unix)] diff --git a/compiler/rustc_codegen_gcc/src/abi.rs b/compiler/rustc_codegen_gcc/src/abi.rs index ed78d4ef19f..14fc23593f0 100644 --- a/compiler/rustc_codegen_gcc/src/abi.rs +++ b/compiler/rustc_codegen_gcc/src/abi.rs @@ -4,8 +4,8 @@ use rustc_codegen_ssa::traits::{AbiBuilderMethods, BaseTypeCodegenMethods}; use rustc_data_structures::fx::FxHashSet; use rustc_middle::bug; -use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::Ty; +use rustc_middle::ty::layout::LayoutOf; #[cfg(feature = "master")] use rustc_session::config; use rustc_target::abi::call::{ArgAttributes, CastTarget, FnAbi, PassMode, Reg, RegKind}; diff --git a/compiler/rustc_codegen_gcc/src/allocator.rs b/compiler/rustc_codegen_gcc/src/allocator.rs index deeb55e9d12..e9498857fb9 100644 --- a/compiler/rustc_codegen_gcc/src/allocator.rs +++ b/compiler/rustc_codegen_gcc/src/allocator.rs @@ -2,8 +2,8 @@ use gccjit::FnAttribute; use gccjit::{Context, FunctionType, GlobalKind, ToRValue, Type}; use rustc_ast::expand::allocator::{ - alloc_error_handler_name, default_fn_name, global_fn_name, AllocatorKind, AllocatorTy, - ALLOCATOR_METHODS, NO_ALLOC_SHIM_IS_UNSTABLE, + ALLOCATOR_METHODS, AllocatorKind, AllocatorTy, NO_ALLOC_SHIM_IS_UNSTABLE, + alloc_error_handler_name, default_fn_name, global_fn_name, }; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; diff --git a/compiler/rustc_codegen_gcc/src/back/lto.rs b/compiler/rustc_codegen_gcc/src/back/lto.rs index c2adab7137f..ed92f9c5241 100644 --- a/compiler/rustc_codegen_gcc/src/back/lto.rs +++ b/compiler/rustc_codegen_gcc/src/back/lto.rs @@ -27,7 +27,7 @@ use rustc_codegen_ssa::back::symbol_export; use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput}; use rustc_codegen_ssa::traits::*; -use rustc_codegen_ssa::{looks_like_rust_object_file, ModuleCodegen, ModuleKind}; +use rustc_codegen_ssa::{ModuleCodegen, ModuleKind, looks_like_rust_object_file}; use rustc_data_structures::memmap::Mmap; use rustc_errors::{DiagCtxtHandle, FatalError}; use rustc_hir::def_id::LOCAL_CRATE; @@ -35,11 +35,11 @@ use rustc_middle::dep_graph::WorkProduct; use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel}; use rustc_session::config::{CrateType, Lto}; -use tempfile::{tempdir, TempDir}; +use tempfile::{TempDir, tempdir}; use crate::back::write::save_temp_bitcode; use crate::errors::{DynamicLinkingWithLTO, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib}; -use crate::{to_gcc_opt_level, GccCodegenBackend, GccContext, SyncContext}; +use crate::{GccCodegenBackend, GccContext, SyncContext, to_gcc_opt_level}; /// We keep track of the computed LTO cache keys from the previous /// session to determine which CGUs we can reuse. diff --git a/compiler/rustc_codegen_gcc/src/base.rs b/compiler/rustc_codegen_gcc/src/base.rs index c0443faf24a..9836e654f37 100644 --- a/compiler/rustc_codegen_gcc/src/base.rs +++ b/compiler/rustc_codegen_gcc/src/base.rs @@ -19,7 +19,7 @@ use crate::builder::Builder; use crate::context::CodegenCx; -use crate::{gcc_util, new_context, GccContext, LockedTargetInfo, SyncContext}; +use crate::{GccContext, LockedTargetInfo, SyncContext, gcc_util, new_context}; #[cfg(feature = "master")] pub fn visibility_to_gcc(linkage: Visibility) -> gccjit::Visibility { diff --git a/compiler/rustc_codegen_gcc/src/builder.rs b/compiler/rustc_codegen_gcc/src/builder.rs index 9282d8699eb..2b5c39a4d16 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -7,7 +7,8 @@ BinaryOp, Block, ComparisonOp, Context, Function, LValue, Location, RValue, ToRValue, Type, UnaryOp, }; -use rustc_apfloat::{ieee, Float, Round, Status}; +use rustc_apfloat::{Float, Round, Status, ieee}; +use rustc_codegen_ssa::MemFlags; use rustc_codegen_ssa::common::{ AtomicOrdering, AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope, TypeKind, }; @@ -17,7 +18,6 @@ BackendTypes, BaseTypeCodegenMethods, BuilderMethods, ConstCodegenMethods, LayoutTypeCodegenMethods, OverflowOp, StaticBuilderMethods, }; -use rustc_codegen_ssa::MemFlags; use rustc_data_structures::fx::FxHashSet; use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; @@ -25,13 +25,13 @@ FnAbiError, FnAbiOfHelpers, FnAbiRequest, HasParamEnv, HasTyCtxt, LayoutError, LayoutOfHelpers, }; use rustc_middle::ty::{Instance, ParamEnv, Ty, TyCtxt}; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; use rustc_target::abi::call::FnAbi; use rustc_target::abi::{self, Align, HasDataLayout, Size, TargetDataLayout, WrappingRange}; use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, Target, WasmCAbi}; -use crate::common::{type_is_pointer, SignType, TypeReflection}; +use crate::common::{SignType, TypeReflection, type_is_pointer}; use crate::context::CodegenCx; use crate::intrinsic::llvm; use crate::type_of::LayoutGccExt; @@ -152,11 +152,14 @@ fn compare_exchange( // 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>) { @@ -1079,11 +1082,9 @@ fn write_operand_repeatedly( 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/common.rs b/compiler/rustc_codegen_gcc/src/common.rs index b7ed34858b5..c7cf73f1992 100644 --- a/compiler/rustc_codegen_gcc/src/common.rs +++ b/compiler/rustc_codegen_gcc/src/common.rs @@ -2,8 +2,8 @@ use rustc_codegen_ssa::traits::{ BaseTypeCodegenMethods, ConstCodegenMethods, MiscCodegenMethods, StaticCodegenMethods, }; -use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar}; use rustc_middle::mir::Mutability; +use rustc_middle::mir::interpret::{ConstAllocation, GlobalAlloc, Scalar}; use rustc_middle::ty::layout::LayoutOf; use rustc_target::abi::{self, HasDataLayout, Pointer}; diff --git a/compiler/rustc_codegen_gcc/src/consts.rs b/compiler/rustc_codegen_gcc/src/consts.rs index 68b9df946d0..5ad5117d7fd 100644 --- a/compiler/rustc_codegen_gcc/src/consts.rs +++ b/compiler/rustc_codegen_gcc/src/consts.rs @@ -7,7 +7,7 @@ use rustc_hir::def::DefKind; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}; use rustc_middle::mir::interpret::{ - self, read_target_uint, ConstAllocation, ErrorHandled, Scalar as InterpScalar, + self, ConstAllocation, ErrorHandled, Scalar as InterpScalar, read_target_uint, }; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, Instance}; diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index 8e1a5b61285..6542677af67 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -6,7 +6,7 @@ use rustc_codegen_ssa::base::wants_msvc_seh; use rustc_codegen_ssa::errors as ssa_errors; use rustc_codegen_ssa::traits::{BackendTypes, BaseTypeCodegenMethods, MiscCodegenMethods}; -use rustc_data_structures::base_n::{ToBaseN, ALPHANUMERIC_ONLY}; +use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, ToBaseN}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_middle::mir::mono::CodegenUnit; use rustc_middle::span_bug; @@ -17,7 +17,7 @@ use rustc_middle::ty::{self, Instance, ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt}; use rustc_session::Session; use rustc_span::source_map::respan; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi::{HasDataLayout, PointeeInfo, Size, TargetDataLayout, VariantIdx}; use rustc_target::spec::{HasTargetSpec, HasWasmCAbiOpt, Target, TlsModel, WasmCAbi}; diff --git a/compiler/rustc_codegen_gcc/src/debuginfo.rs b/compiler/rustc_codegen_gcc/src/debuginfo.rs index 1d859656b3e..271d65a8235 100644 --- a/compiler/rustc_codegen_gcc/src/debuginfo.rs +++ b/compiler/rustc_codegen_gcc/src/debuginfo.rs @@ -10,8 +10,8 @@ use rustc_middle::ty::{Instance, PolyExistentialTraitRef, Ty}; use rustc_session::config::DebugInfo; use rustc_span::{BytePos, Pos, SourceFile, SourceFileAndLine, Span, Symbol}; -use rustc_target::abi::call::FnAbi; use rustc_target::abi::Size; +use rustc_target::abi::call::FnAbi; use crate::builder::Builder; use crate::context::CodegenCx; diff --git a/compiler/rustc_codegen_gcc/src/gcc_util.rs b/compiler/rustc_codegen_gcc/src/gcc_util.rs index 5308ccdb614..01dd1a8856a 100644 --- a/compiler/rustc_codegen_gcc/src/gcc_util.rs +++ b/compiler/rustc_codegen_gcc/src/gcc_util.rs @@ -4,7 +4,7 @@ use rustc_middle::bug; use rustc_session::Session; use rustc_target::target_features::RUSTC_SPECIFIC_FEATURES; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use crate::errors::{ PossibleFeature, TargetFeatureDisableOrEnable, UnknownCTargetFeature, diff --git a/compiler/rustc_codegen_gcc/src/int.rs b/compiler/rustc_codegen_gcc/src/int.rs index 29f4db6738b..abb473a830c 100644 --- a/compiler/rustc_codegen_gcc/src/int.rs +++ b/compiler/rustc_codegen_gcc/src/int.rs @@ -6,8 +6,8 @@ use rustc_codegen_ssa::common::{IntPredicate, TypeKind}; use rustc_codegen_ssa::traits::{BackendTypes, BaseTypeCodegenMethods, BuilderMethods, OverflowOp}; use rustc_middle::ty::{ParamEnv, Ty}; -use rustc_target::abi::call::{ArgAbi, ArgAttributes, Conv, FnAbi, PassMode}; use rustc_target::abi::Endian; +use rustc_target::abi::call::{ArgAbi, ArgAttributes, Conv, FnAbi, PassMode}; use rustc_target::spec; use crate::builder::{Builder, ToGccComp}; @@ -395,11 +395,9 @@ pub fn operation_with_overflow( let indirect = matches!(fn_abi.ret.mode, PassMode::Indirect { .. }); - let return_type = self.context.new_struct_type( - self.location, - "result_overflow", - &[result_field, overflow_field], - ); + let return_type = self + .context + .new_struct_type(self.location, "result_overflow", &[result_field, overflow_field]); let result = if indirect { let return_value = self.current_func().new_local(self.location, return_type.as_type(), "return_value"); @@ -416,11 +414,11 @@ pub fn operation_with_overflow( ); self.llbb().add_eval( self.location, - self.context.new_call( - self.location, - func, - &[return_value.get_address(self.location), lhs, rhs], - ), + self.context.new_call(self.location, func, &[ + return_value.get_address(self.location), + lhs, + rhs, + ]), ); return_value.to_rvalue() } else { diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs b/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs index 554e57250e6..48f96df61e9 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/llvm.rs @@ -511,12 +511,11 @@ 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" => { @@ -541,12 +540,11 @@ 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(), + ]); } _ => (), } diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index 4fd033255fe..753c3a3dfa6 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -7,6 +7,7 @@ #[cfg(feature = "master")] use gccjit::FunctionType; use gccjit::{ComparisonOp, Function, RValue, ToRValue, Type, UnaryOp}; +use rustc_codegen_ssa::MemFlags; use rustc_codegen_ssa::base::wants_msvc_seh; use rustc_codegen_ssa::common::IntPredicate; use rustc_codegen_ssa::errors::InvalidMonomorphization; @@ -17,18 +18,17 @@ }; #[cfg(feature = "master")] use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, MiscCodegenMethods}; -use rustc_codegen_ssa::MemFlags; use rustc_middle::bug; use rustc_middle::ty::layout::LayoutOf; #[cfg(feature = "master")] use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt}; use rustc_middle::ty::{self, Instance, Ty}; -use rustc_span::{sym, Span, Symbol}; -use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode}; +use rustc_span::{Span, Symbol, sym}; use rustc_target::abi::HasDataLayout; +use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode}; +use rustc_target::spec::PanicStrategy; #[cfg(feature = "master")] use rustc_target::spec::abi::Abi; -use rustc_target::spec::PanicStrategy; #[cfg(feature = "master")] use crate::abi::FnAbiGccExt; diff --git a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs index 28f6a0821fb..d78b3f2eb8e 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/simd.rs @@ -16,7 +16,7 @@ use rustc_middle::mir::BinOp; use rustc_middle::ty::layout::HasTyCtxt; use rustc_middle::ty::{self, Ty}; -use rustc_span::{sym, Span, Symbol}; +use rustc_span::{Span, Symbol, sym}; use rustc_target::abi::{Align, Size}; use crate::builder::Builder; @@ -60,10 +60,11 @@ macro_rules! require_simd { 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(); @@ -135,17 +136,14 @@ macro_rules! require_simd { 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 } @@ -251,17 +249,23 @@ macro_rules! require_simd { 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()); @@ -364,14 +368,21 @@ macro_rules! require_simd { 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(); @@ -380,16 +391,13 @@ macro_rules! require_simd { #[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(); @@ -403,10 +411,13 @@ macro_rules! require_simd { #[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()); } @@ -414,15 +425,18 @@ macro_rules! require_simd { 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 }), @@ -434,27 +448,25 @@ macro_rules! require_simd { 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::ParamEnv::reveal_all(), ty) }); - require!( - metadata.is_unit(), - InvalidMonomorphization::CastFatPointer { span, name, ty: in_elem } - ); + require!(metadata.is_unit(), InvalidMonomorphization::CastFatPointer { + span, + name, + ty: in_elem + }); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem }) @@ -465,10 +477,11 @@ macro_rules! require_simd { let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), ty) }); - require!( - metadata.is_unit(), - InvalidMonomorphization::CastFatPointer { span, name, ty: out_elem } - ); + require!(metadata.is_unit(), InvalidMonomorphization::CastFatPointer { + span, + name, + ty: out_elem + }); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem }) @@ -491,17 +504,14 @@ macro_rules! require_simd { 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(_, _) => {} @@ -530,17 +540,14 @@ macro_rules! require_simd { 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) => {} @@ -569,17 +576,14 @@ macro_rules! require_simd { 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()); @@ -605,17 +609,14 @@ enum Style { 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)), } @@ -880,47 +881,45 @@ fn gather<'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 { @@ -947,18 +946,15 @@ fn non_ptr(t: Ty<'_>) -> Ty<'_> { (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!(); } }; @@ -971,15 +967,12 @@ fn non_ptr(t: Ty<'_>) -> Ty<'_> { 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] + }); } } @@ -1003,40 +996,36 @@ fn non_ptr(t: Ty<'_>) -> Ty<'_> { // 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 { @@ -1064,18 +1053,15 @@ fn non_ptr(t: Ty<'_>) -> Ty<'_> { (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!(); } }; @@ -1087,15 +1073,12 @@ fn non_ptr(t: Ty<'_>) -> Ty<'_> { 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] + }); } } @@ -1262,10 +1245,13 @@ macro_rules! arith_red { ($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); @@ -1331,10 +1317,13 @@ macro_rules! arith_red { 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())), @@ -1358,10 +1347,13 @@ macro_rules! bitwise_red { ($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_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index 4de671ac4a0..edf524ff0b4 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/src/lib.rs @@ -107,10 +107,10 @@ use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; use rustc_middle::ty::TyCtxt; use rustc_middle::util::Providers; -use rustc_session::config::{Lto, OptLevel, OutputFilenames}; use rustc_session::Session; -use rustc_span::fatal_error::FatalError; +use rustc_session::config::{Lto, OptLevel, OutputFilenames}; use rustc_span::Symbol; +use rustc_span::fatal_error::FatalError; use tempfile::TempDir; use crate::back::lto::ModuleBuffer; diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs index 0fa8c9d3f19..3d75393bf06 100644 --- a/compiler/rustc_codegen_llvm/src/abi.rs +++ b/compiler/rustc_codegen_llvm/src/abi.rs @@ -1,19 +1,19 @@ use std::cmp; use libc::c_uint; +use rustc_codegen_ssa::MemFlags; use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue}; use rustc_codegen_ssa::mir::place::{PlaceRef, PlaceValue}; use rustc_codegen_ssa::traits::*; -use rustc_codegen_ssa::MemFlags; +use rustc_middle::ty::Ty; use rustc_middle::ty::layout::LayoutOf; pub(crate) use rustc_middle::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA}; -use rustc_middle::ty::Ty; use rustc_middle::{bug, ty}; use rustc_session::config; pub(crate) use rustc_target::abi::call::*; use rustc_target::abi::{self, HasDataLayout, Int, Size}; -pub(crate) use rustc_target::spec::abi::Abi; use rustc_target::spec::SanitizerSet; +pub(crate) use rustc_target::spec::abi::Abi; use smallvec::SmallVec; use crate::attributes::llfn_attrs_from_instance; @@ -445,11 +445,11 @@ fn apply_attrs_llfn( // 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), + )]); } }; @@ -469,14 +469,10 @@ fn apply_attrs_llfn( ); 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: _ } => { @@ -592,11 +588,9 @@ fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll V 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 } => { @@ -628,11 +622,9 @@ fn apply_attrs_callsite(&self, bx: &mut Builder<'_, 'll, 'tcx>, callsite: &'ll V // 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/allocator.rs b/compiler/rustc_codegen_llvm/src/allocator.rs index b4f3784a31a..2adac278c62 100644 --- a/compiler/rustc_codegen_llvm/src/allocator.rs +++ b/compiler/rustc_codegen_llvm/src/allocator.rs @@ -1,14 +1,14 @@ use libc::c_uint; use rustc_ast::expand::allocator::{ - alloc_error_handler_name, default_fn_name, global_fn_name, AllocatorKind, AllocatorTy, - ALLOCATOR_METHODS, NO_ALLOC_SHIM_IS_UNSTABLE, + ALLOCATOR_METHODS, AllocatorKind, AllocatorTy, NO_ALLOC_SHIM_IS_UNSTABLE, + alloc_error_handler_name, default_fn_name, global_fn_name, }; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; use rustc_session::config::{DebugInfo, OomStrategy}; use crate::llvm::{self, Context, False, Module, True, Type}; -use crate::{attributes, debuginfo, ModuleLlvm}; +use crate::{ModuleLlvm, attributes, debuginfo}; pub(crate) unsafe fn codegen( tcx: TyCtxt<'_>, diff --git a/compiler/rustc_codegen_llvm/src/asm.rs b/compiler/rustc_codegen_llvm/src/asm.rs index 430ba735243..fabe7e56b8f 100644 --- a/compiler/rustc_codegen_llvm/src/asm.rs +++ b/compiler/rustc_codegen_llvm/src/asm.rs @@ -5,10 +5,10 @@ use rustc_codegen_ssa::mir::operand::OperandValue; use rustc_codegen_ssa::traits::*; use rustc_data_structures::fx::FxHashMap; -use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::Instance; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::{bug, span_bug}; -use rustc_span::{sym, Pos, Span, Symbol}; +use rustc_span::{Pos, Span, Symbol, sym}; use rustc_target::abi::*; use rustc_target::asm::*; use smallvec::SmallVec; diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index 4f2c83634a8..1b4f6682af0 100644 --- a/compiler/rustc_codegen_llvm/src/back/archive.rs +++ b/compiler/rustc_codegen_llvm/src/back/archive.rs @@ -1,12 +1,12 @@ //! A helper class for dealing with static archives -use std::ffi::{c_char, c_void, CStr, CString}; +use std::ffi::{CStr, CString, c_char, c_void}; use std::path::{Path, PathBuf}; use std::{io, mem, ptr, str}; use rustc_codegen_ssa::back::archive::{ - try_extract_macho_fat_archive, ArArchiveBuilder, ArchiveBuildFailure, ArchiveBuilder, - ArchiveBuilderBuilder, ObjectReader, UnknownArchiveKind, DEFAULT_OBJECT_READER, + ArArchiveBuilder, ArchiveBuildFailure, ArchiveBuilder, ArchiveBuilderBuilder, + DEFAULT_OBJECT_READER, ObjectReader, UnknownArchiveKind, try_extract_macho_fat_archive, }; use rustc_session::Session; diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index 66479ad7f34..5e510177818 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -11,7 +11,7 @@ use rustc_codegen_ssa::back::symbol_export; use rustc_codegen_ssa::back::write::{CodegenContext, FatLtoInput, TargetMachineFactoryConfig}; use rustc_codegen_ssa::traits::*; -use rustc_codegen_ssa::{looks_like_rust_object_file, ModuleCodegen, ModuleKind}; +use rustc_codegen_ssa::{ModuleCodegen, ModuleKind, looks_like_rust_object_file}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::memmap::Mmap; use rustc_errors::{DiagCtxtHandle, FatalError}; @@ -23,7 +23,7 @@ use tracing::{debug, info}; use crate::back::write::{ - self, bitcode_section_name, save_temp_bitcode, CodegenDiagnosticsStage, DiagnosticHandlers, + self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, save_temp_bitcode, }; use crate::errors::{ DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib, LtoProcMacro, @@ -844,7 +844,7 @@ fn from_thin_lto_modules( llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0); }) .expect("Invalid ThinLTO module key"); - (name.clone().into_string().unwrap(), key) + (module_name_to_str(name).to_string(), key) }) .collect(); Self { keys } diff --git a/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs b/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs index 76529e0c83b..44c30d22a9e 100644 --- a/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs +++ b/compiler/rustc_codegen_llvm/src/back/owned_target_machine.rs @@ -1,4 +1,4 @@ -use std::ffi::{c_char, CStr}; +use std::ffi::{CStr, c_char}; use std::marker::PhantomData; use std::ops::Deref; use std::ptr::NonNull; diff --git a/compiler/rustc_codegen_llvm/src/back/profiling.rs b/compiler/rustc_codegen_llvm/src/back/profiling.rs index 79794775b7b..73ae0072c42 100644 --- a/compiler/rustc_codegen_llvm/src/back/profiling.rs +++ b/compiler/rustc_codegen_llvm/src/back/profiling.rs @@ -1,4 +1,4 @@ -use std::ffi::{c_void, CStr}; +use std::ffi::{CStr, c_void}; use std::os::raw::c_char; use std::sync::Arc; diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index d2c4ea8171b..afdd2b581b8 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -20,19 +20,19 @@ use rustc_errors::{DiagCtxtHandle, FatalError, Level}; use rustc_fs_util::{link_or_copy, path_to_c_string}; use rustc_middle::ty::TyCtxt; +use rustc_session::Session; use rustc_session::config::{ self, Lto, OutputType, Passes, RemapPathScopeComponents, SplitDwarfKind, SwitchWithOptPath, }; -use rustc_session::Session; -use rustc_span::symbol::sym; use rustc_span::InnerSpan; +use rustc_span::symbol::sym; use rustc_target::spec::{CodeModel, RelocModel, SanitizerSet, SplitDebuginfo, TlsModel}; use tracing::debug; use crate::back::lto::ThinBuffer; use crate::back::owned_target_machine::OwnedTargetMachine; use crate::back::profiling::{ - selfprofile_after_pass_callback, selfprofile_before_pass_callback, LlvmSelfProfiler, + LlvmSelfProfiler, selfprofile_after_pass_callback, selfprofile_before_pass_callback, }; use crate::errors::{ CopyBitcode, FromLlvmDiag, FromLlvmOptimizationDiag, LlvmError, UnknownCompression, @@ -41,7 +41,7 @@ use crate::llvm::diagnostic::OptimizationDiagnosticKind::*; use crate::llvm::{self, DiagnosticInfo, PassManager}; use crate::type_::Type; -use crate::{base, common, llvm_util, LlvmCodegenBackend, ModuleLlvm}; +use crate::{LlvmCodegenBackend, ModuleLlvm, base, common, llvm_util}; pub(crate) fn llvm_err<'a>(dcx: DiagCtxtHandle<'_>, err: LlvmError<'a>) -> FatalError { match llvm::last_error() { diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 6ffe90997f5..a8af2de1ddd 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -3,11 +3,11 @@ use std::{iter, ptr}; use libc::{c_char, c_uint}; +use rustc_codegen_ssa::MemFlags; use rustc_codegen_ssa::common::{IntPredicate, RealPredicate, SynchronizationScope, TypeKind}; use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue}; use rustc_codegen_ssa::mir::place::PlaceRef; use rustc_codegen_ssa::traits::*; -use rustc_codegen_ssa::MemFlags; use rustc_data_structures::small_c_str::SmallCStr; use rustc_hir::def_id::DefId; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs; diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 33d3b5d4474..33a85adeb87 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -6,8 +6,8 @@ use rustc_hir::def_id::DefId; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}; use rustc_middle::mir::interpret::{ - read_target_uint, Allocation, ConstAllocation, ErrorHandled, InitChunk, Pointer, - Scalar as InterpScalar, + Allocation, ConstAllocation, ErrorHandled, InitChunk, Pointer, Scalar as InterpScalar, + read_target_uint, }; use rustc_middle::mir::mono::MonoItem; use rustc_middle::ty::layout::LayoutOf; diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 1d5580fdd07..2f9a7d77a3b 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -7,7 +7,7 @@ use rustc_codegen_ssa::base::{wants_msvc_seh, wants_wasm_eh}; use rustc_codegen_ssa::errors as ssa_errors; use rustc_codegen_ssa::traits::*; -use rustc_data_structures::base_n::{ToBaseN, ALPHANUMERIC_ONLY}; +use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, ToBaseN}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::small_c_str::SmallCStr; use rustc_hir::def_id::DefId; @@ -18,12 +18,12 @@ }; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; +use rustc_session::Session; use rustc_session::config::{ BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, PAuthKey, PacRet, }; -use rustc_session::Session; use rustc_span::source_map::Spanned; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi::{HasDataLayout, TargetDataLayout, VariantIdx}; use rustc_target::spec::{HasTargetSpec, RelocModel, SmallDataThresholdSupport, Target, TlsModel}; use smallvec::SmallVec; diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index a9f65ee8a93..267a2244916 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs @@ -5,8 +5,8 @@ use rustc_index::IndexVec; use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::{bug, mir}; -use rustc_span::def_id::DefIdSet; use rustc_span::Symbol; +use rustc_span::def_id::DefIdSet; use tracing::debug; use crate::common::CodegenCx; @@ -183,8 +183,8 @@ fn make_filenames_buffer(&self, tcx: TyCtxt<'_>) -> Vec { // Since rustc generates coverage maps with relative paths, the // compilation directory can be combined with the relative paths // to get absolute paths, if needed. - use rustc_session::config::RemapPathScopeComponents; use rustc_session::RemapFileNameExt; + use rustc_session::config::RemapPathScopeComponents; let working_dir: &str = &tcx .sess .opts diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs index c9d2a1c9b88..3a80d216f47 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/mod.rs @@ -9,8 +9,8 @@ use rustc_llvm::RustString; use rustc_middle::bug; use rustc_middle::mir::coverage::CoverageKind; -use rustc_middle::ty::layout::HasTyCtxt; use rustc_middle::ty::Instance; +use rustc_middle::ty::layout::HasTyCtxt; use rustc_target::abi::{Align, Size}; use tracing::{debug, instrument}; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs index c3087d8ec30..ac6c2fb1b83 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/create_scope_map.rs @@ -1,7 +1,7 @@ use rustc_codegen_ssa::mir::debuginfo::{DebugScope, FunctionDebugContext}; use rustc_codegen_ssa::traits::*; -use rustc_index::bit_set::BitSet; use rustc_index::Idx; +use rustc_index::bit_set::BitSet; use rustc_middle::mir::{Body, SourceScope}; use rustc_middle::ty::layout::FnAbiOf; use rustc_middle::ty::{self, Instance}; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index 57e396415cc..d429d5730dd 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -5,7 +5,7 @@ use std::{iter, ptr}; use libc::{c_char, c_longlong, c_uint}; -use rustc_codegen_ssa::debuginfo::type_names::{cpp_like_debuginfo, VTableNameKind}; +use rustc_codegen_ssa::debuginfo::type_names::{VTableNameKind, cpp_like_debuginfo}; use rustc_codegen_ssa::traits::*; use rustc_fs_util::path_to_c_string; use rustc_hir::def::{CtorKind, DefKind}; @@ -18,7 +18,7 @@ }; use rustc_session::config::{self, DebugInfo, Lto}; use rustc_span::symbol::Symbol; -use rustc_span::{hygiene, FileName, FileNameDisplayPreference, SourceFile, DUMMY_SP}; +use rustc_span::{DUMMY_SP, FileName, FileNameDisplayPreference, SourceFile, hygiene}; use rustc_symbol_mangling::typeid_for_trait_ref; use rustc_target::abi::{Align, Size}; use rustc_target::spec::DebuginfoKind; @@ -26,15 +26,15 @@ use tracing::{debug, instrument}; use self::type_map::{DINodeCreationResult, Stub, UniqueTypeId}; +use super::CodegenUnitDebugContext; use super::namespace::mangled_name_of_instance; use super::type_names::{compute_debuginfo_type_name, compute_debuginfo_vtable_name}; use super::utils::{ - create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, DIB, + DIB, create_DIArray, debug_context, get_namespace_for_item, is_node_local_to_unit, }; -use super::CodegenUnitDebugContext; use crate::common::CodegenCx; use crate::debuginfo::metadata::type_map::build_type_with_children; -use crate::debuginfo::utils::{fat_pointer_kind, FatPtrKind}; +use crate::debuginfo::utils::{FatPtrKind, fat_pointer_kind}; use crate::llvm::debuginfo::{ DIDescriptor, DIFile, DIFlags, DILexicalBlock, DIScope, DIType, DebugEmissionKind, DebugNameTableKind, @@ -875,8 +875,8 @@ pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>( codegen_unit_name: &str, debug_context: &CodegenUnitDebugContext<'ll, 'tcx>, ) -> &'ll DIDescriptor { - use rustc_session::config::RemapPathScopeComponents; use rustc_session::RemapFileNameExt; + use rustc_session::config::RemapPathScopeComponents; let mut name_in_debuginfo = tcx .sess .local_crate_source_file() diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs index 8a132f89aa3..966788cf32f 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/cpp_like.rs @@ -15,9 +15,9 @@ use crate::debuginfo::metadata::enums::DiscrResult; use crate::debuginfo::metadata::type_map::{self, Stub, UniqueTypeId}; use crate::debuginfo::metadata::{ + DINodeCreationResult, NO_GENERICS, NO_SCOPE_METADATA, SmallVec, UNKNOWN_LINE_NUMBER, build_field_di_node, file_metadata, size_and_align_of, type_di_node, unknown_file_metadata, - visibility_di_flags, DINodeCreationResult, SmallVec, NO_GENERICS, NO_SCOPE_METADATA, - UNKNOWN_LINE_NUMBER, + visibility_di_flags, }; use crate::debuginfo::utils::DIB; use crate::llvm::debuginfo::{DIFile, DIFlags, DIType}; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs index edaf73b74a2..fe1634146ff 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/mod.rs @@ -12,14 +12,14 @@ use rustc_target::abi::{FieldIdx, TagEncoding, VariantIdx, Variants}; use super::type_map::{DINodeCreationResult, UniqueTypeId}; -use super::{size_and_align_of, SmallVec}; +use super::{SmallVec, size_and_align_of}; use crate::common::CodegenCx; use crate::debuginfo::metadata::type_map::{self, Stub}; use crate::debuginfo::metadata::{ - build_field_di_node, build_generic_type_param_di_nodes, type_di_node, unknown_file_metadata, - UNKNOWN_LINE_NUMBER, + UNKNOWN_LINE_NUMBER, build_field_di_node, build_generic_type_param_di_nodes, type_di_node, + unknown_file_metadata, }; -use crate::debuginfo::utils::{create_DIArray, get_namespace_for_item, DIB}; +use crate::debuginfo::utils::{DIB, create_DIArray, get_namespace_for_item}; use crate::llvm::debuginfo::{DIFlags, DIType}; use crate::llvm::{self}; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs index 0b3140cc91f..5e7dbdd921a 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs @@ -13,10 +13,10 @@ use crate::common::CodegenCx; use crate::debuginfo::metadata::type_map::{self, Stub, StubInfo, UniqueTypeId}; use crate::debuginfo::metadata::{ - file_metadata, size_and_align_of, type_di_node, unknown_file_metadata, visibility_di_flags, - DINodeCreationResult, SmallVec, NO_GENERICS, UNKNOWN_LINE_NUMBER, + DINodeCreationResult, NO_GENERICS, SmallVec, UNKNOWN_LINE_NUMBER, file_metadata, + size_and_align_of, type_di_node, unknown_file_metadata, visibility_di_flags, }; -use crate::debuginfo::utils::{create_DIArray, get_namespace_for_item, DIB}; +use crate::debuginfo::utils::{DIB, create_DIArray, get_namespace_for_item}; use crate::llvm::debuginfo::{DIFile, DIFlags, DIType}; use crate::llvm::{self}; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs index 6d21f4204e3..714e3c0b145 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs @@ -8,9 +8,9 @@ use rustc_middle::ty::{ParamEnv, PolyExistentialTraitRef, Ty, TyCtxt}; use rustc_target::abi::{Align, Size, VariantIdx}; -use super::{unknown_file_metadata, SmallVec, UNKNOWN_LINE_NUMBER}; +use super::{SmallVec, UNKNOWN_LINE_NUMBER, unknown_file_metadata}; use crate::common::CodegenCx; -use crate::debuginfo::utils::{create_DIArray, debug_context, DIB}; +use crate::debuginfo::utils::{DIB, create_DIArray, debug_context}; use crate::llvm::debuginfo::{DIFlags, DIScope, DIType}; use crate::llvm::{self}; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index 920c9e06be4..1a8153a54e8 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -16,8 +16,8 @@ use rustc_middle::mir; use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::{self, GenericArgsRef, Instance, ParamEnv, Ty, TypeVisitableExt}; -use rustc_session::config::{self, DebugInfo}; use rustc_session::Session; +use rustc_session::config::{self, DebugInfo}; use rustc_span::symbol::Symbol; use rustc_span::{ BytePos, Pos, SourceFile, SourceFileAndLine, SourceFileHash, Span, StableSourceFileId, @@ -26,9 +26,9 @@ use smallvec::SmallVec; use tracing::debug; -use self::metadata::{file_metadata, type_di_node, UNKNOWN_COLUMN_NUMBER, UNKNOWN_LINE_NUMBER}; +use self::metadata::{UNKNOWN_COLUMN_NUMBER, UNKNOWN_LINE_NUMBER, file_metadata, type_di_node}; use self::namespace::mangled_name_of_instance; -use self::utils::{create_DIArray, is_node_local_to_unit, DIB}; +use self::utils::{DIB, create_DIArray, is_node_local_to_unit}; use crate::abi::FnAbi; use crate::builder::Builder; use crate::common::CodegenCx; @@ -555,17 +555,14 @@ fn get_containing_scope<'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/debuginfo/namespace.rs b/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs index 9674b1eb848..3578755aae0 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs @@ -4,7 +4,7 @@ use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, Instance}; -use super::utils::{debug_context, DIB}; +use super::utils::{DIB, debug_context}; use crate::common::CodegenCx; use crate::llvm; use crate::llvm::debuginfo::DIScope; diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs b/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs index 321553a3df0..acb15449ce3 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/utils.rs @@ -5,8 +5,8 @@ use rustc_middle::ty::{self, Ty}; use tracing::trace; -use super::namespace::item_namespace; use super::CodegenUnitDebugContext; +use super::namespace::item_namespace; use crate::common::CodegenCx; use crate::llvm; use crate::llvm::debuginfo::{DIArray, DIBuilder, DIDescriptor, DIScope}; diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 307fb9c35b7..6ee5ca73eef 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -12,7 +12,7 @@ use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, LayoutOf}; use rustc_middle::ty::{self, GenericArgsRef, Ty}; use rustc_middle::{bug, span_bug}; -use rustc_span::{sym, Span, Symbol}; +use rustc_span::{Span, Symbol, sym}; use rustc_target::abi::{self, Align, Float, HasDataLayout, Primitive, Size}; use rustc_target::spec::{HasTargetSpec, PanicStrategy}; use tracing::debug; @@ -330,15 +330,12 @@ fn codegen_intrinsic_call( 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::ctlz | sym::ctlz_nonzero @@ -356,10 +353,10 @@ fn codegen_intrinsic_call( Some((width, signed)) => 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) } @@ -376,26 +373,24 @@ fn codegen_intrinsic_call( 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(); @@ -471,10 +466,11 @@ fn codegen_intrinsic_call( 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)) } @@ -1216,17 +1212,14 @@ macro_rules! require_simd { 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 } @@ -1252,14 +1245,21 @@ macro_rules! require_simd { 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; @@ -1304,14 +1304,21 @@ macro_rules! require_simd { }; 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; @@ -1336,16 +1343,13 @@ macro_rules! require_simd { } 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"); @@ -1364,10 +1368,13 @@ macro_rules! require_simd { )); } 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"); @@ -1386,10 +1393,12 @@ macro_rules! require_simd { 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 } - ); + 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 }), @@ -1616,34 +1625,30 @@ fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) - 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!( @@ -1734,23 +1739,22 @@ fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) - 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!( @@ -1832,17 +1836,14 @@ fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) - 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!( @@ -1921,28 +1922,22 @@ fn llvm_vector_ty<'ll>(cx: &CodegenCx<'ll, '_>, elem_ty: Ty<'_>, vec_len: u64) - 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!( @@ -2016,10 +2011,13 @@ macro_rules! arith_red { ($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()); @@ -2088,10 +2086,13 @@ macro_rules! arith_red { 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)), @@ -2116,10 +2117,13 @@ macro_rules! bitwise_red { ($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 { match in_elem.kind() { @@ -2165,27 +2169,25 @@ macro_rules! bitwise_red { 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(ty::ParamEnv::reveal_all(), ty) }); - require!( - metadata.is_unit(), - InvalidMonomorphization::CastFatPointer { span, name, ty: in_elem } - ); + require!(metadata.is_unit(), InvalidMonomorphization::CastFatPointer { + span, + name, + ty: in_elem + }); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: in_elem }) @@ -2196,10 +2198,11 @@ macro_rules! bitwise_red { let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), ty) }); - require!( - metadata.is_unit(), - InvalidMonomorphization::CastFatPointer { span, name, ty: out_elem } - ); + require!(metadata.is_unit(), InvalidMonomorphization::CastFatPointer { + span, + name, + ty: out_elem + }); } _ => { return_error!(InvalidMonomorphization::ExpectedPointer { span, name, ty: out_elem }) @@ -2211,17 +2214,14 @@ macro_rules! bitwise_red { 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(_, _) => {} @@ -2239,17 +2239,14 @@ macro_rules! bitwise_red { 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) => {} @@ -2267,17 +2264,14 @@ macro_rules! bitwise_red { 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_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 7f26bbd7f87..d69112612ba 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -41,8 +41,8 @@ use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; use rustc_middle::ty::TyCtxt; use rustc_middle::util::Providers; -use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest}; use rustc_session::Session; +use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest}; use rustc_span::symbol::Symbol; mod back { diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index a588f11b623..4b71cb8963b 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -5,13 +5,13 @@ use libc::{c_char, c_int, c_uint, c_ulonglong, c_void, size_t}; +use super::RustString; use super::debuginfo::{ DIArray, DIBasicType, DIBuilder, DICompositeType, DIDerivedType, DIDescriptor, DIEnumerator, DIFile, DIFlags, DIGlobalVariableExpression, DILexicalBlock, DILocation, DINameSpace, DISPFlags, DIScope, DISubprogram, DISubrange, DITemplateTypeParameter, DIType, DIVariable, DebugEmissionKind, DebugNameTableKind, }; -use super::RustString; pub type Bool = c_uint; diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index fd8db4ad1d5..71fd7afb148 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -1,4 +1,4 @@ -use std::ffi::{c_char, c_void, CStr, CString}; +use std::ffi::{CStr, CString, c_char, c_void}; use std::fmt::Write; use std::path::Path; use std::sync::Once; @@ -11,8 +11,8 @@ use rustc_data_structures::unord::UnordSet; use rustc_fs_util::path_to_c_string; use rustc_middle::bug; -use rustc_session::config::{PrintKind, PrintRequest}; use rustc_session::Session; +use rustc_session::config::{PrintKind, PrintRequest}; use rustc_span::symbol::Symbol; use rustc_target::spec::{MergeFunctions, PanicStrategy, SmallDataThresholdSupport}; use rustc_target::target_features::{RUSTC_SPECIAL_FEATURES, RUSTC_SPECIFIC_FEATURES}; diff --git a/compiler/rustc_codegen_llvm/src/va_arg.rs b/compiler/rustc_codegen_llvm/src/va_arg.rs index 781cee81180..f12b94d5887 100644 --- a/compiler/rustc_codegen_llvm/src/va_arg.rs +++ b/compiler/rustc_codegen_llvm/src/va_arg.rs @@ -1,8 +1,8 @@ use rustc_codegen_ssa::common::IntPredicate; use rustc_codegen_ssa::mir::operand::OperandRef; use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, BuilderMethods, ConstCodegenMethods}; -use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; use rustc_middle::ty::Ty; +use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; use rustc_target::abi::{Align, Endian, HasDataLayout, Size}; use crate::builder::Builder; diff --git a/compiler/rustc_codegen_ssa/src/back/archive.rs b/compiler/rustc_codegen_ssa/src/back/archive.rs index a665f5c9306..2f48c1fbf0d 100644 --- a/compiler/rustc_codegen_ssa/src/back/archive.rs +++ b/compiler/rustc_codegen_ssa/src/back/archive.rs @@ -6,9 +6,9 @@ use std::path::{Path, PathBuf}; use ar_archive_writer::{ - write_archive_to_stream, ArchiveKind, COFFShortExport, MachineTypes, NewArchiveMember, + ArchiveKind, COFFShortExport, MachineTypes, NewArchiveMember, write_archive_to_stream, }; -pub use ar_archive_writer::{ObjectReader, DEFAULT_OBJECT_READER}; +pub use ar_archive_writer::{DEFAULT_OBJECT_READER, ObjectReader}; use object::read::archive::ArchiveFile; use object::read::macho::FatArch; use rustc_data_structures::fx::FxIndexSet; @@ -395,10 +395,10 @@ fn add_archive( 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/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 8b855bd0dd5..892dfb91201 100644 --- a/compiler/rustc_codegen_ssa/src/back/link.rs +++ b/compiler/rustc_codegen_ssa/src/back/link.rs @@ -1,6 +1,6 @@ use std::collections::BTreeSet; use std::ffi::OsString; -use std::fs::{read, File, OpenOptions}; +use std::fs::{File, OpenOptions, read}; use std::io::{BufWriter, Write}; use std::ops::{ControlFlow, Deref}; use std::path::{Path, PathBuf}; @@ -18,7 +18,7 @@ use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, FatalError}; use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize}; use rustc_hir::def_id::{CrateNum, LOCAL_CRATE}; -use rustc_metadata::fs::{copy_to_stdout, emit_wrapper_file, METADATA_FILENAME}; +use rustc_metadata::fs::{METADATA_FILENAME, copy_to_stdout, emit_wrapper_file}; use rustc_metadata::{find_native_static_library, walk_native_lib_search_dirs}; use rustc_middle::bug; use rustc_middle::middle::debugger_visualizer::DebuggerVisualizerFile; @@ -34,7 +34,7 @@ use rustc_session::utils::NativeLibKind; /// For all the linkers we support, and information they might /// need out of the shared crate context before we get rid of it. -use rustc_session::{filesearch, Session}; +use rustc_session::{Session, filesearch}; use rustc_span::symbol::Symbol; use rustc_target::spec::crt_objects::CrtObjects; use rustc_target::spec::{ @@ -48,11 +48,11 @@ use super::archive::{ArchiveBuilder, ArchiveBuilderBuilder}; use super::command::Command; use super::linker::{self, Linker}; -use super::metadata::{create_wrapper_file, MetadataPosition}; +use super::metadata::{MetadataPosition, create_wrapper_file}; use super::rpath::{self, RPathConfig}; use crate::{ - common, errors, looks_like_rust_object_file, CodegenResults, CompiledModule, CrateInfo, - NativeLib, + CodegenResults, CompiledModule, CrateInfo, NativeLib, common, errors, + looks_like_rust_object_file, }; pub fn ensure_removed(dcx: DiagCtxtHandle<'_>, path: &Path) { @@ -1197,8 +1197,8 @@ fn escape_linker_output(s: &[u8], flavour: LinkerFlavor) -> String { #[cfg(windows)] mod win { use windows::Win32::Globalization::{ - GetLocaleInfoEx, MultiByteToWideChar, CP_OEMCP, LOCALE_IUSEUTF8LEGACYOEMCP, - LOCALE_NAME_SYSTEM_DEFAULT, LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, + CP_OEMCP, GetLocaleInfoEx, LOCALE_IUSEUTF8LEGACYOEMCP, LOCALE_NAME_SYSTEM_DEFAULT, + LOCALE_RETURN_NUMBER, MB_ERR_INVALID_CHARS, MultiByteToWideChar, }; /// Get the Windows system OEM code page. This is most notably the code page diff --git a/compiler/rustc_codegen_ssa/src/back/linker.rs b/compiler/rustc_codegen_ssa/src/back/linker.rs index 06fc164893f..84817e19844 100644 --- a/compiler/rustc_codegen_ssa/src/back/linker.rs +++ b/compiler/rustc_codegen_ssa/src/back/linker.rs @@ -15,8 +15,8 @@ use rustc_middle::middle::exported_symbols; use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo, SymbolExportKind}; use rustc_middle::ty::TyCtxt; -use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip}; use rustc_session::Session; +use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip}; use rustc_span::symbol::sym; use rustc_target::spec::{Cc, LinkOutputKind, LinkerFlavor, Lld}; use tracing::{debug, warn}; diff --git a/compiler/rustc_codegen_ssa/src/back/lto.rs b/compiler/rustc_codegen_ssa/src/back/lto.rs index 1e1e039882b..ab8b06a05fc 100644 --- a/compiler/rustc_codegen_ssa/src/back/lto.rs +++ b/compiler/rustc_codegen_ssa/src/back/lto.rs @@ -5,8 +5,8 @@ use rustc_errors::FatalError; use super::write::CodegenContext; -use crate::traits::*; use crate::ModuleCodegen; +use crate::traits::*; pub struct ThinModule { pub shared: Arc>, diff --git a/compiler/rustc_codegen_ssa/src/back/metadata.rs b/compiler/rustc_codegen_ssa/src/back/metadata.rs index ff87f7f1ea4..06433484ea3 100644 --- a/compiler/rustc_codegen_ssa/src/back/metadata.rs +++ b/compiler/rustc_codegen_ssa/src/back/metadata.rs @@ -7,19 +7,20 @@ use object::write::{self, StandardSegment, Symbol, SymbolSection}; use object::{ - elf, pe, xcoff, Architecture, BinaryFormat, Endianness, FileFlags, Object, ObjectSection, - ObjectSymbol, SectionFlags, SectionKind, SubArchitecture, SymbolFlags, SymbolKind, SymbolScope, + Architecture, BinaryFormat, Endianness, FileFlags, Object, ObjectSection, ObjectSymbol, + SectionFlags, SectionKind, SubArchitecture, SymbolFlags, SymbolKind, SymbolScope, elf, pe, + xcoff, }; use rustc_data_structures::memmap::Mmap; -use rustc_data_structures::owned_slice::{try_slice_owned, OwnedSlice}; +use rustc_data_structures::owned_slice::{OwnedSlice, try_slice_owned}; +use rustc_metadata::EncodedMetadata; use rustc_metadata::creader::MetadataLoader; use rustc_metadata::fs::METADATA_FILENAME; -use rustc_metadata::EncodedMetadata; use rustc_middle::bug; use rustc_session::Session; use rustc_span::sym; use rustc_target::abi::Endian; -use rustc_target::spec::{ef_avr_arch, RelocModel, Target}; +use rustc_target::spec::{RelocModel, Target, ef_avr_arch}; /// The default metadata loader. This is used by cg_llvm and cg_clif. /// @@ -668,17 +669,13 @@ 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/rpath/tests.rs b/compiler/rustc_codegen_ssa/src/back/rpath/tests.rs index 0de0b8a52b1..39034842d10 100644 --- a/compiler/rustc_codegen_ssa/src/back/rpath/tests.rs +++ b/compiler/rustc_codegen_ssa/src/back/rpath/tests.rs @@ -1,7 +1,7 @@ use std::ffi::OsString; use std::path::{Path, PathBuf}; -use super::{get_rpath_relative_to_output, minimize_rpaths, rpaths_to_flags, RPathConfig}; +use super::{RPathConfig, get_rpath_relative_to_output, minimize_rpaths, rpaths_to_flags}; #[test] fn test_rpaths_to_flags() { @@ -74,13 +74,10 @@ fn test_rpath_relative_issue_119571() { fn test_xlinker() { let args = rpaths_to_flags(vec!["a/normal/path".into(), "a,comma,path".into()]); - assert_eq!( - args, - vec![ - OsString::from("-Wl,-rpath,a/normal/path"), - OsString::from("-Wl,-rpath"), - OsString::from("-Xlinker"), - OsString::from("a,comma,path") - ] - ); + assert_eq!(args, vec![ + OsString::from("-Wl,-rpath,a/normal/path"), + OsString::from("-Wl,-rpath"), + OsString::from("-Xlinker"), + OsString::from("a,comma,path") + ]); } diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index 257e2dfac00..77c35a1fe79 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -3,11 +3,11 @@ use rustc_ast::expand::allocator::{ALLOCATOR_METHODS, NO_ALLOC_SHIM_IS_UNSTABLE}; use rustc_data_structures::unord::UnordMap; use rustc_hir::def::DefKind; -use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LOCAL_CRATE, LocalDefId}; use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::exported_symbols::{ - metadata_symbol_name, ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel, + ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel, metadata_symbol_name, }; use rustc_middle::query::LocalCrate; use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, Instance, SymbolName, TyCtxt}; @@ -140,14 +140,11 @@ fn reachable_non_generics_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> DefIdMap { if args.non_erasable_generics(tcx, def).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(def_id, Some(ty)), args }) => { @@ -354,14 +327,11 @@ fn exported_symbols_provider_local( args.non_erasable_generics(tcx, def_id).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(def_id, Some(ty)), @@ -372,14 +342,11 @@ fn exported_symbols_provider_local( args.non_erasable_generics(tcx, def_id).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/back/write.rs b/compiler/rustc_codegen_ssa/src/back/write.rs index c170cd41ec4..4d81ff933dd 100644 --- a/compiler/rustc_codegen_ssa/src/back/write.rs +++ b/compiler/rustc_codegen_ssa/src/back/write.rs @@ -2,8 +2,8 @@ use std::assert_matches::assert_matches; use std::marker::PhantomData; use std::path::{Path, PathBuf}; -use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::Arc; +use std::sync::mpsc::{Receiver, Sender, channel}; use std::{fs, io, mem, str, thread}; use jobserver::{Acquired, Client}; @@ -23,16 +23,16 @@ use rustc_incremental::{ copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess, }; -use rustc_metadata::fs::copy_to_stdout; use rustc_metadata::EncodedMetadata; +use rustc_metadata::fs::copy_to_stdout; use rustc_middle::bug; use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; use rustc_middle::middle::exported_symbols::SymbolExportInfo; use rustc_middle::ty::TyCtxt; +use rustc_session::Session; use rustc_session::config::{ self, CrateType, Lto, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath, }; -use rustc_session::Session; use rustc_span::source_map::SourceMap; use rustc_span::symbol::sym; use rustc_span::{BytePos, FileName, InnerSpan, Pos, Span}; @@ -45,8 +45,8 @@ use crate::errors::ErrorCreatingRemarkDir; use crate::traits::*; use crate::{ - errors, CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, - ModuleKind, + CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind, + errors, }; const PRE_LTO_BC_EXT: &str = "pre-lto.bc"; diff --git a/compiler/rustc_codegen_ssa/src/base.rs b/compiler/rustc_codegen_ssa/src/base.rs index 3d1007a4673..8e4385bee1a 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -3,7 +3,7 @@ use std::time::{Duration, Instant}; use itertools::Itertools; -use rustc_ast::expand::allocator::{global_fn_name, AllocatorKind, ALLOCATOR_METHODS}; +use rustc_ast::expand::allocator::{ALLOCATOR_METHODS, AllocatorKind, global_fn_name}; use rustc_attr as attr; use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; @@ -17,15 +17,15 @@ use rustc_middle::middle::debugger_visualizer::{DebuggerVisualizerFile, DebuggerVisualizerType}; use rustc_middle::middle::exported_symbols::SymbolExportKind; use rustc_middle::middle::{exported_symbols, lang_items}; -use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem}; use rustc_middle::mir::BinOp; +use rustc_middle::mir::mono::{CodegenUnit, CodegenUnitNameBuilder, MonoItem}; use rustc_middle::query::Providers; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; -use rustc_session::config::{self, CrateType, EntryFnType, OptLevel, OutputType}; use rustc_session::Session; +use rustc_session::config::{self, CrateType, EntryFnType, OptLevel, OutputType}; use rustc_span::symbol::sym; -use rustc_span::{Symbol, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Symbol}; use rustc_target::abi::FIRST_VARIANT; use tracing::{debug, info}; @@ -33,15 +33,15 @@ use crate::back::link::are_upstream_rust_objects_already_included; use crate::back::metadata::create_compressed_metadata_file; use crate::back::write::{ - compute_per_cgu_lto_type, start_async_codegen, submit_codegened_module_to_llvm, - submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, ComputedLtoType, OngoingCodegen, + ComputedLtoType, OngoingCodegen, compute_per_cgu_lto_type, start_async_codegen, + submit_codegened_module_to_llvm, submit_post_lto_module_to_llvm, submit_pre_lto_module_to_llvm, }; use crate::common::{self, IntPredicate, RealPredicate, TypeKind}; use crate::mir::operand::OperandValue; use crate::mir::place::PlaceRef; use crate::traits::*; use crate::{ - errors, meth, mir, CachedModuleCodegen, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind, + CachedModuleCodegen, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind, errors, meth, mir, }; pub(crate) fn bin_op_to_icmp_predicate(op: BinOp, signed: bool) -> IntPredicate { diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index 9bd8a84f5a3..e99c3a46271 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -1,12 +1,12 @@ -use rustc_ast::{ast, attr, MetaItemKind, NestedMetaItem}; -use rustc_attr::{list_contains_name, InlineAttr, InstructionSetAttr, OptimizeAttr}; +use rustc_ast::{MetaItemKind, NestedMetaItem, ast, attr}; +use rustc_attr::{InlineAttr, InstructionSetAttr, OptimizeAttr, list_contains_name}; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, DiagMessage, SubdiagMessage}; +use rustc_errors::{DiagMessage, SubdiagMessage, struct_span_code_err}; use rustc_hir as hir; use rustc_hir::def::DefKind; -use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS; -use rustc_hir::{lang_items, LangItem}; +use rustc_hir::{LangItem, lang_items}; use rustc_middle::middle::codegen_fn_attrs::{ CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry, }; @@ -16,8 +16,8 @@ use rustc_session::lint; use rustc_session::parse::feature_err; use rustc_span::symbol::Ident; -use rustc_span::{sym, Span}; -use rustc_target::spec::{abi, SanitizerSet}; +use rustc_span::{Span, sym}; +use rustc_target::spec::{SanitizerSet, abi}; use crate::errors; use crate::target_features::{check_target_feature_trait_unsafe, from_target_feature}; diff --git a/compiler/rustc_codegen_ssa/src/errors.rs b/compiler/rustc_codegen_ssa/src/errors.rs index 58877379e26..08b326e3ac3 100644 --- a/compiler/rustc_codegen_ssa/src/errors.rs +++ b/compiler/rustc_codegen_ssa/src/errors.rs @@ -10,8 +10,8 @@ Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level, }; use rustc_macros::Diagnostic; -use rustc_middle::ty::layout::LayoutError; use rustc_middle::ty::Ty; +use rustc_middle::ty::layout::LayoutError; use rustc_span::{Span, Symbol}; use rustc_type_ir::FloatTy; diff --git a/compiler/rustc_codegen_ssa/src/lib.rs b/compiler/rustc_codegen_ssa/src/lib.rs index 26d4d0acac5..ec0520fbb09 100644 --- a/compiler/rustc_codegen_ssa/src/lib.rs +++ b/compiler/rustc_codegen_ssa/src/lib.rs @@ -37,10 +37,10 @@ use rustc_middle::util::Providers; use rustc_serialize::opaque::{FileEncoder, MemDecoder}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; +use rustc_session::Session; use rustc_session::config::{CrateType, OutputFilenames, OutputType, RUST_CGU_EXT}; use rustc_session::cstore::{self, CrateSource}; use rustc_session::utils::NativeLibKind; -use rustc_session::Session; use rustc_span::symbol::Symbol; pub mod assert_module_sources; diff --git a/compiler/rustc_codegen_ssa/src/mir/analyze.rs b/compiler/rustc_codegen_ssa/src/mir/analyze.rs index 25712095e76..43b8230c679 100644 --- a/compiler/rustc_codegen_ssa/src/mir/analyze.rs +++ b/compiler/rustc_codegen_ssa/src/mir/analyze.rs @@ -5,7 +5,7 @@ use rustc_index::bit_set::BitSet; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; -use rustc_middle::mir::{self, traversal, DefLocation, Location, TerminatorKind}; +use rustc_middle::mir::{self, DefLocation, Location, TerminatorKind, traversal}; use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; use rustc_middle::{bug, span_bug}; use tracing::debug; diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index f23ae7abafd..125d3b908c7 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -10,7 +10,7 @@ use rustc_middle::{bug, span_bug}; use rustc_session::config::OptLevel; use rustc_span::source_map::Spanned; -use rustc_span::{sym, Span}; +use rustc_span::{Span, sym}; use rustc_target::abi::call::{ArgAbi, FnAbi, PassMode, Reg}; use rustc_target::abi::{self, HasDataLayout, WrappingRange}; use rustc_target::spec::abi::Abi; @@ -24,7 +24,7 @@ use crate::common::{self, IntPredicate}; use crate::errors::CompilerBuiltinsCannotCall; use crate::traits::*; -use crate::{meth, MemFlags}; +use crate::{MemFlags, meth}; // Indicates if we are in the middle of merging a BB's successor into it. This // can happen when BB jumps directly to its successor and the successor has no @@ -1590,10 +1590,10 @@ fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> { 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/coverageinfo.rs b/compiler/rustc_codegen_ssa/src/mir/coverageinfo.rs index 52e749f4fb7..33a050ef280 100644 --- a/compiler/rustc_codegen_ssa/src/mir/coverageinfo.rs +++ b/compiler/rustc_codegen_ssa/src/mir/coverageinfo.rs @@ -1,5 +1,5 @@ -use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::mir::SourceScope; +use rustc_middle::mir::coverage::CoverageKind; use super::FunctionCx; use crate::traits::*; diff --git a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs index 5b36a11aa25..9874809ea2b 100644 --- a/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/mir/debuginfo.rs @@ -8,8 +8,8 @@ use rustc_middle::ty::{Instance, Ty}; use rustc_middle::{bug, mir, ty}; use rustc_session::config::DebugInfo; -use rustc_span::symbol::{kw, Symbol}; -use rustc_span::{hygiene, BytePos, Span}; +use rustc_span::symbol::{Symbol, kw}; +use rustc_span::{BytePos, Span, hygiene}; use rustc_target::abi::{Abi, FieldIdx, FieldsShape, Size, VariantIdx}; use super::operand::{OperandRef, OperandValue}; diff --git a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs index 4acbc04c505..71541e6ab41 100644 --- a/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/mir/intrinsic.rs @@ -1,16 +1,16 @@ use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_session::config::OptLevel; -use rustc_span::{sym, Span}; -use rustc_target::abi::call::{FnAbi, PassMode}; +use rustc_span::{Span, sym}; use rustc_target::abi::WrappingRange; +use rustc_target::abi::call::{FnAbi, PassMode}; +use super::FunctionCx; use super::operand::OperandRef; use super::place::PlaceRef; -use super::FunctionCx; use crate::errors::InvalidMonomorphization; use crate::traits::*; -use crate::{errors, meth, size_of_val, MemFlags}; +use crate::{MemFlags, errors, meth, size_of_val}; fn copy_intrinsic<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>( bx: &mut Bx, diff --git a/compiler/rustc_codegen_ssa/src/mir/mod.rs b/compiler/rustc_codegen_ssa/src/mir/mod.rs index 68fb5cb2206..202baddec72 100644 --- a/compiler/rustc_codegen_ssa/src/mir/mod.rs +++ b/compiler/rustc_codegen_ssa/src/mir/mod.rs @@ -1,9 +1,9 @@ use std::iter; -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use rustc_middle::mir::{traversal, UnwindTerminateReason}; +use rustc_middle::mir::{UnwindTerminateReason, traversal}; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable, TypeVisitableExt}; use rustc_middle::{bug, mir, span_bug}; diff --git a/compiler/rustc_codegen_ssa/src/mir/operand.rs b/compiler/rustc_codegen_ssa/src/mir/operand.rs index ee32b4f23c9..17f66c12a03 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -4,17 +4,17 @@ use arrayvec::ArrayVec; use either::Either; use rustc_middle::bug; -use rustc_middle::mir::interpret::{alloc_range, Pointer, Scalar}; +use rustc_middle::mir::interpret::{Pointer, Scalar, alloc_range}; use rustc_middle::mir::{self, ConstValue}; -use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::Ty; +use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_target::abi::{self, Abi, Align, Size}; use tracing::debug; use super::place::{PlaceRef, PlaceValue}; use super::{FunctionCx, LocalRef}; use crate::traits::*; -use crate::{size_of_val, MemFlags}; +use crate::{MemFlags, size_of_val}; /// The representation of a Rust value. The enum variant is in fact /// uniquely determined by the value's type, but is kept as a diff --git a/compiler/rustc_codegen_ssa/src/mir/place.rs b/compiler/rustc_codegen_ssa/src/mir/place.rs index eba150c6eac..0b764ae7747 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -415,11 +415,10 @@ pub fn project_index>( layout.size }; - let llval = bx.inbounds_gep( - bx.cx().backend_type(self.layout), - self.val.llval, - &[bx.cx().const_usize(0), llindex], - ); + let llval = bx.inbounds_gep(bx.cx().backend_type(self.layout), self.val.llval, &[ + bx.cx().const_usize(0), + llindex, + ]); let align = self.val.align.restrict_for_offset(offset); PlaceValue::new_sized(llval, align).with_type(layout) } @@ -470,10 +469,10 @@ pub fn codegen_place( 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_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index 6bf75293fce..ad0e03fc263 100644 --- a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs +++ b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs @@ -6,8 +6,8 @@ use rustc_middle::ty::{self, Instance, Ty, TyCtxt}; use rustc_middle::{bug, mir, span_bug}; use rustc_session::config::OptLevel; -use rustc_span::{Span, DUMMY_SP}; -use rustc_target::abi::{self, FieldIdx, FIRST_VARIANT}; +use rustc_span::{DUMMY_SP, Span}; +use rustc_target::abi::{self, FIRST_VARIANT, FieldIdx}; use tracing::{debug, instrument}; use super::operand::{OperandRef, OperandValue}; @@ -15,7 +15,7 @@ use super::{FunctionCx, LocalRef}; use crate::common::IntPredicate; use crate::traits::*; -use crate::{base, MemFlags}; +use crate::{MemFlags, base}; impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { #[instrument(level = "trace", skip(self, bx))] diff --git a/compiler/rustc_codegen_ssa/src/mono_item.rs b/compiler/rustc_codegen_ssa/src/mono_item.rs index 64fcefdc860..038c5857fac 100644 --- a/compiler/rustc_codegen_ssa/src/mono_item.rs +++ b/compiler/rustc_codegen_ssa/src/mono_item.rs @@ -1,8 +1,8 @@ use rustc_hir as hir; use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::mir::mono::{Linkage, MonoItem, Visibility}; -use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; use rustc_middle::ty::Instance; +use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf}; use rustc_middle::{span_bug, ty}; use tracing::debug; diff --git a/compiler/rustc_codegen_ssa/src/target_features.rs b/compiler/rustc_codegen_ssa/src/target_features.rs index 0349d5817b4..dfe8fd616e4 100644 --- a/compiler/rustc_codegen_ssa/src/target_features.rs +++ b/compiler/rustc_codegen_ssa/src/target_features.rs @@ -4,14 +4,14 @@ use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_errors::Applicability; use rustc_hir::def::DefKind; -use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::TargetFeature; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::parse::feature_err; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, sym}; use crate::errors; diff --git a/compiler/rustc_codegen_ssa/src/traits/backend.rs b/compiler/rustc_codegen_ssa/src/traits/backend.rs index e45af1cd153..3df85a618d1 100644 --- a/compiler/rustc_codegen_ssa/src/traits/backend.rs +++ b/compiler/rustc_codegen_ssa/src/traits/backend.rs @@ -5,17 +5,17 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync::{DynSend, DynSync}; use rustc_errors::ErrorGuaranteed; -use rustc_metadata::creader::MetadataLoaderDyn; use rustc_metadata::EncodedMetadata; +use rustc_metadata::creader::MetadataLoaderDyn; use rustc_middle::dep_graph::{WorkProduct, WorkProductId}; use rustc_middle::ty::TyCtxt; use rustc_middle::util::Providers; -use rustc_session::config::{self, OutputFilenames, PrintRequest}; use rustc_session::Session; +use rustc_session::config::{self, OutputFilenames, PrintRequest}; use rustc_span::symbol::Symbol; -use super::write::WriteBackendMethods; use super::CodegenObject; +use super::write::WriteBackendMethods; use crate::back::write::TargetMachineFactoryFn; use crate::{CodegenResults, ModuleCodegen}; diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index 5af0457bebd..71187df37cc 100644 --- a/compiler/rustc_codegen_ssa/src/traits/builder.rs +++ b/compiler/rustc_codegen_ssa/src/traits/builder.rs @@ -18,12 +18,12 @@ use super::misc::MiscCodegenMethods; use super::type_::{ArgAbiBuilderMethods, BaseTypeCodegenMethods, LayoutTypeCodegenMethods}; use super::{CodegenMethods, StaticBuilderMethods}; +use crate::MemFlags; use crate::common::{ AtomicOrdering, AtomicRmwBinOp, IntPredicate, RealPredicate, SynchronizationScope, TypeKind, }; use crate::mir::operand::{OperandRef, OperandValue}; use crate::mir::place::{PlaceRef, PlaceValue}; -use crate::MemFlags; #[derive(Copy, Clone, Debug)] pub enum OverflowOp { diff --git a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs index 7526c221b05..c26d4532d0f 100644 --- a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs @@ -3,8 +3,8 @@ use rustc_middle::mir; use rustc_middle::ty::{Instance, PolyExistentialTraitRef, Ty}; use rustc_span::{SourceFile, Span, Symbol}; -use rustc_target::abi::call::FnAbi; use rustc_target::abi::Size; +use rustc_target::abi::call::FnAbi; use super::BackendTypes; use crate::mir::debuginfo::{FunctionDebugContext, VariableKind}; diff --git a/compiler/rustc_codegen_ssa/src/traits/mod.rs b/compiler/rustc_codegen_ssa/src/traits/mod.rs index 2196bc996d9..800470286bc 100644 --- a/compiler/rustc_codegen_ssa/src/traits/mod.rs +++ b/compiler/rustc_codegen_ssa/src/traits/mod.rs @@ -27,8 +27,8 @@ use std::fmt; -use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout}; use rustc_middle::ty::Ty; +use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout}; use rustc_target::abi::call::FnAbi; pub use self::abi::AbiBuilderMethods; diff --git a/compiler/rustc_codegen_ssa/src/traits/type_.rs b/compiler/rustc_codegen_ssa/src/traits/type_.rs index f6f309287fe..50534ec8030 100644 --- a/compiler/rustc_codegen_ssa/src/traits/type_.rs +++ b/compiler/rustc_codegen_ssa/src/traits/type_.rs @@ -4,8 +4,8 @@ use rustc_target::abi::call::{ArgAbi, CastTarget, FnAbi, Reg}; use rustc_target::abi::{AddressSpace, Float, Integer}; -use super::misc::MiscCodegenMethods; use super::BackendTypes; +use super::misc::MiscCodegenMethods; use crate::common::TypeKind; use crate::mir::place::PlaceRef; diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 6d09ed5b4bf..2c33ff9d219 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -16,10 +16,10 @@ use rustc_middle::span_bug; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::{self, Instance, InstanceKind, Ty, TypeVisitableExt}; +use rustc_mir_dataflow::Analysis; use rustc_mir_dataflow::impls::MaybeStorageLive; use rustc_mir_dataflow::storage::always_storage_live_locals; -use rustc_mir_dataflow::Analysis; -use rustc_span::{sym, Span, Symbol, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span, Symbol, sym}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt}; use tracing::{debug, instrument, trace}; diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index a52fc6a077b..df8313d0e70 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -2,20 +2,20 @@ use hir::def_id::LocalDefId; use hir::{ConstContext, LangItem}; -use rustc_errors::codes::*; use rustc_errors::Diag; +use rustc_errors::codes::*; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::{ImplSource, Obligation, ObligationCause}; use rustc_middle::mir::CallSource; use rustc_middle::span_bug; -use rustc_middle::ty::print::{with_no_trimmed_paths, PrintTraitRefExt as _}; +use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths}; use rustc_middle::ty::{ - self, suggest_constraining_type_param, Closure, FnDef, FnPtr, GenericArgKind, GenericArgsRef, - Param, TraitRef, Ty, + self, Closure, FnDef, FnPtr, GenericArgKind, GenericArgsRef, Param, TraitRef, Ty, + suggest_constraining_type_param, }; -use rustc_middle::util::{call_kind, CallDesugaringKind, CallKind}; +use rustc_middle::util::{CallDesugaringKind, CallKind, call_kind}; use rustc_session::parse::feature_err; use rustc_span::symbol::sym; use rustc_span::{BytePos, Pos, Span, Symbol}; diff --git a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs index f0998300dc8..f98234ce7f3 100644 --- a/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs +++ b/compiler/rustc_const_eval/src/check_consts/post_drop_elaboration.rs @@ -1,14 +1,14 @@ use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::{self, BasicBlock, Location}; use rustc_middle::ty::{Ty, TyCtxt}; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use tracing::trace; +use super::ConstCx; use super::check::Qualifs; use super::ops::{self, NonConstOp}; use super::qualifs::{NeedsNonConstDrop, Qualif}; -use super::ConstCx; use crate::check_consts::rustc_allow_const_fn_unstable; /// Returns `true` if we should use the more precise live drop checker that runs after drop diff --git a/compiler/rustc_const_eval/src/check_consts/qualifs.rs b/compiler/rustc_const_eval/src/check_consts/qualifs.rs index c566dc7fa84..7358a6c6d22 100644 --- a/compiler/rustc_const_eval/src/check_consts/qualifs.rs +++ b/compiler/rustc_const_eval/src/check_consts/qualifs.rs @@ -206,14 +206,10 @@ fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { cx.tcx, ObligationCause::dummy_with_span(cx.body.span), cx.param_env, - ty::TraitRef::new( - cx.tcx, - destruct_def_id, - [ - ty::GenericArg::from(ty), - ty::GenericArg::from(cx.tcx.expected_host_effect_param_for_body(cx.def_id())), - ], - ), + ty::TraitRef::new(cx.tcx, destruct_def_id, [ + ty::GenericArg::from(ty), + ty::GenericArg::from(cx.tcx.expected_host_effect_param_for_body(cx.def_id())), + ]), ); let infcx = cx.tcx.infer_ctxt().build(); diff --git a/compiler/rustc_const_eval/src/check_consts/resolver.rs b/compiler/rustc_const_eval/src/check_consts/resolver.rs index 681184f7fbc..eb5024c36f4 100644 --- a/compiler/rustc_const_eval/src/check_consts/resolver.rs +++ b/compiler/rustc_const_eval/src/check_consts/resolver.rs @@ -13,7 +13,7 @@ use rustc_mir_dataflow::fmt::DebugWithContext; use rustc_mir_dataflow::{Analysis, AnalysisDomain, JoinSemiLattice}; -use super::{qualifs, ConstCx, Qualif}; +use super::{ConstCx, Qualif, qualifs}; /// A `Visitor` that propagates qualifs between locals. This defines the transfer function of /// `FlowSensitiveAnalysis`. diff --git a/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs b/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs index aa7449e8ad2..ed1c912e6cb 100644 --- a/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/dummy_machine.rs @@ -6,7 +6,7 @@ use rustc_span::def_id::DefId; use crate::interpret::{ - self, throw_machine_stop, HasStaticRootDefId, ImmTy, Immediate, InterpCx, PointerArithmetic, + self, HasStaticRootDefId, ImmTy, Immediate, InterpCx, PointerArithmetic, throw_machine_stop, }; /// Macro for machine-specific `InterpError` without allocation. diff --git a/compiler/rustc_const_eval/src/const_eval/error.rs b/compiler/rustc_const_eval/src/const_eval/error.rs index 25b32785b7d..fd05664e2f2 100644 --- a/compiler/rustc_const_eval/src/const_eval/error.rs +++ b/compiler/rustc_const_eval/src/const_eval/error.rs @@ -1,8 +1,8 @@ use std::mem; use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage, Diagnostic, IntoDiagArg}; -use rustc_middle::mir::interpret::{Provenance, ReportedErrorInfo}; use rustc_middle::mir::AssertKind; +use rustc_middle::mir::interpret::{Provenance, ReportedErrorInfo}; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::layout::LayoutError; use rustc_middle::ty::{ConstInt, TyCtxt}; @@ -11,7 +11,7 @@ use super::CompileTimeMachine; use crate::errors::{self, FrameNote, ReportErrorExt}; use crate::interpret::{ - err_inval, err_machine_stop, ErrorHandled, Frame, InterpError, InterpErrorInfo, MachineStopType, + ErrorHandled, Frame, InterpError, InterpErrorInfo, MachineStopType, err_inval, err_machine_stop, }; /// The CTFE machine has some custom error kinds. diff --git a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs index 337eab7a1c2..a241edbd77a 100644 --- a/compiler/rustc_const_eval/src/const_eval/eval_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/eval_queries.rs @@ -11,18 +11,18 @@ use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::def_id::LocalDefId; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi::{self, Abi}; use tracing::{debug, instrument, trace}; use super::{CanAccessMutGlobal, CompileTimeInterpCx, CompileTimeMachine}; use crate::const_eval::CheckAlignment; use crate::interpret::{ - create_static_alloc, eval_nullary_intrinsic, intern_const_alloc_recursive, throw_exhaust, CtfeValidationMode, GlobalId, Immediate, InternKind, InternResult, InterpCx, InterpError, - InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, StackPopCleanup, + InterpResult, MPlaceTy, MemoryKind, OpTy, RefTracking, StackPopCleanup, create_static_alloc, + eval_nullary_intrinsic, intern_const_alloc_recursive, throw_exhaust, }; -use crate::{errors, CTRL_C_RECEIVED}; +use crate::{CTRL_C_RECEIVED, errors}; // Returns a pointer to where the result lives #[instrument(level = "trace", skip(ecx, body))] diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 6a691abae02..6d74998b7d8 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -6,14 +6,14 @@ use rustc_ast::Mutability; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry}; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir::{self as hir, LangItem, CRATE_HIR_ID}; +use rustc_hir::{self as hir, CRATE_HIR_ID, LangItem}; use rustc_middle::mir::AssertMessage; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::layout::{FnAbiOf, TyAndLayout}; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::{bug, mir}; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, sym}; use rustc_target::abi::{Align, Size}; use rustc_target::spec::abi::Abi as CallAbi; use tracing::debug; @@ -22,10 +22,10 @@ use crate::errors::{LongRunning, LongRunningWarn}; use crate::fluent_generated as fluent; use crate::interpret::{ - self, compile_time_machine, err_ub, throw_exhaust, throw_inval, throw_ub_custom, throw_unsup, - throw_unsup_format, AllocId, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame, - GlobalAlloc, ImmTy, InterpCx, InterpResult, MPlaceTy, OpTy, Pointer, PointerArithmetic, - RangeSet, Scalar, StackPopCleanup, + self, AllocId, AllocRange, ConstAllocation, CtfeProvenance, FnArg, Frame, GlobalAlloc, ImmTy, + InterpCx, InterpResult, MPlaceTy, OpTy, Pointer, PointerArithmetic, RangeSet, Scalar, + StackPopCleanup, compile_time_machine, err_ub, throw_exhaust, throw_inval, throw_ub_custom, + throw_unsup, throw_unsup_format, }; /// When hitting this many interpreted terminators we emit a deny by default lint @@ -203,8 +203,8 @@ fn location_triple_for_span(&self, span: Span) -> (Symbol, u32, u32) { let topmost = span.ctxt().outer_expn().expansion_cause().unwrap_or(span); let caller = self.tcx.sess.source_map().lookup_char_pos(topmost.lo()); - use rustc_session::config::RemapPathScopeComponents; use rustc_session::RemapFileNameExt; + use rustc_session::config::RemapPathScopeComponents; ( Symbol::intern( &caller @@ -641,7 +641,14 @@ fn increment_const_eval_counter(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult< // current number of evaluated terminators is a power of 2. The latter gives us a cheap // way to implement exponential backoff. let span = ecx.cur_span(); - ecx.tcx.dcx().emit_warn(LongRunningWarn { span, item_span: ecx.tcx.span }); + // We store a unique number in `force_duplicate` to evade `-Z deduplicate-diagnostics`. + // `new_steps` is guaranteed to be unique because `ecx.machine.num_evaluated_steps` is + // always increasing. + ecx.tcx.dcx().emit_warn(LongRunningWarn { + span, + item_span: ecx.tcx.span, + force_duplicate: new_steps, + }); } } diff --git a/compiler/rustc_const_eval/src/const_eval/mod.rs b/compiler/rustc_const_eval/src/const_eval/mod.rs index 8add23ed22f..48aeee2e6f0 100644 --- a/compiler/rustc_const_eval/src/const_eval/mod.rs +++ b/compiler/rustc_const_eval/src/const_eval/mod.rs @@ -7,7 +7,7 @@ use rustc_target::abi::VariantIdx; use tracing::instrument; -use crate::interpret::{format_interp_error, InterpCx}; +use crate::interpret::{InterpCx, format_interp_error}; mod dummy_machine; mod error; @@ -16,12 +16,12 @@ mod machine; mod valtrees; -pub use dummy_machine::*; -pub use error::*; -pub use eval_queries::*; -pub use fn_queries::*; -pub use machine::*; -pub(crate) use valtrees::{eval_to_valtree, valtree_to_const_value}; +pub use self::dummy_machine::*; +pub use self::error::*; +pub use self::eval_queries::*; +pub use self::fn_queries::*; +pub use self::machine::*; +pub(crate) use self::valtrees::{eval_to_valtree, valtree_to_const_value}; // We forbid type-level constants that contain more than `VALTREE_MAX_NODES` nodes. const VALTREE_MAX_NODES: usize = 100000; diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index 8351a6af25b..a11d491bdd2 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -9,12 +9,12 @@ use super::eval_queries::{mk_eval_cx_to_read_const_val, op_to_const}; use super::machine::CompileTimeInterpCx; -use super::{ValTreeCreationError, ValTreeCreationResult, VALTREE_MAX_NODES}; +use super::{VALTREE_MAX_NODES, ValTreeCreationError, ValTreeCreationResult}; use crate::const_eval::CanAccessMutGlobal; use crate::errors::MaxNumNodesInConstErr; use crate::interpret::{ - intern_const_alloc_recursive, ImmTy, Immediate, InternKind, MPlaceTy, MemPlaceMeta, MemoryKind, - PlaceTy, Projectable, Scalar, + ImmTy, Immediate, InternKind, MPlaceTy, MemPlaceMeta, MemoryKind, PlaceTy, Projectable, Scalar, + intern_const_alloc_recursive, }; #[instrument(skip(ecx), level = "debug")] diff --git a/compiler/rustc_const_eval/src/errors.rs b/compiler/rustc_const_eval/src/errors.rs index b66b5c0a00a..c38d7f3d03c 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -15,8 +15,8 @@ }; use rustc_middle::ty::{self, Mutability, Ty}; use rustc_span::Span; -use rustc_target::abi::call::AdjustForForeignAbiError; use rustc_target::abi::WrappingRange; +use rustc_target::abi::call::AdjustForForeignAbiError; use crate::interpret::InternKind; @@ -209,6 +209,8 @@ pub struct LongRunningWarn { pub span: Span, #[help] pub item_span: Span, + // Used for evading `-Z deduplicate-diagnostics`. + pub force_duplicate: usize, } #[derive(Subdiagnostic)] @@ -508,13 +510,10 @@ fn add_args(self, diag: &mut Diag<'_, G>) { } 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 0f2b22f035b..f5a0a2c0ee3 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -14,9 +14,9 @@ use tracing::{info, instrument, trace}; use super::{ - throw_ub, throw_ub_custom, throw_unsup_format, CtfeProvenance, FnVal, ImmTy, InterpCx, - InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, Projectable, Provenance, ReturnAction, Scalar, - StackPopCleanup, StackPopInfo, + CtfeProvenance, FnVal, ImmTy, InterpCx, InterpResult, MPlaceTy, Machine, OpTy, PlaceTy, + Projectable, Provenance, ReturnAction, Scalar, StackPopCleanup, StackPopInfo, throw_ub, + throw_ub_custom, throw_unsup_format, }; use crate::fluent_generated as fluent; @@ -221,7 +221,6 @@ fn layout_compat( } // Fall back to exact equality. - // FIXME: We are missing the rules for "repr(C) wrapping compatible types". Ok(caller == callee) } @@ -234,6 +233,7 @@ fn check_argument_compat( // so we implement a type-based check that reflects the guaranteed rules for ABI compatibility. if self.layout_compat(caller_abi.layout, callee_abi.layout)? { // Ensure that our checks imply actual ABI compatibility for this concrete call. + // (This can fail e.g. if `#[rustc_nonnull_optimization_guaranteed]` is used incorrectly.) assert!(caller_abi.eq_abi(callee_abi)); Ok(true) } else { @@ -364,13 +364,10 @@ pub fn init_stack_frame( "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!( @@ -853,13 +850,10 @@ pub(super) fn return_from_current_stack_frame( ); // 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/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index e8c9f145eea..198aa1bbd5b 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -2,8 +2,8 @@ use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::{Float, FloatConvert}; -use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar}; use rustc_middle::mir::CastKind; +use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar}; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::layout::{IntegerExt, LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, FloatTy, Ty}; @@ -14,7 +14,7 @@ use super::util::ensure_monomorphic_enough; use super::{ - err_inval, throw_ub, throw_ub_custom, FnVal, ImmTy, Immediate, InterpCx, Machine, OpTy, PlaceTy, + FnVal, ImmTy, Immediate, InterpCx, Machine, OpTy, PlaceTy, err_inval, throw_ub, throw_ub_custom, }; use crate::fluent_generated as fluent; diff --git a/compiler/rustc_const_eval/src/interpret/discriminant.rs b/compiler/rustc_const_eval/src/interpret/discriminant.rs index de93ed85704..3bab2b3261e 100644 --- a/compiler/rustc_const_eval/src/interpret/discriminant.rs +++ b/compiler/rustc_const_eval/src/interpret/discriminant.rs @@ -7,7 +7,7 @@ use tracing::{instrument, trace}; use super::{ - err_ub, throw_ub, ImmTy, InterpCx, InterpResult, Machine, Projectable, Scalar, Writeable, + ImmTy, InterpCx, InterpResult, Machine, Projectable, Scalar, Writeable, err_ub, throw_ub, }; impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 16d40fcceb6..f4c4a6fb0bf 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -1,8 +1,8 @@ use either::{Left, Right}; use rustc_errors::DiagCtxtHandle; use rustc_hir::def_id::DefId; -use rustc_infer::infer::at::ToTrace; use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::at::ToTrace; use rustc_infer::traits::ObligationCause; use rustc_middle::mir::interpret::{ErrorHandled, InvalidMetaKind, ReportedErrorInfo}; use rustc_middle::query::TyCtxtAt; @@ -19,11 +19,11 @@ use tracing::{debug, instrument, trace}; use super::{ - err_inval, throw_inval, throw_ub, throw_ub_custom, Frame, FrameInfo, GlobalId, InterpErrorInfo, - InterpResult, MPlaceTy, Machine, MemPlaceMeta, Memory, OpTy, Place, PlaceTy, PointerArithmetic, - Projectable, Provenance, + Frame, FrameInfo, GlobalId, InterpErrorInfo, InterpResult, MPlaceTy, Machine, MemPlaceMeta, + Memory, OpTy, Place, PlaceTy, PointerArithmetic, Projectable, Provenance, err_inval, + throw_inval, throw_ub, throw_ub_custom, }; -use crate::{fluent_generated as fluent, util, ReportErrorExt}; +use crate::{ReportErrorExt, fluent_generated as fluent, util}; pub struct InterpCx<'tcx, M: Machine<'tcx>> { /// Stores the `Machine` instance. diff --git a/compiler/rustc_const_eval/src/interpret/intern.rs b/compiler/rustc_const_eval/src/interpret/intern.rs index 5df989b4c1d..81659df7c53 100644 --- a/compiler/rustc_const_eval/src/interpret/intern.rs +++ b/compiler/rustc_const_eval/src/interpret/intern.rs @@ -26,7 +26,7 @@ use rustc_span::sym; use tracing::{instrument, trace}; -use super::{err_ub, AllocId, Allocation, InterpCx, MPlaceTy, Machine, MemoryKind, PlaceTy}; +use super::{AllocId, Allocation, InterpCx, MPlaceTy, Machine, MemoryKind, PlaceTy, err_ub}; use crate::const_eval; use crate::errors::NestedStaticInThreadLocal; @@ -100,11 +100,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/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index b3f4fd5e2a1..e1fd8bea1f3 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -9,16 +9,16 @@ use rustc_middle::ty::layout::{LayoutOf as _, TyAndLayout, ValidityRequirement}; use rustc_middle::ty::{GenericArgsRef, Ty, TyCtxt}; use rustc_middle::{bug, ty}; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; use rustc_target::abi::Size; use tracing::trace; use super::memory::MemoryKind; use super::util::ensure_monomorphic_enough; use super::{ - err_inval, err_ub_custom, err_unsup_format, throw_inval, throw_ub_custom, throw_ub_format, Allocation, CheckInAllocMsg, ConstAllocation, GlobalId, ImmTy, InterpCx, InterpResult, - MPlaceTy, Machine, OpTy, Pointer, PointerArithmetic, Provenance, Scalar, + MPlaceTy, Machine, OpTy, Pointer, PointerArithmetic, Provenance, Scalar, err_inval, + err_ub_custom, err_unsup_format, throw_inval, throw_ub_custom, throw_ub_format, }; use crate::fluent_generated as fluent; diff --git a/compiler/rustc_const_eval/src/interpret/machine.rs b/compiler/rustc_const_eval/src/interpret/machine.rs index 67c99934059..a809f74e8eb 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -9,18 +9,18 @@ use rustc_apfloat::{Float, FloatConvert}; use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_middle::query::TyCtxtAt; -use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::Ty; +use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::{mir, ty}; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; use rustc_target::abi::{Align, Size}; use rustc_target::spec::abi::Abi as CallAbi; use super::{ - throw_unsup, throw_unsup_format, AllocBytes, AllocId, AllocKind, AllocRange, Allocation, - ConstAllocation, CtfeProvenance, FnArg, Frame, ImmTy, InterpCx, InterpResult, MPlaceTy, - MemoryKind, Misalignment, OpTy, PlaceTy, Pointer, Provenance, RangeSet, CTFE_ALLOC_SALT, + AllocBytes, AllocId, AllocKind, AllocRange, Allocation, CTFE_ALLOC_SALT, ConstAllocation, + CtfeProvenance, FnArg, Frame, ImmTy, InterpCx, InterpResult, MPlaceTy, MemoryKind, + Misalignment, OpTy, PlaceTy, Pointer, Provenance, RangeSet, throw_unsup, throw_unsup_format, }; /// Data returned by [`Machine::after_stack_pop`], and consumed by diff --git a/compiler/rustc_const_eval/src/interpret/memory.rs b/compiler/rustc_const_eval/src/interpret/memory.rs index b1d1dab7c16..e5fdf592ec9 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -21,10 +21,10 @@ use tracing::{debug, instrument, trace}; use super::{ - alloc_range, err_ub, err_ub_custom, throw_ub, throw_ub_custom, throw_unsup, throw_unsup_format, AllocBytes, AllocId, AllocMap, AllocRange, Allocation, CheckAlignMsg, CheckInAllocMsg, CtfeProvenance, GlobalAlloc, InterpCx, InterpResult, Machine, MayLeak, Misalignment, Pointer, - PointerArithmetic, Provenance, Scalar, + PointerArithmetic, Provenance, Scalar, alloc_range, err_ub, err_ub_custom, throw_ub, + throw_ub_custom, throw_unsup, throw_unsup_format, }; use crate::fluent_generated as fluent; diff --git a/compiler/rustc_const_eval/src/interpret/mod.rs b/compiler/rustc_const_eval/src/interpret/mod.rs index 561d681f804..5e84626f77e 100644 --- a/compiler/rustc_const_eval/src/interpret/mod.rs +++ b/compiler/rustc_const_eval/src/interpret/mod.rs @@ -19,18 +19,18 @@ mod validity; mod visitor; -use eval_context::{from_known_layout, mir_assign_valid_types}; #[doc(no_inline)] pub use rustc_middle::mir::interpret::*; // have all the `interpret` symbols in one place: here pub use self::call::FnArg; -pub use self::eval_context::{format_interp_error, InterpCx}; +pub use self::eval_context::{InterpCx, format_interp_error}; +use self::eval_context::{from_known_layout, mir_assign_valid_types}; pub use self::intern::{ - intern_const_alloc_for_constprop, intern_const_alloc_recursive, HasStaticRootDefId, InternKind, - InternResult, + HasStaticRootDefId, InternKind, InternResult, intern_const_alloc_for_constprop, + intern_const_alloc_recursive, }; pub(crate) use self::intrinsics::eval_nullary_intrinsic; -pub use self::machine::{compile_time_machine, AllocMap, Machine, MayLeak, ReturnAction}; +pub use self::machine::{AllocMap, Machine, MayLeak, ReturnAction, compile_time_machine}; pub use self::memory::{AllocKind, AllocRef, AllocRefMut, FnVal, Memory, MemoryKind}; use self::operand::Operand; pub use self::operand::{ImmTy, Immediate, OpTy}; diff --git a/compiler/rustc_const_eval/src/interpret/operand.rs b/compiler/rustc_const_eval/src/interpret/operand.rs index ead3ef6861a..31ee3e6519a 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -14,9 +14,9 @@ use tracing::trace; use super::{ - alloc_range, err_ub, from_known_layout, mir_assign_valid_types, throw_ub, CtfeProvenance, - InterpCx, InterpResult, MPlaceTy, Machine, MemPlace, MemPlaceMeta, OffsetMode, PlaceTy, - Pointer, Projectable, Provenance, Scalar, + CtfeProvenance, InterpCx, InterpResult, MPlaceTy, Machine, MemPlace, MemPlaceMeta, OffsetMode, + PlaceTy, Pointer, Projectable, Provenance, Scalar, alloc_range, err_ub, from_known_layout, + mir_assign_valid_types, throw_ub, }; /// An `Immediate` represents a single immediate self-contained Rust value. diff --git a/compiler/rustc_const_eval/src/interpret/operator.rs b/compiler/rustc_const_eval/src/interpret/operator.rs index 7d32fcbb664..863b330a74c 100644 --- a/compiler/rustc_const_eval/src/interpret/operator.rs +++ b/compiler/rustc_const_eval/src/interpret/operator.rs @@ -1,7 +1,7 @@ use either::Either; use rustc_apfloat::{Float, FloatConvert}; -use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar}; use rustc_middle::mir::NullOp; +use rustc_middle::mir::interpret::{InterpResult, PointerArithmetic, Scalar}; use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, FloatTy, ScalarInt, Ty}; use rustc_middle::{bug, mir, span_bug}; @@ -9,7 +9,7 @@ use rustc_target::abi::Size; use tracing::trace; -use super::{throw_ub, ImmTy, InterpCx, Machine, MemPlaceMeta}; +use super::{ImmTy, InterpCx, Machine, MemPlaceMeta, throw_ub}; impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { fn three_way_compare(&self, lhs: T, rhs: T) -> ImmTy<'tcx, M::Provenance> { diff --git a/compiler/rustc_const_eval/src/interpret/place.rs b/compiler/rustc_const_eval/src/interpret/place.rs index e398c4c0742..32f90254a94 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -6,16 +6,16 @@ use either::{Either, Left, Right}; use rustc_ast::Mutability; -use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::Ty; +use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::{bug, mir, span_bug}; use rustc_target::abi::{Abi, Align, HasDataLayout, Size}; use tracing::{instrument, trace}; use super::{ - alloc_range, mir_assign_valid_types, AllocRef, AllocRefMut, CheckAlignMsg, CtfeProvenance, - ImmTy, Immediate, InterpCx, InterpResult, Machine, MemoryKind, Misalignment, OffsetMode, OpTy, - Operand, Pointer, Projectable, Provenance, Scalar, + AllocRef, AllocRefMut, CheckAlignMsg, CtfeProvenance, ImmTy, Immediate, InterpCx, InterpResult, + Machine, MemoryKind, Misalignment, OffsetMode, OpTy, Operand, Pointer, Projectable, Provenance, + Scalar, alloc_range, mir_assign_valid_types, }; #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)] diff --git a/compiler/rustc_const_eval/src/interpret/projection.rs b/compiler/rustc_const_eval/src/interpret/projection.rs index 58ce44e4014..621afdb1050 100644 --- a/compiler/rustc_const_eval/src/interpret/projection.rs +++ b/compiler/rustc_const_eval/src/interpret/projection.rs @@ -10,15 +10,15 @@ use std::marker::PhantomData; use std::ops::Range; -use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::ty::Ty; +use rustc_middle::ty::layout::{LayoutOf, TyAndLayout}; use rustc_middle::{bug, mir, span_bug, ty}; use rustc_target::abi::{self, Size, VariantIdx}; use tracing::{debug, instrument}; use super::{ - err_ub, throw_ub, throw_unsup, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy, - Provenance, Scalar, + InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, OpTy, Provenance, Scalar, err_ub, + throw_ub, throw_unsup, }; /// Describes the constraints placed on offset-projections. diff --git a/compiler/rustc_const_eval/src/interpret/stack.rs b/compiler/rustc_const_eval/src/interpret/stack.rs index db418c82f66..15868f1b02d 100644 --- a/compiler/rustc_const_eval/src/interpret/stack.rs +++ b/compiler/rustc_const_eval/src/interpret/stack.rs @@ -15,9 +15,9 @@ use tracing::{info_span, instrument, trace}; use super::{ - from_known_layout, throw_ub, throw_unsup, AllocId, CtfeProvenance, Immediate, InterpCx, - InterpResult, MPlaceTy, Machine, MemPlace, MemPlaceMeta, MemoryKind, Operand, Pointer, - Provenance, ReturnAction, Scalar, + AllocId, CtfeProvenance, Immediate, InterpCx, InterpResult, MPlaceTy, Machine, MemPlace, + MemPlaceMeta, MemoryKind, Operand, Pointer, Provenance, ReturnAction, Scalar, + from_known_layout, throw_ub, throw_unsup, }; use crate::errors; diff --git a/compiler/rustc_const_eval/src/interpret/step.rs b/compiler/rustc_const_eval/src/interpret/step.rs index 70cfba1922c..8e2367e0d21 100644 --- a/compiler/rustc_const_eval/src/interpret/step.rs +++ b/compiler/rustc_const_eval/src/interpret/step.rs @@ -9,12 +9,12 @@ use rustc_middle::{bug, mir, span_bug}; use rustc_span::source_map::Spanned; use rustc_target::abi::call::FnAbi; -use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx}; use tracing::{info, instrument, trace}; use super::{ - throw_ub, FnArg, FnVal, ImmTy, Immediate, InterpCx, InterpResult, Machine, MemPlaceMeta, - PlaceTy, Projectable, Scalar, + FnArg, FnVal, ImmTy, Immediate, InterpCx, InterpResult, Machine, MemPlaceMeta, PlaceTy, + Projectable, Scalar, throw_ub, }; use crate::util; diff --git a/compiler/rustc_const_eval/src/interpret/traits.rs b/compiler/rustc_const_eval/src/interpret/traits.rs index cd4faf06655..b5eef0fd8c9 100644 --- a/compiler/rustc_const_eval/src/interpret/traits.rs +++ b/compiler/rustc_const_eval/src/interpret/traits.rs @@ -5,7 +5,7 @@ use tracing::trace; use super::util::ensure_monomorphic_enough; -use super::{throw_ub, InterpCx, MPlaceTy, Machine, MemPlaceMeta, OffsetMode, Projectable}; +use super::{InterpCx, MPlaceTy, Machine, MemPlaceMeta, OffsetMode, Projectable, throw_ub}; impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// Creates a dynamic vtable for the given type and vtable origin. This is used only for diff --git a/compiler/rustc_const_eval/src/interpret/util.rs b/compiler/rustc_const_eval/src/interpret/util.rs index 490355f416c..2d53badf0f9 100644 --- a/compiler/rustc_const_eval/src/interpret/util.rs +++ b/compiler/rustc_const_eval/src/interpret/util.rs @@ -9,7 +9,7 @@ }; use tracing::debug; -use super::{throw_inval, InterpCx, MPlaceTy, MemoryKind}; +use super::{InterpCx, MPlaceTy, MemoryKind, throw_inval}; use crate::const_eval::{CompileTimeInterpCx, CompileTimeMachine, InterpretationResult}; /// Checks whether a type contains generic parameters which must be instantiated. diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index b20df7ac9c1..ff3c6120f0c 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -17,12 +17,12 @@ use rustc_middle::bug; use rustc_middle::mir::interpret::ValidationErrorKind::{self, *}; use rustc_middle::mir::interpret::{ - alloc_range, ExpectedKind, InterpError, InvalidMetaKind, Misalignment, PointerKind, Provenance, - UnsupportedOpInfo, ValidationErrorInfo, + ExpectedKind, InterpError, InvalidMetaKind, Misalignment, PointerKind, Provenance, + UnsupportedOpInfo, ValidationErrorInfo, alloc_range, }; use rustc_middle::ty::layout::{LayoutCx, LayoutOf, TyAndLayout}; use rustc_middle::ty::{self, Ty}; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; use rustc_target::abi::{ Abi, FieldIdx, FieldsShape, Scalar as ScalarAbi, Size, VariantIdx, Variants, WrappingRange, }; @@ -30,9 +30,9 @@ use super::machine::AllocMap; use super::{ - err_ub, format_interp_error, throw_ub, AllocId, AllocKind, CheckInAllocMsg, GlobalAlloc, ImmTy, - Immediate, InterpCx, InterpResult, MPlaceTy, Machine, MemPlaceMeta, PlaceTy, Pointer, - Projectable, Scalar, ValueVisitor, + AllocId, AllocKind, CheckInAllocMsg, GlobalAlloc, ImmTy, Immediate, InterpCx, InterpResult, + MPlaceTy, Machine, MemPlaceMeta, PlaceTy, Pointer, Projectable, Scalar, ValueVisitor, err_ub, + format_interp_error, throw_ub, }; // for the validation errors @@ -803,10 +803,10 @@ fn visit_scalar( 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 Ok(()); } @@ -816,10 +816,10 @@ fn visit_scalar( } 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 + }) } } }; @@ -827,10 +827,11 @@ fn visit_scalar( if valid_range.contains(bits) { 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_const_eval/src/interpret/visitor.rs b/compiler/rustc_const_eval/src/interpret/visitor.rs index d8af67bd0e7..d004a3f0892 100644 --- a/compiler/rustc_const_eval/src/interpret/visitor.rs +++ b/compiler/rustc_const_eval/src/interpret/visitor.rs @@ -10,7 +10,7 @@ use rustc_target::abi::{FieldIdx, FieldsShape, VariantIdx, Variants}; use tracing::trace; -use super::{throw_inval, InterpCx, MPlaceTy, Machine, Projectable}; +use super::{InterpCx, MPlaceTy, Machine, Projectable, throw_inval}; /// How to traverse a value and what to do when we are at the leaves. pub trait ValueVisitor<'tcx, M: Machine<'tcx>>: Sized { diff --git a/compiler/rustc_const_eval/src/lib.rs b/compiler/rustc_const_eval/src/lib.rs index 73dda81bd29..cbe8a043fba 100644 --- a/compiler/rustc_const_eval/src/lib.rs +++ b/compiler/rustc_const_eval/src/lib.rs @@ -1,6 +1,8 @@ // tidy-alphabetical-start #![allow(internal_features)] #![allow(rustc::diagnostic_outside_of_impl)] +#![cfg_attr(not(bootstrap), feature(unqualified_local_imports))] +#![cfg_attr(not(bootstrap), warn(unqualified_local_imports))] #![doc(rust_logo)] #![feature(assert_matches)] #![feature(box_patterns)] @@ -25,10 +27,11 @@ use std::sync::atomic::AtomicBool; -pub use errors::ReportErrorExt; use rustc_middle::ty; use rustc_middle::util::Providers; +pub use self::errors::ReportErrorExt; + rustc_fluent_macro::fluent_messages! { "../messages.ftl" } pub fn provide(providers: &mut Providers) { diff --git a/compiler/rustc_const_eval/src/util/caller_location.rs b/compiler/rustc_const_eval/src/util/caller_location.rs index eb185bee5c0..7f4c36835e4 100644 --- a/compiler/rustc_const_eval/src/util/caller_location.rs +++ b/compiler/rustc_const_eval/src/util/caller_location.rs @@ -6,7 +6,7 @@ use rustc_span::symbol::Symbol; use tracing::trace; -use crate::const_eval::{mk_eval_cx_to_read_const_val, CanAccessMutGlobal, CompileTimeInterpCx}; +use crate::const_eval::{CanAccessMutGlobal, CompileTimeInterpCx, mk_eval_cx_to_read_const_val}; use crate::interpret::*; /// Allocate a `const core::panic::Location` with the provided filename and line/column numbers. diff --git a/compiler/rustc_data_structures/src/fingerprint.rs b/compiler/rustc_data_structures/src/fingerprint.rs index efc56dc9337..16c66824c5b 100644 --- a/compiler/rustc_data_structures/src/fingerprint.rs +++ b/compiler/rustc_data_structures/src/fingerprint.rs @@ -3,7 +3,7 @@ use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use crate::stable_hasher::{ - impl_stable_traits_for_trivial_type, FromStableHash, Hash64, StableHasherHash, + FromStableHash, Hash64, StableHasherHash, impl_stable_traits_for_trivial_type, }; #[cfg(test)] diff --git a/compiler/rustc_data_structures/src/flock/windows.rs b/compiler/rustc_data_structures/src/flock/windows.rs index 0d76df27a0a..9739e501272 100644 --- a/compiler/rustc_data_structures/src/flock/windows.rs +++ b/compiler/rustc_data_structures/src/flock/windows.rs @@ -6,8 +6,8 @@ use tracing::debug; use windows::Win32::Foundation::{ERROR_INVALID_FUNCTION, HANDLE}; use windows::Win32::Storage::FileSystem::{ - LockFileEx, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, LOCKFILE_EXCLUSIVE_LOCK, - LOCKFILE_FAIL_IMMEDIATELY, LOCK_FILE_FLAGS, + FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, LOCK_FILE_FLAGS, LOCKFILE_EXCLUSIVE_LOCK, + LOCKFILE_FAIL_IMMEDIATELY, LockFileEx, }; use windows::Win32::System::IO::OVERLAPPED; diff --git a/compiler/rustc_data_structures/src/graph/dominators/tests.rs b/compiler/rustc_data_structures/src/graph/dominators/tests.rs index 6c078ca7c6e..ef82193a4b9 100644 --- a/compiler/rustc_data_structures/src/graph/dominators/tests.rs +++ b/compiler/rustc_data_structures/src/graph/dominators/tests.rs @@ -15,10 +15,17 @@ 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 @@ -33,10 +40,19 @@ 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); } @@ -53,24 +69,21 @@ 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 32a6d9ec881..7a240f4e58b 100644 --- a/compiler/rustc_data_structures/src/graph/implementation/tests.rs +++ b/compiler/rustc_data_structures/src/graph/implementation/tests.rs @@ -110,13 +110,10 @@ 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 373f87bfdbc..7c876c82af2 100644 --- a/compiler/rustc_data_structures/src/graph/scc/tests.rs +++ b/compiler/rustc_data_structures/src/graph/scc/tests.rs @@ -326,49 +326,46 @@ 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 a58c6ee1bcc..8391e98ba8b 100644 --- a/compiler/rustc_data_structures/src/obligation_forest/tests.rs +++ b/compiler/rustc_data_structures/src/obligation_forest/tests.rs @@ -347,10 +347,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/owned_slice/tests.rs b/compiler/rustc_data_structures/src/owned_slice/tests.rs index 324b8ecf2d3..e9ef7ea5afc 100644 --- a/compiler/rustc_data_structures/src/owned_slice/tests.rs +++ b/compiler/rustc_data_structures/src/owned_slice/tests.rs @@ -1,9 +1,9 @@ use std::ops::Deref; -use std::sync::atomic::{self, AtomicBool}; use std::sync::Arc; +use std::sync::atomic::{self, AtomicBool}; use crate::defer; -use crate::owned_slice::{slice_owned, try_slice_owned, OwnedSlice}; +use crate::owned_slice::{OwnedSlice, slice_owned, try_slice_owned}; #[test] fn smoke() { diff --git a/compiler/rustc_data_structures/src/sharded.rs b/compiler/rustc_data_structures/src/sharded.rs index 03aa1d8f678..d0b6fe2bc6f 100644 --- a/compiler/rustc_data_structures/src/sharded.rs +++ b/compiler/rustc_data_structures/src/sharded.rs @@ -8,7 +8,7 @@ use crate::fx::{FxHashMap, FxHasher}; #[cfg(parallel_compiler)] -use crate::sync::{is_dyn_thread_safe, CacheAligned}; +use crate::sync::{CacheAligned, is_dyn_thread_safe}; use crate::sync::{Lock, LockGuard, Mode}; // 32 shards is sufficient to reduce contention on an 8-core Ryzen 7 1700, diff --git a/compiler/rustc_data_structures/src/stable_hasher.rs b/compiler/rustc_data_structures/src/stable_hasher.rs index 9673f94d7a4..0872bd2c9ac 100644 --- a/compiler/rustc_data_structures/src/stable_hasher.rs +++ b/compiler/rustc_data_structures/src/stable_hasher.rs @@ -14,7 +14,7 @@ FromStableHash, SipHasher128Hash as StableHasherHash, StableSipHasher128 as StableHasher, }; -pub use crate::hashes::{Hash128, Hash64}; +pub use crate::hashes::{Hash64, Hash128}; /// Something that implements `HashStable` can be hashed in a way that is /// stable across multiple compilation sessions. diff --git a/compiler/rustc_data_structures/src/sync/lock.rs b/compiler/rustc_data_structures/src/sync/lock.rs index 7cf942685e3..012ee7f900e 100644 --- a/compiler/rustc_data_structures/src/sync/lock.rs +++ b/compiler/rustc_data_structures/src/sync/lock.rs @@ -25,8 +25,8 @@ mod maybe_sync { use std::mem::ManuallyDrop; use std::ops::{Deref, DerefMut}; - use parking_lot::lock_api::RawMutex as _; use parking_lot::RawMutex; + use parking_lot::lock_api::RawMutex as _; use super::Mode; use crate::sync::mode; diff --git a/compiler/rustc_data_structures/src/sync/parallel.rs b/compiler/rustc_data_structures/src/sync/parallel.rs index 2b89431c2ed..c7df19842d6 100644 --- a/compiler/rustc_data_structures/src/sync/parallel.rs +++ b/compiler/rustc_data_structures/src/sync/parallel.rs @@ -4,7 +4,7 @@ #![allow(dead_code)] use std::any::Any; -use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; +use std::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; #[cfg(not(parallel_compiler))] pub use disabled::*; @@ -12,8 +12,8 @@ pub use enabled::*; use parking_lot::Mutex; -use crate::sync::IntoDynSyncSend; use crate::FatalErrorMarker; +use crate::sync::IntoDynSyncSend; /// A guard used to hold panics that occur during a parallel section to later by unwound. /// This is used for the parallel compiler to prevent fatal errors from non-deterministically @@ -102,7 +102,7 @@ pub fn par_map>( #[cfg(parallel_compiler)] mod enabled { - use crate::sync::{mode, parallel_guard, DynSend, DynSync, FromDyn}; + use crate::sync::{DynSend, DynSync, FromDyn, mode, parallel_guard}; /// Runs a list of blocks in parallel. The first block is executed immediately on /// the current thread. Use that for the longest running block. diff --git a/compiler/rustc_data_structures/src/work_queue.rs b/compiler/rustc_data_structures/src/work_queue.rs index 490d7d3ddd5..ca052e2eac6 100644 --- a/compiler/rustc_data_structures/src/work_queue.rs +++ b/compiler/rustc_data_structures/src/work_queue.rs @@ -1,7 +1,7 @@ use std::collections::VecDeque; -use rustc_index::bit_set::BitSet; use rustc_index::Idx; +use rustc_index::bit_set::BitSet; /// A work queue is a handy data structure for tracking work left to /// do. (For example, basic blocks left to process.) It is basically a diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 44a6b03177e..76b7270d4b8 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -24,7 +24,7 @@ use std::fmt::Write as _; use std::fs::{self, File}; use std::io::{self, IsTerminal, Read, Write}; -use std::panic::{self, catch_unwind, PanicHookInfo}; +use std::panic::{self, PanicHookInfo, catch_unwind}; use std::path::PathBuf; use std::process::{self, Command, Stdio}; use std::sync::atomic::{AtomicBool, Ordering}; @@ -37,30 +37,30 @@ use rustc_codegen_ssa::{CodegenErrors, CodegenResults}; use rustc_const_eval::CTRL_C_RECEIVED; use rustc_data_structures::profiling::{ - get_resident_set_size, print_time_passes_entry, TimePassesFormat, + TimePassesFormat, get_resident_set_size, print_time_passes_entry, }; use rustc_errors::emitter::stderr_destination; use rustc_errors::registry::Registry; use rustc_errors::{ - markdown, ColorConfig, DiagCtxt, ErrCode, ErrorGuaranteed, FatalError, PResult, + ColorConfig, DiagCtxt, ErrCode, ErrorGuaranteed, FatalError, PResult, markdown, }; use rustc_feature::find_gated_cfg; use rustc_interface::util::{self, get_codegen_backend}; -use rustc_interface::{interface, passes, Linker, Queries}; +use rustc_interface::{Linker, Queries, interface, passes}; use rustc_lint::unerased_lint_store; use rustc_metadata::creader::MetadataLoader; use rustc_metadata::locator; use rustc_parse::{new_parser_from_file, new_parser_from_source_str, unwrap_or_emit_fatal}; use rustc_session::config::{ - nightly_options, ErrorOutputType, Input, OutFileName, OutputType, UnstableOptions, CG_OPTIONS, - Z_OPTIONS, + CG_OPTIONS, ErrorOutputType, Input, OutFileName, OutputType, UnstableOptions, Z_OPTIONS, + nightly_options, }; use rustc_session::getopts::{self, Matches}; use rustc_session::lint::{Lint, LintId}; use rustc_session::output::collect_crate_types; -use rustc_session::{config, filesearch, EarlyDiagCtxt, Session}; -use rustc_span::source_map::FileLoader; +use rustc_session::{EarlyDiagCtxt, Session, config, filesearch}; use rustc_span::FileName; +use rustc_span::source_map::FileLoader; use rustc_target::json::ToJson; use rustc_target::spec::{Target, TargetTriple}; use time::OffsetDateTime; @@ -410,11 +410,9 @@ fn run_compiler( }); } else { let krate = queries.parse()?; - pretty::print( - sess, - pp_mode, - pretty::PrintExtra::AfterParsing { krate: &*krate.borrow() }, - ); + pretty::print(sess, pp_mode, pretty::PrintExtra::AfterParsing { + krate: &*krate.borrow(), + }); } trace!("finished pretty-printing"); return early_exit(); diff --git a/compiler/rustc_driver_impl/src/pretty.rs b/compiler/rustc_driver_impl/src/pretty.rs index 74225d646bd..0733b8c0b98 100644 --- a/compiler/rustc_driver_impl/src/pretty.rs +++ b/compiler/rustc_driver_impl/src/pretty.rs @@ -8,11 +8,11 @@ use rustc_middle::bug; use rustc_middle::mir::{write_mir_graphviz, write_mir_pretty}; use rustc_middle::ty::{self, TyCtxt}; -use rustc_session::config::{OutFileName, PpHirMode, PpMode, PpSourceMode}; use rustc_session::Session; +use rustc_session::config::{OutFileName, PpHirMode, PpMode, PpSourceMode}; use rustc_smir::rustc_internal::pretty::write_smir_pretty; -use rustc_span::symbol::Ident; use rustc_span::FileName; +use rustc_span::symbol::Ident; use tracing::debug; use {rustc_ast as ast, rustc_hir_pretty as pprust_hir}; diff --git a/compiler/rustc_driver_impl/src/signal_handler.rs b/compiler/rustc_driver_impl/src/signal_handler.rs index 411661824f0..d4f8199390c 100644 --- a/compiler/rustc_driver_impl/src/signal_handler.rs +++ b/compiler/rustc_driver_impl/src/signal_handler.rs @@ -1,7 +1,7 @@ //! Signal handler for rustc //! Primarily used to extract a backtrace from stack overflow -use std::alloc::{alloc, Layout}; +use std::alloc::{Layout, alloc}; use std::{fmt, mem, ptr}; use rustc_interface::util::{DEFAULT_STACK_SIZE, STACK_SIZE}; diff --git a/compiler/rustc_error_messages/src/lib.rs b/compiler/rustc_error_messages/src/lib.rs index e84d7be45d7..2ede7d805fa 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -16,20 +16,20 @@ use std::sync::LazyLock as Lazy; use std::{fmt, fs, io}; -pub use fluent_bundle::types::FluentType; use fluent_bundle::FluentResource; +pub use fluent_bundle::types::FluentType; pub use fluent_bundle::{self, FluentArgs, FluentError, FluentValue}; use fluent_syntax::parser::ParserError; use icu_provider_adapters::fallback::{LocaleFallbackProvider, LocaleFallbacker}; -#[cfg(parallel_compiler)] -use intl_memoizer::concurrent::IntlLangMemoizer; #[cfg(not(parallel_compiler))] use intl_memoizer::IntlLangMemoizer; +#[cfg(parallel_compiler)] +use intl_memoizer::concurrent::IntlLangMemoizer; use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; use rustc_macros::{Decodable, Encodable}; use rustc_span::Span; use tracing::{instrument, trace}; -pub use unic_langid::{langid, LanguageIdentifier}; +pub use unic_langid::{LanguageIdentifier, langid}; pub type FluentBundle = IntoDynSyncSend>; diff --git a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs index 556e6d46f89..f468fbf4497 100644 --- a/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs +++ b/compiler/rustc_errors/src/annotate_snippet_emitter_writer.rs @@ -8,12 +8,12 @@ use annotate_snippets::{Renderer, Snippet}; use rustc_data_structures::sync::Lrc; use rustc_error_messages::FluentArgs; -use rustc_span::source_map::SourceMap; use rustc_span::SourceFile; +use rustc_span::source_map::SourceMap; use crate::emitter::FileWithAnnotatedLines; use crate::snippet::Line; -use crate::translation::{to_fluent_args, Translate}; +use crate::translation::{Translate, to_fluent_args}; use crate::{ CodeSuggestion, DiagInner, DiagMessage, Emitter, ErrCode, FluentBundle, LazyFallbackBundle, Level, MultiSpan, Style, Subdiag, diff --git a/compiler/rustc_errors/src/diagnostic.rs b/compiler/rustc_errors/src/diagnostic.rs index 6b756cff225..4352de3ad25 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -7,12 +7,12 @@ use std::thread::panicking; use rustc_data_structures::fx::FxIndexMap; -use rustc_error_messages::{fluent_value_from_str_list_sep_by_and, FluentValue}; +use rustc_error_messages::{FluentValue, fluent_value_from_str_list_sep_by_and}; use rustc_lint_defs::Applicability; use rustc_macros::{Decodable, Encodable}; use rustc_span::source_map::Spanned; use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::debug; use crate::snippet::Style; diff --git a/compiler/rustc_errors/src/diagnostic_impls.rs b/compiler/rustc_errors/src/diagnostic_impls.rs index 9e3bc3e60b1..19529f06ef1 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -7,9 +7,9 @@ use rustc_ast_pretty::pprust; use rustc_macros::Subdiagnostic; +use rustc_span::Span; use rustc_span::edition::Edition; use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, Symbol}; -use rustc_span::Span; use rustc_target::abi::TargetDataLayoutErrors; use rustc_target::spec::{PanicStrategy, SplitDebuginfo, StackProtector, TargetTriple}; use rustc_type_ir::{ClosureKind, FloatTy}; @@ -17,8 +17,8 @@ use crate::diagnostic::DiagLocation; use crate::{ - fluent_generated as fluent, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, - ErrCode, IntoDiagArg, Level, SubdiagMessageOp, Subdiagnostic, + Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, ErrCode, IntoDiagArg, Level, + SubdiagMessageOp, Subdiagnostic, fluent_generated as fluent, }; pub struct DiagArgFromDisplay<'a>(pub &'a dyn fmt::Display); diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index 3ab371b8057..1dc52c4d0a4 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -8,7 +8,7 @@ //! The output types are defined in `rustc_session::config::ErrorOutputType`. use std::borrow::Cow; -use std::cmp::{max, min, Reverse}; +use std::cmp::{Reverse, max, min}; use std::error::Report; use std::io::prelude::*; use std::io::{self, IsTerminal}; @@ -22,7 +22,7 @@ use rustc_lint_defs::pluralize; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::source_map::SourceMap; -use rustc_span::{char_width, FileLines, FileName, SourceFile, Span}; +use rustc_span::{FileLines, FileName, SourceFile, Span, char_width}; use termcolor::{Buffer, BufferWriter, Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; use tracing::{debug, instrument, trace, warn}; @@ -31,7 +31,7 @@ Annotation, AnnotationColumn, AnnotationType, Line, MultilineAnnotation, Style, StyledString, }; use crate::styled_buffer::StyledBuffer; -use crate::translation::{to_fluent_args, Translate}; +use crate::translation::{Translate, to_fluent_args}; use crate::{ CodeSuggestion, DiagCtxt, DiagInner, DiagMessage, ErrCode, FluentBundle, LazyFallbackBundle, Level, MultiSpan, Subdiag, SubstitutionHighlight, SuggestionStyle, TerminalUrl, diff --git a/compiler/rustc_errors/src/json.rs b/compiler/rustc_errors/src/json.rs index 6a2ecf13f7b..1972a522e39 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -19,19 +19,19 @@ use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; use rustc_error_messages::FluentArgs; use rustc_lint_defs::Applicability; +use rustc_span::Span; use rustc_span::hygiene::ExpnData; use rustc_span::source_map::SourceMap; -use rustc_span::Span; use serde::Serialize; use termcolor::{ColorSpec, WriteColor}; use crate::diagnostic::IsLint; use crate::emitter::{ - should_show_source_code, ColorConfig, Destination, Emitter, HumanEmitter, - HumanReadableErrorType, + ColorConfig, Destination, Emitter, HumanEmitter, HumanReadableErrorType, + should_show_source_code, }; use crate::registry::Registry; -use crate::translation::{to_fluent_args, Translate}; +use crate::translation::{Translate, to_fluent_args}; use crate::{ CodeSuggestion, FluentBundle, LazyFallbackBundle, MultiSpan, SpanLabel, Subdiag, Suggestions, TerminalUrl, diff --git a/compiler/rustc_errors/src/json/tests.rs b/compiler/rustc_errors/src/json/tests.rs index 6af376d7afd..0de555b83d3 100644 --- a/compiler/rustc_errors/src/json/tests.rs +++ b/compiler/rustc_errors/src/json/tests.rs @@ -1,7 +1,7 @@ use std::str; -use rustc_span::source_map::FilePathMapping; use rustc_span::BytePos; +use rustc_span::source_map::FilePathMapping; use serde::Deserialize; use super::*; @@ -69,128 +69,96 @@ 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_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 59866012069..39acacfbe59 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -42,6 +42,7 @@ use std::path::{Path, PathBuf}; use std::{fmt, panic}; +use Level::*; pub use codes::*; pub use diagnostic::{ BugAbort, Diag, DiagArg, DiagArgMap, DiagArgName, DiagArgValue, DiagInner, DiagStyledString, @@ -53,29 +54,28 @@ IndicateAnonymousLifetime, SingleLabelManySpans, }; pub use emitter::ColorConfig; -use emitter::{is_case_difference, is_different, DynEmitter, Emitter}; +use emitter::{DynEmitter, Emitter, is_case_difference, is_different}; use registry::Registry; +use rustc_data_structures::AtomicRef; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::stable_hasher::{Hash128, StableHasher}; use rustc_data_structures::sync::{Lock, Lrc}; -use rustc_data_structures::AtomicRef; pub use rustc_error_messages::{ - fallback_fluent_bundle, fluent_bundle, DiagMessage, FluentBundle, LanguageIdentifier, - LazyFallbackBundle, MultiSpan, SpanLabel, SubdiagMessage, + DiagMessage, FluentBundle, LanguageIdentifier, LazyFallbackBundle, MultiSpan, SpanLabel, + SubdiagMessage, fallback_fluent_bundle, fluent_bundle, }; use rustc_lint_defs::LintExpectationId; -pub use rustc_lint_defs::{pluralize, Applicability}; +pub use rustc_lint_defs::{Applicability, pluralize}; use rustc_macros::{Decodable, Encodable}; +pub use rustc_span::ErrorGuaranteed; pub use rustc_span::fatal_error::{FatalError, FatalErrorMarker}; use rustc_span::source_map::SourceMap; -pub use rustc_span::ErrorGuaranteed; -use rustc_span::{Loc, Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Loc, Span}; pub use snippet::Style; // Used by external projects such as `rust-gpu`. // See https://github.com/rust-lang/rust/pull/115393. pub use termcolor::{Color, ColorSpec, WriteColor}; use tracing::debug; -use Level::*; pub mod annotate_snippet_emitter_writer; pub mod codes; diff --git a/compiler/rustc_errors/src/lock.rs b/compiler/rustc_errors/src/lock.rs index 7557969f374..85199c34a14 100644 --- a/compiler/rustc_errors/src/lock.rs +++ b/compiler/rustc_errors/src/lock.rs @@ -16,11 +16,11 @@ pub(crate) fn acquire_global_lock(name: &str) -> Box { use std::ffi::CString; use std::io; - use windows::core::PCSTR; use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_ABANDONED, WAIT_OBJECT_0}; use windows::Win32::System::Threading::{ - CreateMutexA, ReleaseMutex, WaitForSingleObject, INFINITE, + CreateMutexA, INFINITE, ReleaseMutex, WaitForSingleObject, }; + use windows::core::PCSTR; struct Handle(HANDLE); diff --git a/compiler/rustc_errors/src/tests.rs b/compiler/rustc_errors/src/tests.rs index bfe4c9f2a3a..17a1635bd11 100644 --- a/compiler/rustc_errors/src/tests.rs +++ b/compiler/rustc_errors/src/tests.rs @@ -1,11 +1,11 @@ use rustc_data_structures::sync::{IntoDynSyncSend, Lrc}; use rustc_error_messages::fluent_bundle::resolver::errors::{ReferenceKind, ResolverError}; -use rustc_error_messages::{langid, DiagMessage}; +use rustc_error_messages::{DiagMessage, langid}; +use crate::FluentBundle; use crate::error::{TranslateError, TranslateErrorKind}; use crate::fluent_bundle::*; use crate::translation::Translate; -use crate::FluentBundle; struct Dummy { bundle: FluentBundle, diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 8f9104135cd..d0552a754fe 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -15,8 +15,8 @@ use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, PResult}; use rustc_feature::Features; use rustc_lint_defs::{BufferedEarlyLint, RegisteredTools}; -use rustc_parse::parser::Parser; use rustc_parse::MACRO_ARGUMENTS; +use rustc_parse::parser::Parser; use rustc_session::config::CollapseMacroDebuginfo; use rustc_session::parse::ParseSess; use rustc_session::{Limit, Session}; @@ -24,9 +24,9 @@ use rustc_span::edition::Edition; use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind}; use rustc_span::source_map::SourceMap; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{FileName, Span, DUMMY_SP}; -use smallvec::{smallvec, SmallVec}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, FileName, Span}; +use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; use crate::base::ast::NestedMetaItem; diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 8ecdb551342..b5945759d43 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -1,12 +1,12 @@ use rustc_ast::ptr::P; use rustc_ast::util::literal; use rustc_ast::{ - self as ast, attr, token, AttrVec, BlockCheckMode, Expr, LocalKind, MatchKind, PatKind, UnOp, + self as ast, AttrVec, BlockCheckMode, Expr, LocalKind, MatchKind, PatKind, UnOp, attr, token, }; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, Span}; +use thin_vec::{ThinVec, thin_vec}; use crate::base::ExtCtxt; @@ -152,18 +152,15 @@ pub fn poly_trait_ref(&self, span: Span, path: ast::Path) -> ast::PolyTraitRef { } pub fn trait_bound(&self, path: ast::Path, is_const: bool) -> ast::GenericBound { - ast::GenericBound::Trait( - self.poly_trait_ref(path.span, path), - ast::TraitBoundModifiers { - polarity: ast::BoundPolarity::Positive, - constness: if is_const { - ast::BoundConstness::Maybe(DUMMY_SP) - } else { - ast::BoundConstness::Never - }, - asyncness: ast::BoundAsyncness::Normal, + ast::GenericBound::Trait(self.poly_trait_ref(path.span, path), ast::TraitBoundModifiers { + polarity: ast::BoundPolarity::Positive, + constness: if is_const { + ast::BoundConstness::Maybe(DUMMY_SP) + } else { + ast::BoundConstness::Never }, - ) + asyncness: ast::BoundAsyncness::Normal, + }) } pub fn lifetime(&self, span: Span, ident: Ident) -> ast::Lifetime { @@ -232,14 +229,11 @@ pub fn stmt_item(&self, sp: Span, item: P) -> ast::Stmt { } 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/config.rs b/compiler/rustc_expand/src/config.rs index b0d3fecbb47..32088374277 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -9,14 +9,14 @@ use rustc_attr as attr; use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_feature::{ - AttributeSafety, Features, ACCEPTED_FEATURES, REMOVED_FEATURES, UNSTABLE_FEATURES, + ACCEPTED_FEATURES, AttributeSafety, Features, REMOVED_FEATURES, UNSTABLE_FEATURES, }; use rustc_lint_defs::BuiltinLintDiag; use rustc_parse::validate_attr; -use rustc_session::parse::feature_err; use rustc_session::Session; -use rustc_span::symbol::{sym, Symbol}; +use rustc_session::parse::feature_err; use rustc_span::Span; +use rustc_span::symbol::{Symbol, sym}; use thin_vec::ThinVec; use tracing::instrument; diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 0d56a005f15..079dcee99d3 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -8,7 +8,7 @@ use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter}; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::visit::{self, try_visit, walk_list, AssocCtxt, Visitor, VisitorResult}; +use rustc_ast::visit::{self, AssocCtxt, Visitor, VisitorResult, try_visit, walk_list}; use rustc_ast::{ AssocItemKind, AstNodeWrapper, AttrArgs, AttrStyle, AttrVec, ExprKind, ForeignItemKind, HasAttrs, HasNodeId, Inline, ItemKind, MacStmtStyle, MetaItemKind, ModKind, NestedMetaItem, @@ -23,12 +23,12 @@ AttemptLocalParseRecovery, CommaRecoveryMode, ForceCollect, Parser, RecoverColon, RecoverComma, }; use rustc_parse::validate_attr; -use rustc_session::lint::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS}; use rustc_session::lint::BuiltinLintDiag; +use rustc_session::lint::builtin::{UNUSED_ATTRIBUTES, UNUSED_DOC_COMMENTS}; use rustc_session::parse::feature_err; use rustc_session::{Limit, Session}; use rustc_span::hygiene::SyntaxContext; -use rustc_span::symbol::{sym, Ident}; +use rustc_span::symbol::{Ident, sym}; use rustc_span::{ErrorGuaranteed, FileName, LocalExpnId, Span}; use smallvec::SmallVec; @@ -41,8 +41,10 @@ }; use crate::fluent_generated; use crate::mbe::diagnostics::annotate_err_with_kind; -use crate::module::{mod_dir_path, parse_external_mod, DirOwnership, ParsedExternalMod}; -use crate::placeholders::{placeholder, PlaceholderExpander}; +use crate::module::{ + DirOwnership, ParsedExternalMod, mod_dir_path, mod_file_path_from_attr, parse_external_mod, +}; +use crate::placeholders::{PlaceholderExpander, placeholder}; macro_rules! ast_fragments { ( @@ -1202,8 +1204,14 @@ fn wrap_flat_map_node_walk_flat_map( ecx.current_expansion.dir_ownership, *inline, ); + // If the module was parsed from an external file, recover its path. + // This lets `parse_external_mod` catch cycles if it's self-referential. + let file_path = match inline { + Inline::Yes => None, + Inline::No => mod_file_path_from_attr(ecx.sess, &attrs, &dir_path), + }; node.attrs = attrs; - (None, dir_path, dir_ownership) + (file_path, dir_path, dir_ownership) } ModKind::Unloaded => { // We have an outline `mod foo;` so we need to parse the file. diff --git a/compiler/rustc_expand/src/mbe.rs b/compiler/rustc_expand/src/mbe.rs index 08d4a039454..e5d098f63d6 100644 --- a/compiler/rustc_expand/src/mbe.rs +++ b/compiler/rustc_expand/src/mbe.rs @@ -16,8 +16,8 @@ use rustc_ast::token::{Delimiter, NonterminalKind, Token, TokenKind}; use rustc_ast::tokenstream::{DelimSpacing, DelimSpan}; use rustc_macros::{Decodable, Encodable}; -use rustc_span::symbol::Ident; use rustc_span::Span; +use rustc_span::symbol::Ident; /// Contains the sub-token-trees of a "delimited" token tree such as `(a b c)`. /// The delimiters are not represented explicitly in the `tts` vector. diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 5778f661622..103bbb05e7f 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -12,11 +12,11 @@ use rustc_span::{ErrorGuaranteed, Span}; use tracing::debug; -use super::macro_rules::{parser_from_cx, NoopTracker}; -use crate::expand::{parse_ast_fragment, AstFragmentKind}; +use super::macro_rules::{NoopTracker, parser_from_cx}; +use crate::expand::{AstFragmentKind, parse_ast_fragment}; use crate::mbe::macro_parser::ParseResult::*; use crate::mbe::macro_parser::{MatcherLoc, NamedParseResult, TtParser}; -use crate::mbe::macro_rules::{try_match_macro, Tracker}; +use crate::mbe::macro_rules::{Tracker, try_match_macro}; pub(super) fn failed_to_match_macro( psess: &ParseSess, diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 68eeba6f415..b1d898b6949 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -108,14 +108,14 @@ use std::iter; use rustc_ast::token::{Delimiter, IdentIsRaw, Token, TokenKind}; -use rustc_ast::{NodeId, DUMMY_NODE_ID}; +use rustc_ast::{DUMMY_NODE_ID, NodeId}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::MultiSpan; use rustc_lint_defs::BuiltinLintDiag; use rustc_session::lint::builtin::{META_VARIABLE_MISUSE, MISSING_FRAGMENT_SPECIFIER}; use rustc_session::parse::ParseSess; use rustc_span::edition::Edition; -use rustc_span::symbol::{kw, MacroRulesNormalizedIdent}; +use rustc_span::symbol::{MacroRulesNormalizedIdent, kw}; use rustc_span::{ErrorGuaranteed, Span}; use smallvec::SmallVec; diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index 501a2417fcf..3903203da3d 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -75,16 +75,16 @@ use std::fmt::Display; use std::rc::Rc; +pub(crate) use NamedMatch::*; +pub(crate) use ParseResult::*; use rustc_ast::token::{self, DocComment, NonterminalKind, Token}; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashMap; use rustc_errors::ErrorGuaranteed; use rustc_lint_defs::pluralize; use rustc_parse::parser::{ParseNtResult, Parser}; -use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent}; use rustc_span::Span; -pub(crate) use NamedMatch::*; -pub(crate) use ParseResult::*; +use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent}; use crate::mbe::macro_rules::Tracker; use crate::mbe::{KleeneOp, TokenTree}; diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 256713ef730..f40f99b6ea1 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -8,23 +8,23 @@ use rustc_ast::token::TokenKind::*; use rustc_ast::token::{self, Delimiter, NonterminalKind, Token, TokenKind}; use rustc_ast::tokenstream::{DelimSpan, TokenStream}; -use rustc_ast::{NodeId, DUMMY_NODE_ID}; +use rustc_ast::{DUMMY_NODE_ID, NodeId}; use rustc_ast_pretty::pprust; use rustc_attr::{self as attr, TransparencyError}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_errors::{Applicability, ErrorGuaranteed}; use rustc_feature::Features; +use rustc_lint_defs::BuiltinLintDiag; use rustc_lint_defs::builtin::{ RUST_2021_INCOMPATIBLE_OR_PATTERNS, SEMICOLON_IN_EXPRESSIONS_FROM_MACROS, }; -use rustc_lint_defs::BuiltinLintDiag; use rustc_parse::parser::{ParseNtResult, Parser, Recovery}; -use rustc_session::parse::ParseSess; use rustc_session::Session; +use rustc_session::parse::ParseSess; +use rustc_span::Span; use rustc_span::edition::Edition; use rustc_span::hygiene::Transparency; -use rustc_span::symbol::{kw, sym, Ident, MacroRulesNormalizedIdent}; -use rustc_span::Span; +use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, kw, sym}; use tracing::{debug, instrument, trace, trace_span}; use super::diagnostics; @@ -33,7 +33,7 @@ DummyResult, ExpandResult, ExtCtxt, MacResult, MacroExpanderResult, SyntaxExtension, SyntaxExtensionKind, TTMacroExpander, }; -use crate::expand::{ensure_complete_parse, parse_ast_fragment, AstFragment, AstFragmentKind}; +use crate::expand::{AstFragment, AstFragmentKind, ensure_complete_parse, parse_ast_fragment}; use crate::mbe; use crate::mbe::diagnostics::{annotate_doc_comment, parse_failure_msg}; use crate::mbe::macro_check; @@ -408,35 +408,29 @@ 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(def.span, lhs_nm, tt_spec), - mbe::TokenTree::token(token::FatArrow, def.span), - mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec), - ], - separator: Some(Token::new( - if macro_rules { token::Semi } else { token::Comma }, - def.span, - )), - kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span), - num_captures: 2, - }, - ), + mbe::TokenTree::Sequence(DelimSpan::dummy(), mbe::SequenceRepetition { + tts: vec![ + mbe::TokenTree::MetaVarDecl(def.span, lhs_nm, tt_spec), + mbe::TokenTree::token(token::FatArrow, def.span), + mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec), + ], + separator: Some(Token::new( + if macro_rules { token::Semi } else { token::Comma }, + def.span, + )), + kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.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 }, - def.span, - )], - separator: None, - kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.span), - num_captures: 0, - }, - ), + mbe::TokenTree::Sequence(DelimSpan::dummy(), mbe::SequenceRepetition { + tts: vec![mbe::TokenTree::token( + if macro_rules { token::Semi } else { token::Comma }, + def.span, + )], + separator: None, + kleene: mbe::KleeneToken::new(mbe::KleeneOp::ZeroOrMore, def.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 5df0aebfe57..f0a6c841f31 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -1,13 +1,13 @@ use rustc_ast::token::NtExprKind::*; use rustc_ast::token::{self, Delimiter, IdentIsRaw, NonterminalKind, Token}; -use rustc_ast::{tokenstream, NodeId}; +use rustc_ast::{NodeId, tokenstream}; use rustc_ast_pretty::pprust; use rustc_feature::Features; -use rustc_session::parse::feature_err; use rustc_session::Session; -use rustc_span::edition::Edition; -use rustc_span::symbol::{kw, sym, Ident}; +use rustc_session::parse::feature_err; use rustc_span::Span; +use rustc_span::edition::Edition; +use rustc_span::symbol::{Ident, kw, sym}; use crate::errors; use crate::mbe::macro_parser::count_metavar_decls; @@ -207,10 +207,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 { @@ -263,10 +263,12 @@ 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` @@ -287,10 +289,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); } @@ -315,14 +317,12 @@ 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_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index 2bd78d34736..fb6fe0bb1d7 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -1,18 +1,18 @@ use std::mem; +use rustc_ast::ExprKind; use rustc_ast::mut_visit::{self, MutVisitor}; use rustc_ast::token::{self, Delimiter, IdentIsRaw, Lit, LitKind, Nonterminal, Token, TokenKind}; use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; -use rustc_ast::ExprKind; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{pluralize, Diag, DiagCtxtHandle, PResult}; +use rustc_errors::{Diag, DiagCtxtHandle, PResult, pluralize}; use rustc_parse::lexer::nfc_normalize; use rustc_parse::parser::ParseNtResult; use rustc_session::parse::{ParseSess, SymbolGallery}; use rustc_span::hygiene::{LocalExpnId, Transparency}; -use rustc_span::symbol::{sym, Ident, MacroRulesNormalizedIdent}; -use rustc_span::{with_metavar_spans, Span, Symbol, SyntaxContext}; -use smallvec::{smallvec, SmallVec}; +use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent, sym}; +use rustc_span::{Span, Symbol, SyntaxContext, with_metavar_spans}; +use smallvec::{SmallVec, smallvec}; use crate::errors::{ CountRepetitionMisplaced, MetaVarExprUnrecognizedVar, MetaVarsDifSeqMatchers, MustRepeatOnce, diff --git a/compiler/rustc_expand/src/module.rs b/compiler/rustc_expand/src/module.rs index 13348376851..614f52bbd28 100644 --- a/compiler/rustc_expand/src/module.rs +++ b/compiler/rustc_expand/src/module.rs @@ -2,13 +2,13 @@ use std::path::{self, Path, PathBuf}; use rustc_ast::ptr::P; -use rustc_ast::{token, AttrVec, Attribute, Inline, Item, ModSpans}; +use rustc_ast::{AttrVec, Attribute, Inline, Item, ModSpans, token}; use rustc_errors::{Diag, ErrorGuaranteed}; use rustc_parse::{new_parser_from_file, unwrap_or_emit_fatal, validate_attr}; -use rustc_session::parse::ParseSess; use rustc_session::Session; -use rustc_span::symbol::{sym, Ident}; +use rustc_session::parse::ParseSess; use rustc_span::Span; +use rustc_span::symbol::{Ident, sym}; use thin_vec::ThinVec; use crate::base::ModuleData; @@ -171,7 +171,7 @@ fn mod_file_path<'a>( /// Derive a submodule path from the first found `#[path = "path_string"]`. /// The provided `dir_path` is joined with the `path_string`. -fn mod_file_path_from_attr( +pub(crate) fn mod_file_path_from_attr( sess: &Session, attrs: &[Attribute], dir_path: &Path, diff --git a/compiler/rustc_expand/src/placeholders.rs b/compiler/rustc_expand/src/placeholders.rs index 469bed3cd59..610c69e9d21 100644 --- a/compiler/rustc_expand/src/placeholders.rs +++ b/compiler/rustc_expand/src/placeholders.rs @@ -4,9 +4,9 @@ use rustc_ast::visit::AssocCtxt; use rustc_ast::{self as ast}; use rustc_data_structures::fx::FxHashMap; -use rustc_span::symbol::Ident; use rustc_span::DUMMY_SP; -use smallvec::{smallvec, SmallVec}; +use rustc_span::symbol::Ident; +use smallvec::{SmallVec, smallvec}; use thin_vec::ThinVec; use crate::expand::{AstFragment, AstFragmentKind}; diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index d1dcec0cc15..dca0516f9f3 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -4,8 +4,8 @@ use rustc_errors::ErrorGuaranteed; use rustc_parse::parser::{ForceCollect, Parser}; use rustc_session::config::ProcMacroExecutionStrategy; -use rustc_span::profiling::SpannedEventArgRecorder; use rustc_span::Span; +use rustc_span::profiling::SpannedEventArgRecorder; use crate::base::{self, *}; use crate::{errors, proc_macro_server}; diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 5798bcedc22..a7b251ab252 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -2,7 +2,7 @@ use ast::token::IdentIsRaw; use pm::bridge::{ - server, DelimSpan, Diagnostic, ExpnGlobals, Group, Ident, LitKind, Literal, Punct, TokenTree, + DelimSpan, Diagnostic, ExpnGlobals, Group, Ident, LitKind, Literal, Punct, TokenTree, server, }; use pm::{Delimiter, Level}; use rustc_ast as ast; @@ -18,9 +18,9 @@ use rustc_parse::{new_parser_from_source_str, source_str_to_stream, unwrap_or_emit_fatal}; use rustc_session::parse::ParseSess; use rustc_span::def_id::CrateNum; -use rustc_span::symbol::{self, sym, Symbol}; +use rustc_span::symbol::{self, Symbol, sym}; use rustc_span::{BytePos, FileName, Pos, SourceFile, Span}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use crate::base::ExtCtxt; diff --git a/compiler/rustc_feature/src/accepted.rs b/compiler/rustc_feature/src/accepted.rs index 0088a7bbc1e..70e92f545c6 100644 --- a/compiler/rustc_feature/src/accepted.rs +++ b/compiler/rustc_feature/src/accepted.rs @@ -2,7 +2,7 @@ use rustc_span::symbol::sym; -use super::{to_nonzero, Feature}; +use super::{Feature, to_nonzero}; macro_rules! declare_features { ($( diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index fa5f152132a..17827b4e43b 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -2,11 +2,11 @@ use std::sync::LazyLock; -use rustc_data_structures::fx::FxHashMap; -use rustc_span::symbol::{sym, Symbol}; use AttributeDuplicates::*; use AttributeGate::*; use AttributeType::*; +use rustc_data_structures::fx::FxHashMap; +use rustc_span::symbol::{Symbol, sym}; use crate::{Features, Stability}; @@ -859,8 +859,10 @@ pub struct BuiltinAttribute { rustc_attr!( rustc_nonnull_optimization_guaranteed, Normal, template!(Word), WarnFollowing, EncodeCrossCrate::Yes, - "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable \ - niche optimizations in libcore and libstd and will never be stable", + "the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to document \ + guaranteed niche optimizations in libcore and libstd and will never be stable\n\ + (note that the compiler does not even check whether the type indeed is being non-null-optimized; \ + it is your responsibility to ensure that the attribute is only used on types that are optimized)", ), // ========================================================================== diff --git a/compiler/rustc_feature/src/lib.rs b/compiler/rustc_feature/src/lib.rs index fe12930e6b9..8f4c0b0ac95 100644 --- a/compiler/rustc_feature/src/lib.rs +++ b/compiler/rustc_feature/src/lib.rs @@ -129,10 +129,10 @@ pub fn find_feature_issue(feature: Symbol, issue: GateIssue) -> Option bool { (internal, staged_api, "1.0.0", None), /// Added for testing unstable lints; perma-unstable. (internal, test_unstable_lint, "1.60.0", None), + /// Helps with formatting for `group_imports = "StdExternalCrate"`. + (unstable, unqualified_local_imports, "CURRENT_RUSTC_VERSION", None), /// Use for stable + negative coherence and strict coherence depending on trait's /// rustc_strict_coherence value. (unstable, with_negative_coherence, "1.60.0", None), @@ -578,7 +580,7 @@ pub fn internal(&self, feature: Symbol) -> bool { /// be used to describe E or vise-versa. (unstable, result_ffi_guarantees, "1.80.0", Some(110503)), /// Allows bounding the return type of AFIT/RPITIT. - (incomplete, return_type_notation, "1.70.0", Some(109417)), + (unstable, return_type_notation, "1.70.0", Some(109417)), /// Allows `extern "rust-cold"`. (unstable, rust_cold_cc, "1.63.0", Some(97544)), /// Allows use of x86 SHA512, SM3 and SM4 target-features and intrinsics diff --git a/compiler/rustc_fluent_macro/src/fluent.rs b/compiler/rustc_fluent_macro/src/fluent.rs index 37e610a85a6..ead72e2a0e1 100644 --- a/compiler/rustc_fluent_macro/src/fluent.rs +++ b/compiler/rustc_fluent_macro/src/fluent.rs @@ -11,7 +11,7 @@ use proc_macro::{Diagnostic, Level, Span}; use proc_macro2::TokenStream; use quote::quote; -use syn::{parse_macro_input, Ident, LitStr}; +use syn::{Ident, LitStr, parse_macro_input}; use unic_langid::langid; /// Helper function for returning an absolute path for macro-invocation relative file paths. diff --git a/compiler/rustc_fs_util/src/lib.rs b/compiler/rustc_fs_util/src/lib.rs index 91eae98071a..80813af3864 100644 --- a/compiler/rustc_fs_util/src/lib.rs +++ b/compiler/rustc_fs_util/src/lib.rs @@ -1,5 +1,5 @@ use std::ffi::CString; -use std::path::{absolute, Path, PathBuf}; +use std::path::{Path, PathBuf, absolute}; use std::{fs, io}; // Unfortunately, on windows, it looks like msvcrt.dll is silently translating diff --git a/compiler/rustc_graphviz/src/tests.rs b/compiler/rustc_graphviz/src/tests.rs index 01e6cb9a3da..712620a2000 100644 --- a/compiler/rustc_graphviz/src/tests.rs +++ b/compiler/rustc_graphviz/src/tests.rs @@ -4,7 +4,7 @@ use NodeLabels::*; use super::LabelText::{self, EscStr, HtmlStr, LabelStr}; -use super::{render, Edges, GraphWalk, Id, Labeller, Nodes, Style}; +use super::{Edges, GraphWalk, Id, Labeller, Nodes, Style, render}; /// each node is an index in a vector in the graph. type Node = usize; @@ -360,16 +360,12 @@ 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/def.rs b/compiler/rustc_hir/src/def.rs index 9b4174013a6..3276f516a52 100644 --- a/compiler/rustc_hir/src/def.rs +++ b/compiler/rustc_hir/src/def.rs @@ -6,10 +6,10 @@ use rustc_data_structures::stable_hasher::ToStableHashKey; use rustc_data_structures::unord::UnordMap; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; +use rustc_span::Symbol; use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::hygiene::MacroKind; use rustc_span::symbol::kw; -use rustc_span::Symbol; use crate::definitions::DefPathData; use crate::hir; diff --git a/compiler/rustc_hir/src/definitions.rs b/compiler/rustc_hir/src/definitions.rs index 8c2be2152ea..9873a58cfe9 100644 --- a/compiler/rustc_hir/src/definitions.rs +++ b/compiler/rustc_hir/src/definitions.rs @@ -11,11 +11,11 @@ use rustc_data_structures::unord::UnordMap; use rustc_index::IndexVec; use rustc_macros::{Decodable, Encodable}; -use rustc_span::symbol::{kw, sym, Symbol}; +use rustc_span::symbol::{Symbol, kw, sym}; use tracing::{debug, instrument}; pub use crate::def_id::DefPathHash; -use crate::def_id::{CrateNum, DefIndex, LocalDefId, StableCrateId, CRATE_DEF_INDEX, LOCAL_CRATE}; +use crate::def_id::{CRATE_DEF_INDEX, CrateNum, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId}; use crate::def_path_hash_map::DefPathHashMap; /// The `DefPathTable` maps `DefIndex`es to `DefKey`s and vice versa. diff --git a/compiler/rustc_hir/src/diagnostic_items.rs b/compiler/rustc_hir/src/diagnostic_items.rs index 23a83a5011b..67e9c9eeedc 100644 --- a/compiler/rustc_hir/src/diagnostic_items.rs +++ b/compiler/rustc_hir/src/diagnostic_items.rs @@ -1,7 +1,7 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_span::def_id::DefIdMap; use rustc_span::Symbol; +use rustc_span::def_id::DefIdMap; use crate::def_id::DefId; diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index f92c6650355..71216023ecc 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -17,18 +17,18 @@ use rustc_span::def_id::LocalDefId; use rustc_span::hygiene::MacroKind; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{BytePos, ErrorGuaranteed, Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{BytePos, DUMMY_SP, ErrorGuaranteed, Span}; use rustc_target::asm::InlineAsmRegOrRegClass; use rustc_target::spec::abi::Abi; use smallvec::SmallVec; use tracing::debug; +use crate::LangItem; use crate::def::{CtorKind, DefKind, Res}; use crate::def_id::{DefId, LocalDefIdMap}; pub(crate) use crate::hir_id::{HirId, ItemLocalId, ItemLocalMap, OwnerId}; use crate::intravisit::FnKind; -use crate::LangItem; #[derive(Debug, Copy, Clone, HashStable_Generic)] pub struct Lifetime { @@ -1668,10 +1668,17 @@ pub enum ArrayLen<'hir> { } impl ArrayLen<'_> { - pub fn hir_id(&self) -> HirId { + pub fn span(self) -> Span { match self { - ArrayLen::Infer(InferArg { hir_id, .. }) | ArrayLen::Body(ConstArg { hir_id, .. }) => { - *hir_id + ArrayLen::Infer(arg) => arg.span, + ArrayLen::Body(body) => body.span(), + } + } + + pub fn hir_id(self) -> HirId { + match self { + ArrayLen::Infer(InferArg { hir_id, .. }) | ArrayLen::Body(&ConstArg { hir_id, .. }) => { + hir_id } } } @@ -2589,10 +2596,10 @@ impl<'v> Visitor<'v> for MyVisitor { fn visit_ty(&mut self, t: &'v Ty<'v>) { 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; @@ -2920,10 +2927,11 @@ pub fn reg(&self) -> Option { } 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/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index f2142359935..3fa06620ea8 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -2,10 +2,10 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableOrd, ToStableHashKey}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_span::def_id::DefPathHash; use rustc_span::HashStableContext; +use rustc_span::def_id::DefPathHash; -use crate::def_id::{DefId, DefIndex, LocalDefId, CRATE_DEF_ID}; +use crate::def_id::{CRATE_DEF_ID, DefId, DefIndex, LocalDefId}; #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)] pub struct OwnerId { diff --git a/compiler/rustc_hir/src/intravisit.rs b/compiler/rustc_hir/src/intravisit.rs index a54596e3088..4da32245785 100644 --- a/compiler/rustc_hir/src/intravisit.rs +++ b/compiler/rustc_hir/src/intravisit.rs @@ -64,11 +64,11 @@ //! This order consistency is required in a few places in rustc, for //! example coroutine inference, and possibly also HIR borrowck. -use rustc_ast::visit::{try_visit, visit_opt, walk_list, VisitorResult}; +use rustc_ast::visit::{VisitorResult, try_visit, visit_opt, walk_list}; use rustc_ast::{Attribute, Label}; +use rustc_span::Span; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::{Ident, Symbol}; -use rustc_span::Span; use crate::hir::*; diff --git a/compiler/rustc_hir/src/lang_items.rs b/compiler/rustc_hir/src/lang_items.rs index c148dc7f53b..b161e6ba0fa 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -11,8 +11,8 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, kw, sym}; use crate::def_id::DefId; use crate::{MethodKind, Target}; diff --git a/compiler/rustc_hir/src/pat_util.rs b/compiler/rustc_hir/src/pat_util.rs index 73d1ea40707..2ebbb4a06b6 100644 --- a/compiler/rustc_hir/src/pat_util.rs +++ b/compiler/rustc_hir/src/pat_util.rs @@ -1,7 +1,7 @@ use std::iter::Enumerate; -use rustc_span::symbol::Ident; use rustc_span::Span; +use rustc_span::symbol::Ident; use crate::def::{CtorOf, DefKind, Res}; use crate::def_id::{DefId, DefIdSet}; diff --git a/compiler/rustc_hir/src/target.rs b/compiler/rustc_hir/src/target.rs index f43008eda11..155270ca6a7 100644 --- a/compiler/rustc_hir/src/target.rs +++ b/compiler/rustc_hir/src/target.rs @@ -7,7 +7,7 @@ use std::fmt::{self, Display}; use crate::def::DefKind; -use crate::{hir, Item, ItemKind, TraitItem, TraitItemKind}; +use crate::{Item, ItemKind, TraitItem, TraitItemKind, hir}; #[derive(Copy, Clone, PartialEq, Debug)] pub enum GenericParamKind { diff --git a/compiler/rustc_hir/src/tests.rs b/compiler/rustc_hir/src/tests.rs index 16b3c4a9ab6..5c10fa46971 100644 --- a/compiler/rustc_hir/src/tests.rs +++ b/compiler/rustc_hir/src/tests.rs @@ -1,7 +1,7 @@ use rustc_data_structures::stable_hasher::Hash64; use rustc_span::def_id::{DefPathHash, StableCrateId}; use rustc_span::edition::Edition; -use rustc_span::{create_session_globals_then, Symbol}; +use rustc_span::{Symbol, create_session_globals_then}; use crate::definitions::{DefKey, DefPathData, DisambiguatedDefPathData}; diff --git a/compiler/rustc_hir/src/weak_lang_items.rs b/compiler/rustc_hir/src/weak_lang_items.rs index ca133c5965d..337859cd1fb 100644 --- a/compiler/rustc_hir/src/weak_lang_items.rs +++ b/compiler/rustc_hir/src/weak_lang_items.rs @@ -1,6 +1,6 @@ //! Validity checking for weak lang items -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; use crate::LangItem; diff --git a/compiler/rustc_hir_analysis/src/autoderef.rs b/compiler/rustc_hir_analysis/src/autoderef.rs index 46a0d4f498a..8d11328743c 100644 --- a/compiler/rustc_hir_analysis/src/autoderef.rs +++ b/compiler/rustc_hir_analysis/src/autoderef.rs @@ -1,8 +1,8 @@ use rustc_infer::infer::InferCtxt; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use rustc_session::Limit; -use rustc_span::def_id::{LocalDefId, LOCAL_CRATE}; use rustc_span::Span; +use rustc_span::def_id::{LOCAL_CRATE, LocalDefId}; use rustc_trait_selection::traits::ObligationCtxt; use tracing::{debug, instrument}; diff --git a/compiler/rustc_hir_analysis/src/bounds.rs b/compiler/rustc_hir_analysis/src/bounds.rs index 14ea7816291..caf9960741d 100644 --- a/compiler/rustc_hir_analysis/src/bounds.rs +++ b/compiler/rustc_hir_analysis/src/bounds.rs @@ -2,12 +2,12 @@ //! [`rustc_middle::ty`] form. use rustc_data_structures::fx::FxIndexMap; -use rustc_hir::def::DefKind; use rustc_hir::LangItem; +use rustc_hir::def::DefKind; use rustc_middle::ty::fold::FnMutDelegate; use rustc_middle::ty::{self, Ty, TyCtxt, Upcast}; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; use crate::hir_ty_lowering::OnlySelfBounds; @@ -112,14 +112,11 @@ pub(crate) fn push_trait_bound( // This should work for any bound variables as long as they don't have any // bounds e.g. `for`. // FIXME(effects) reconsider this approach to allow compatibility with `for` - let ty = tcx.replace_bound_vars_uncached( - ty, - FnMutDelegate { - regions: &mut |_| tcx.lifetimes.re_static, - types: &mut |_| tcx.types.unit, - consts: &mut |_| unimplemented!("`~const` does not support const binders"), - }, - ); + let ty = tcx.replace_bound_vars_uncached(ty, FnMutDelegate { + regions: &mut |_| tcx.lifetimes.re_static, + types: &mut |_| tcx.types.unit, + consts: &mut |_| unimplemented!("`~const` does not support const binders"), + }); self.effects_min_tys.insert(ty, span); return; @@ -152,11 +149,11 @@ pub(crate) fn push_trait_bound( }; let self_ty = Ty::new_projection(tcx, assoc, bound_trait_ref.skip_binder().args); // make `::Effects: Compat` - let new_trait_ref = ty::TraitRef::new( - tcx, - tcx.require_lang_item(LangItem::EffectsCompat, Some(span)), - [ty::GenericArg::from(self_ty), compat_val.into()], - ); + let new_trait_ref = + ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::EffectsCompat, Some(span)), [ + ty::GenericArg::from(self_ty), + compat_val.into(), + ]); self.clauses.push((bound_trait_ref.rebind(new_trait_ref).upcast(tcx), span)); } diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 1d686878eab..d725772a5b3 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -2,10 +2,10 @@ use std::ops::ControlFlow; use rustc_data_structures::unord::{UnordMap, UnordSet}; -use rustc_errors::codes::*; use rustc_errors::MultiSpan; -use rustc_hir::def::{CtorKind, DefKind}; +use rustc_errors::codes::*; use rustc_hir::Node; +use rustc_hir::def::{CtorKind, DefKind}; use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt}; use rustc_infer::traits::Obligation; use rustc_lint_defs::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS; @@ -22,8 +22,8 @@ }; use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS}; use rustc_target::abi::FieldIdx; -use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; +use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedDirective; use rustc_trait_selection::traits; use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _; use rustc_type_ir::fold::TypeFoldable; 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 cc7a0dff34e..9ca5f25447b 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -5,10 +5,10 @@ use hir::def_id::{DefId, DefIdMap, LocalDefId}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_errors::codes::*; -use rustc_errors::{pluralize, struct_span_code_err, Applicability, ErrorGuaranteed}; +use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::{intravisit, GenericParamKind, ImplItemKind}; +use rustc_hir::{GenericParamKind, ImplItemKind, intravisit}; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::util; @@ -176,15 +176,12 @@ 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 impl to placeholder. let impl_to_placeholder_args = GenericArgs::identity_for_item(tcx, impl_m.def_id); @@ -237,15 +234,12 @@ 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)); } @@ -465,15 +459,12 @@ 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 impl to placeholder. let impl_to_placeholder_args = GenericArgs::identity_for_item(tcx, impl_m.def_id); @@ -561,16 +552,13 @@ 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(); @@ -936,13 +924,10 @@ fn try_fold_region( 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, + })) } } @@ -1932,15 +1917,12 @@ 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)); } @@ -2178,25 +2160,20 @@ 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::BrNamed(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/compare_impl_item/refine.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs index d2b7ede6523..e07b587508a 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs @@ -1,8 +1,8 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_hir as hir; use rustc_hir::def_id::DefId; -use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_lint_defs::builtin::{REFINING_IMPL_TRAIT_INTERNAL, REFINING_IMPL_TRAIT_REACHABLE}; use rustc_middle::span_bug; use rustc_middle::traits::{ObligationCause, Reveal}; @@ -13,7 +13,7 @@ use rustc_span::Span; use rustc_trait_selection::regions::InferCtxtRegionExt; use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt; -use rustc_trait_selection::traits::{elaborate, normalize_param_env_or_error, ObligationCtxt}; +use rustc_trait_selection::traits::{ObligationCtxt, elaborate, normalize_param_env_or_error}; /// Check that an implementation does not refine an RPITIT from a trait method signature. pub(super) fn check_refining_return_position_impl_trait_in_trait<'tcx>( diff --git a/compiler/rustc_hir_analysis/src/check/dropck.rs b/compiler/rustc_hir_analysis/src/check/dropck.rs index d173915e480..97a29b32c01 100644 --- a/compiler/rustc_hir_analysis/src/check/dropck.rs +++ b/compiler/rustc_hir_analysis/src/check/dropck.rs @@ -4,7 +4,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, ErrorGuaranteed}; +use rustc_errors::{ErrorGuaranteed, struct_span_code_err}; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{RegionResolutionError, TyCtxtInferExt}; use rustc_infer::traits::{ObligationCause, ObligationCauseCode}; diff --git a/compiler/rustc_hir_analysis/src/check/entry.rs b/compiler/rustc_hir_analysis/src/check/entry.rs index 83d2c2c1e28..7da2cd93d4e 100644 --- a/compiler/rustc_hir_analysis/src/check/entry.rs +++ b/compiler/rustc_hir_analysis/src/check/entry.rs @@ -6,9 +6,9 @@ use rustc_middle::span_bug; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::config::EntryFnType; -use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; +use rustc_span::symbol::sym; use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode}; diff --git a/compiler/rustc_hir_analysis/src/check/errs.rs b/compiler/rustc_hir_analysis/src/check/errs.rs index 22d7d1fea9c..64307407b73 100644 --- a/compiler/rustc_hir_analysis/src/check/errs.rs +++ b/compiler/rustc_hir_analysis/src/check/errs.rs @@ -79,11 +79,10 @@ fn handle_static_mut_ref( } else { (errors::MutRefSugg::Shared { lo, hi }, "shared") }; - tcx.emit_node_span_lint( - STATIC_MUT_REFS, - hir_id, + tcx.emit_node_span_lint(STATIC_MUT_REFS, hir_id, span, errors::RefOfMutStatic { span, - errors::RefOfMutStatic { span, sugg, shared }, - ); + sugg, + shared, + }); } } diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index c2b2f08132e..25e219ef3f2 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -2,7 +2,7 @@ //! intrinsics that the compiler exposes. use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, DiagMessage}; +use rustc_errors::{DiagMessage, struct_span_code_err}; use rustc_hir as hir; use rustc_middle::bug; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; @@ -190,16 +190,14 @@ 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::BrAnon }, - ); - let env_region = ty::Region::new_bound( - tcx, - ty::INNERMOST, - ty::BoundRegion { var: ty::BoundVar::from_u32(2), kind: ty::BrEnv }, - ); + let region = ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { + var: ty::BoundVar::ZERO, + kind: ty::BrAnon, + }); + let env_region = ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { + var: ty::BoundVar::from_u32(2), + kind: ty::BrEnv, + }); 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/intrinsicck.rs b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs index 3d5a22fce85..71eb368185e 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsicck.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsicck.rs @@ -6,8 +6,8 @@ use rustc_middle::bug; use rustc_middle::ty::{self, FloatTy, IntTy, Ty, TyCtxt, TypeVisitableExt, UintTy}; use rustc_session::lint; -use rustc_span::def_id::LocalDefId; use rustc_span::Symbol; +use rustc_span::def_id::LocalDefId; use rustc_target::abi::FieldIdx; use rustc_target::asm::{ InlineAsmReg, InlineAsmRegClass, InlineAsmRegOrRegClass, InlineAsmType, ModifierInfo, diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 3a7366ef78a..d3d88919d87 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -75,7 +75,7 @@ pub use check::check_abi; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; -use rustc_errors::{pluralize, struct_span_code_err, Diag, ErrorGuaranteed}; +use rustc_errors::{Diag, ErrorGuaranteed, pluralize, struct_span_code_err}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::Visitor; use rustc_index::bit_set::BitSet; @@ -88,13 +88,13 @@ use rustc_middle::{bug, span_bug}; use rustc_session::parse::feature_err; use rustc_span::def_id::CRATE_DEF_ID; -use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::{BytePos, Span, Symbol, DUMMY_SP}; +use rustc_span::symbol::{Ident, kw, sym}; +use rustc_span::{BytePos, DUMMY_SP, Span, Symbol}; use rustc_target::abi::VariantIdx; use rustc_target::spec::abi::Abi; +use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::error_reporting::infer::ObligationCauseExt as _; use rustc_trait_selection::error_reporting::traits::suggestions::ReturnsVisitor; -use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::ObligationCtxt; use tracing::debug; diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 10b3fe380ab..f8a19e93a41 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -4,11 +4,11 @@ use hir::intravisit::{self, Visitor}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_errors::codes::*; -use rustc_errors::{pluralize, struct_span_code_err, Applicability, ErrorGuaranteed}; +use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err}; +use rustc_hir::ItemKind; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId}; use rustc_hir::lang_items::LangItem; -use rustc_hir::ItemKind; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt}; use rustc_macros::LintDiagnostic; @@ -21,27 +21,27 @@ }; use rustc_middle::{bug, span_bug}; use rustc_session::parse::feature_err; -use rustc_span::symbol::{sym, Ident}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, sym}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::regions::InferCtxtRegionExt; use rustc_trait_selection::traits::misc::{ - type_allowed_to_implement_const_param_ty, ConstParamTyImplementationError, + ConstParamTyImplementationError, type_allowed_to_implement_const_param_ty, }; use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; use rustc_trait_selection::traits::{ self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt, WellFormedLoc, }; -use rustc_type_ir::solve::NoSolution; use rustc_type_ir::TypeFlags; +use rustc_type_ir::solve::NoSolution; use tracing::{debug, instrument}; use {rustc_ast as ast, rustc_hir as hir}; use crate::autoderef::Autoderef; use crate::collect::CollectItemTypesVisitor; -use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter}; +use crate::constrained_generic_params::{Parameter, identify_constrained_generic_params}; use crate::{errors, fluent_generated as fluent}; pub(super) struct WfCheckingCtxt<'a, 'tcx> { @@ -664,10 +664,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( @@ -693,16 +693,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( diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index 480116a6249..bea8d28a9f7 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -7,20 +7,20 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::{ErrorGuaranteed, MultiSpan}; use rustc_hir as hir; +use rustc_hir::ItemKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; -use rustc_hir::ItemKind; use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{self, RegionResolutionError, TyCtxtInferExt}; use rustc_infer::traits::Obligation; use rustc_middle::ty::adjustment::CoerceUnsizedInfo; use rustc_middle::ty::print::PrintTraitRefExt as _; -use rustc_middle::ty::{self, suggest_constraining_type_params, Ty, TyCtxt, TypeVisitableExt}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, suggest_constraining_type_params}; +use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::misc::{ - type_allowed_to_implement_const_param_ty, type_allowed_to_implement_copy, ConstParamTyImplementationError, CopyImplementationError, InfringingFieldsReason, + type_allowed_to_implement_const_param_ty, type_allowed_to_implement_copy, }; use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt}; use tracing::debug; @@ -309,11 +309,10 @@ 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.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index 9fce927e2c7..c07d8009aa5 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -11,10 +11,10 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::bug; -use rustc_middle::ty::fast_reject::{simplify_type, SimplifiedType, TreatParams}; +use rustc_middle::ty::fast_reject::{SimplifiedType, TreatParams, simplify_type}; use rustc_middle::ty::{self, CrateInherentImpls, Ty, TyCtxt}; -use rustc_span::symbol::sym; use rustc_span::ErrorGuaranteed; +use rustc_span::symbol::sym; use crate::errors; 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 6825c2e33fe..43b9093ecac 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs @@ -252,13 +252,10 @@ struct ConnectedRegion { 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/coherence/mod.rs b/compiler/rustc_hir_analysis/src/coherence/mod.rs index f2a97d06771..185f3176f07 100644 --- a/compiler/rustc_hir_analysis/src/coherence/mod.rs +++ b/compiler/rustc_hir_analysis/src/coherence/mod.rs @@ -7,12 +7,12 @@ use rustc_errors::codes::*; use rustc_errors::struct_span_code_err; -use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::LangItem; +use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::query::Providers; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_session::parse::feature_err; -use rustc_span::{sym, ErrorGuaranteed}; +use rustc_span::{ErrorGuaranteed, sym}; use tracing::debug; use crate::errors; diff --git a/compiler/rustc_hir_analysis/src/coherence/unsafety.rs b/compiler/rustc_hir_analysis/src/coherence/unsafety.rs index 7513f680271..d66114a50d7 100644 --- a/compiler/rustc_hir_analysis/src/coherence/unsafety.rs +++ b/compiler/rustc_hir_analysis/src/coherence/unsafety.rs @@ -4,11 +4,11 @@ use rustc_errors::codes::*; use rustc_errors::struct_span_code_err; use rustc_hir::Safety; -use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::ImplPolarity::*; +use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{ImplTraitHeader, TraitDef, TyCtxt}; -use rustc_span::def_id::LocalDefId; use rustc_span::ErrorGuaranteed; +use rustc_span::def_id::LocalDefId; pub(super) fn check_item( tcx: TyCtxt<'_>, diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 4c59f7540ee..93b021be245 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -23,11 +23,11 @@ use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::unord::UnordMap; use rustc_errors::{ - struct_span_code_err, Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, StashKey, E0228, + Applicability, Diag, DiagCtxtHandle, E0228, ErrorGuaranteed, StashKey, struct_span_code_err, }; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir::intravisit::{self, walk_generics, Visitor}; +use rustc_hir::intravisit::{self, Visitor, walk_generics}; use rustc_hir::{self as hir, GenericParamKind, Node}; use rustc_infer::infer::{InferCtxt, TyCtxtInferExt}; use rustc_infer::traits::ObligationCause; @@ -36,8 +36,8 @@ use rustc_middle::ty::util::{Discr, IntTypeExt}; use rustc_middle::ty::{self, AdtKind, Const, IsSuggestable, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::spec::abi; use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName; use rustc_trait_selection::infer::InferCtxtExt; diff --git a/compiler/rustc_hir_analysis/src/collect/dump.rs b/compiler/rustc_hir_analysis/src/collect/dump.rs index c73d3a5390d..d76d9213129 100644 --- a/compiler/rustc_hir_analysis/src/collect/dump.rs +++ b/compiler/rustc_hir_analysis/src/collect/dump.rs @@ -1,5 +1,5 @@ use rustc_hir::def::DefKind; -use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; use rustc_hir::intravisit; use rustc_middle::hir::nested_filter::OnlyBodies; use rustc_middle::ty::TyCtxt; diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index ba01ea3f512..0a8eef2006d 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -8,8 +8,8 @@ use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::{self, TyCtxt}; use rustc_session::lint; -use rustc_span::symbol::{kw, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, kw}; use tracing::{debug, instrument}; use crate::delegation::inherit_generics_for_delegation_item; diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index 7a254c884c2..c64741625a4 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -5,13 +5,13 @@ self, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, }; use rustc_middle::{bug, span_bug}; -use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::Span; +use rustc_span::def_id::{DefId, LocalDefId}; use rustc_type_ir::Upcast; use tracing::{debug, instrument}; -use super::predicates_of::assert_only_contains_predicates_from; use super::ItemCtxt; +use super::predicates_of::assert_only_contains_predicates_from; use crate::hir_ty_lowering::{HirTyLowerer, PredicateFilter}; /// For associated types we include both bounds written on the type diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index 67d8813d1f7..9e970462205 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -9,7 +9,7 @@ use rustc_middle::ty::{self, GenericPredicates, ImplTraitInTraitData, Ty, TyCtxt, Upcast}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::Ident; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument, trace}; use crate::bounds::Bounds; @@ -379,10 +379,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 d1601446b6f..c9b949ad88d 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -21,9 +21,9 @@ use rustc_middle::query::Providers; use rustc_middle::ty::{self, TyCtxt, TypeSuperVisitable, TypeVisitor}; use rustc_middle::{bug, span_bug}; -use rustc_span::def_id::{DefId, LocalDefId}; -use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use rustc_span::def_id::{DefId, LocalDefId}; +use rustc_span::symbol::{Ident, sym}; use tracing::{debug, debug_span, instrument}; use crate::errors; @@ -1730,7 +1730,7 @@ fn supertrait_hrtb_vars( ) }; - use smallvec::{smallvec, SmallVec}; + use smallvec::{SmallVec, smallvec}; let mut stack: SmallVec<[(DefId, SmallVec<[ty::BoundVariableKind; 8]>); 8]> = smallvec![(def_id, smallvec![])]; let mut visited: FxHashSet = FxHashSet::default(); diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index b877cacd998..48b5e87cbd0 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -2,18 +2,18 @@ use rustc_errors::{Applicability, StashKey, Suggestions}; use rustc_hir as hir; -use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::HirId; +use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::query::plumbing::CyclePlaceholder; use rustc_middle::ty::print::with_forced_trimmed_paths; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, Article, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::Ident; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::debug; -use super::{bad_placeholder, ItemCtxt}; +use super::{ItemCtxt, bad_placeholder}; use crate::errors::TypeofReservedKeywordUsed; use crate::hir_ty_lowering::HirTyLowerer; diff --git a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs index 2afb29abd68..fcea0052546 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs @@ -2,7 +2,7 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{self as hir, def, Expr, ImplItem, Item, Node, TraitItem}; +use rustc_hir::{self as hir, Expr, ImplItem, Item, Node, TraitItem, def}; use rustc_middle::bug; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; diff --git a/compiler/rustc_hir_analysis/src/delegation.rs b/compiler/rustc_hir_analysis/src/delegation.rs index 2c9f20b7840..1ccb7faaf30 100644 --- a/compiler/rustc_hir_analysis/src/delegation.rs +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -41,10 +41,10 @@ fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'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/errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs index 236543007fc..5ae7944f6d5 100644 --- a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs @@ -1,12 +1,12 @@ use std::iter; +use GenericArgsInfo::*; use rustc_errors::codes::*; -use rustc_errors::{pluralize, Applicability, Diag, Diagnostic, EmissionGuarantee, MultiSpan}; +use rustc_errors::{Applicability, Diag, Diagnostic, EmissionGuarantee, MultiSpan, pluralize}; use rustc_hir as hir; use rustc_middle::ty::{self as ty, AssocItems, AssocKind, TyCtxt}; use rustc_span::def_id::DefId; use tracing::debug; -use GenericArgsInfo::*; /// Handles the `wrong number of type / lifetime / ... arguments` family of error messages. pub(crate) struct WrongNumberOfGenericArgs<'a, 'tcx> { 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 6f7f3128347..45cd46e3df2 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/bounds.rs @@ -4,13 +4,13 @@ use rustc_errors::codes::*; use rustc_errors::struct_span_code_err; use rustc_hir as hir; +use rustc_hir::HirId; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir::HirId; use rustc_middle::bug; use rustc_middle::ty::{self as ty, IsSuggestable, Ty, TyCtxt}; use rustc_span::symbol::Ident; -use rustc_span::{sym, ErrorGuaranteed, Span, Symbol}; +use rustc_span::{ErrorGuaranteed, Span, Symbol, sym}; use rustc_trait_selection::traits; use rustc_type_ir::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; use smallvec::SmallVec; @@ -672,15 +672,13 @@ fn lower_return_type_notation_ty( 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::BrNamed(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/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index af319fd53bd..5e3203e8473 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -3,7 +3,7 @@ use rustc_data_structures::unord::UnordMap; use rustc_errors::codes::*; use rustc_errors::{ - pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, + Applicability, Diag, ErrorGuaranteed, MultiSpan, pluralize, struct_span_code_err, }; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; @@ -12,16 +12,16 @@ use rustc_middle::query::Key; use rustc_middle::ty::print::{PrintPolyTraitRefExt as _, PrintTraitRefExt as _}; use rustc_middle::ty::{ - self, suggest_constraining_type_param, AdtDef, Binder, GenericParamDefKind, TraitRef, Ty, - TyCtxt, TypeVisitableExt, + self, AdtDef, Binder, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeVisitableExt, + suggest_constraining_type_param, }; use rustc_session::parse::feature_err; use rustc_span::edit_distance::find_best_match_for_name; -use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::{BytePos, Span, Symbol, DUMMY_SP}; +use rustc_span::symbol::{Ident, kw, sym}; +use rustc_span::{BytePos, DUMMY_SP, Span, Symbol}; use rustc_trait_selection::error_reporting::traits::report_object_safety_error; use rustc_trait_selection::traits::{ - object_safety_violations_for_assoc_item, FulfillmentError, TraitAliasExpansionInfo, + FulfillmentError, TraitAliasExpansionInfo, object_safety_violations_for_assoc_item, }; use crate::errors::{ @@ -834,17 +834,14 @@ pub(crate) fn complain_about_missing_assoc_tys( .into_iter() .map(|(trait_, mut assocs)| { assocs.sort(); - format!( - "{} in `{trait_}`", - match &assocs[..] { - [] => String::new(), - [only] => format!("`{only}`"), - [assocs @ .., last] => format!( - "{} and `{last}`", - assocs.iter().map(|a| format!("`{a}`")).collect::>().join(", ") - ), - } - ) + format!("{} in `{trait_}`", match &assocs[..] { + [] => String::new(), + [only] => format!("`{only}`"), + [assocs @ .., last] => format!( + "{} and `{last}`", + assocs.iter().map(|a| format!("`{a}`")).collect::>().join(", ") + ), + }) }) .collect::>(); names.sort(); diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs index 8d5f98c7372..6e8a9ded4f3 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs @@ -1,10 +1,10 @@ use rustc_ast::ast::ParamKindOrd; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan}; +use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, struct_span_code_err}; use rustc_hir as hir; +use rustc_hir::GenericArg; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; -use rustc_hir::GenericArg; use rustc_middle::ty::{ self, GenericArgsRef, GenericParamDef, GenericParamDefKind, IsSuggestable, Ty, }; diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs index 149bc6d2698..1fbf70fa201 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/lint.rs @@ -3,8 +3,8 @@ use rustc_errors::{Diag, EmissionGuarantee, StashKey}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_lint_defs::builtin::BARE_TRAIT_OBJECTS; use rustc_lint_defs::Applicability; +use rustc_lint_defs::builtin::BARE_TRAIT_OBJECTS; use rustc_span::Span; use rustc_trait_selection::error_reporting::traits::suggestions::NextTypeParamName; 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 35eebcb6be1..e95b5142559 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -26,7 +26,7 @@ use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_errors::codes::*; use rustc_errors::{ - struct_span_code_err, Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, + Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, struct_span_code_err, }; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; @@ -44,8 +44,8 @@ use rustc_middle::{bug, span_bug}; use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS; use rustc_span::edit_distance::find_best_match_for_name; -use rustc_span::symbol::{kw, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, Symbol, kw}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::spec::abi; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::wf::object_region_bounds; @@ -54,7 +54,7 @@ use crate::bounds::Bounds; use crate::errors::{AmbiguousLifetimeBound, BadReturnTypeNotation, WildPatTy}; -use crate::hir_ty_lowering::errors::{prohibit_assoc_item_constraint, GenericsArgsErrExtend}; +use crate::hir_ty_lowering::errors::{GenericsArgsErrExtend, prohibit_assoc_item_constraint}; use crate::hir_ty_lowering::generics::{check_generic_arg_count, lower_generic_args}; use crate::middle::resolve_bound_vars as rbv; use crate::require_c_abi_if_c_variadic; diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs index 88538863710..87a240f626c 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/object_safety.rs @@ -13,7 +13,7 @@ use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::error_reporting::traits::report_object_safety_error; use rustc_trait_selection::traits::{self, hir_ty_lowering_object_safety_violations}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; use super::HirTyLowerer; diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index 147646930dd..0355adfcb11 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -68,15 +68,15 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::traits::specialization_graph::Node; use rustc_middle::ty::trait_def::TraitSpecializationKind; use rustc_middle::ty::{self, GenericArg, GenericArgs, GenericArgsRef, TyCtxt, TypeVisitableExt}; use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _; -use rustc_trait_selection::traits::{self, translate_args_with_cause, wf, ObligationCtxt}; +use rustc_trait_selection::traits::{self, ObligationCtxt, translate_args_with_cause, wf}; use tracing::{debug, instrument}; use crate::errors::GenericArgsOnOverriddenImpl; diff --git a/compiler/rustc_hir_analysis/src/lib.rs b/compiler/rustc_hir_analysis/src/lib.rs index 1481a4dd141..1dc85c4903e 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -100,8 +100,8 @@ use rustc_middle::query::Providers; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_session::parse::feature_err; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits; diff --git a/compiler/rustc_hir_analysis/src/outlives/utils.rs b/compiler/rustc_hir_analysis/src/outlives/utils.rs index a1eccc91dea..0c9f5ba8b6f 100644 --- a/compiler/rustc_hir_analysis/src/outlives/utils.rs +++ b/compiler/rustc_hir_analysis/src/outlives/utils.rs @@ -2,7 +2,7 @@ use rustc_middle::ty::{self, GenericArg, GenericArgKind, Region, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_span::Span; -use rustc_type_ir::outlives::{push_outlives_components, Component}; +use rustc_type_ir::outlives::{Component, push_outlives_components}; use smallvec::smallvec; /// Tracks the `T: 'a` or `'a: 'a` predicates that we have inferred diff --git a/compiler/rustc_hir_analysis/src/variance/dump.rs b/compiler/rustc_hir_analysis/src/variance/dump.rs index ace183986bd..dbaf9c2c6f0 100644 --- a/compiler/rustc_hir_analysis/src/variance/dump.rs +++ b/compiler/rustc_hir_analysis/src/variance/dump.rs @@ -1,7 +1,7 @@ use std::fmt::Write; use rustc_hir::def::DefKind; -use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; use rustc_middle::ty::{GenericArgs, TyCtxt}; use rustc_span::symbol::sym; diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index ac6707f9316..1c52283d537 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -18,9 +18,9 @@ HirId, LifetimeParamKind, Node, PatKind, PreciseCapturingArg, RangeEnd, Term, TraitBoundModifier, }; -use rustc_span::source_map::SourceMap; -use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::FileName; +use rustc_span::source_map::SourceMap; +use rustc_span::symbol::{Ident, Symbol, kw}; use rustc_target::spec::abi::Abi; use {rustc_ast as ast, rustc_hir as hir}; @@ -2026,13 +2026,10 @@ fn print_closure_binder( 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 3dc8759a9ed..13ba615d4c9 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -13,17 +13,17 @@ }; use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; -use rustc_span::def_id::LocalDefId; -use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use rustc_span::def_id::LocalDefId; +use rustc_span::symbol::{Ident, sym}; use rustc_target::spec::abi; use rustc_trait_selection::error_reporting::traits::DefIdOrName; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; use tracing::{debug, instrument, trace}; -use super::method::probe::ProbeScope; use super::method::MethodCallee; +use super::method::probe::ProbeScope; use super::{Expectation, FnCtxt, TupleArgumentsFlag}; use crate::errors; @@ -156,16 +156,13 @@ fn try_overloaded_call_step( 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)); } @@ -202,16 +199,13 @@ fn try_overloaded_call_step( 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)); } @@ -554,11 +548,11 @@ fn confirm_builtin_call( self.tcx, self.misc(span), self.param_env, - ty::TraitRef::new( - self.tcx, - fn_once_def_id, - [arg_ty.into(), fn_sig.inputs()[0].into(), const_param], - ), + ty::TraitRef::new(self.tcx, fn_once_def_id, [ + arg_ty.into(), + fn_sig.inputs()[0].into(), + const_param, + ]), )); self.register_predicate(traits::Obligation::new( diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 36892aaf80c..aab0c4c116a 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -42,7 +42,7 @@ use rustc_session::lint; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::symbol::sym; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::infer::InferCtxtExt; use tracing::{debug, instrument}; @@ -284,14 +284,11 @@ fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) { let mut err = make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx); if self.cast_ty.is_integral() { - err.help(format!( - "cast through {} first", - match e { - CastError::NeedViaPtr => "a raw pointer", - CastError::NeedViaThinPtr => "a thin pointer", - e => unreachable!("control flow means we should never encounter a {e:?}"), - } - )); + err.help(format!("cast through {} first", match e { + CastError::NeedViaPtr => "a raw pointer", + CastError::NeedViaThinPtr => "a thin pointer", + e => unreachable!("control flow means we should never encounter a {e:?}"), + })); } self.try_suggest_collection_to_bool(fcx, &mut err); @@ -620,12 +617,11 @@ fn trivial_cast_lint(&self, fcx: &FnCtxt<'a, '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 9346ff2d6ef..f2d3a3b509a 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -191,21 +191,18 @@ 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::BrAnon }, - ))], - ); + 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::BrAnon, + }), + )]); 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::BrAnon }, - ), + ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { + var: ty::BoundVar::ZERO, + kind: ty::BrAnon, + }), panic_info_ty, ); diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index f71427e42d4..3e7ce2955fc 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -14,14 +14,14 @@ use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor}; use rustc_span::def_id::LocalDefId; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::error_reporting::traits::ArgKind; use rustc_trait_selection::traits; use rustc_type_ir::ClosureKind; use tracing::{debug, instrument, trace}; -use super::{check_fn, CoroutineTypes, Expectation, FnCtxt}; +use super::{CoroutineTypes, Expectation, FnCtxt, check_fn}; /// What signature do we *expect* the closure to have from context? #[derive(Debug, Clone, TypeFoldable, TypeVisitable)] @@ -103,15 +103,12 @@ pub fn check_expr_closure( 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) } @@ -180,18 +177,15 @@ pub fn check_expr_closure( _ => 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), @@ -222,9 +216,8 @@ pub fn check_expr_closure( }; 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( @@ -245,8 +238,7 @@ pub fn check_expr_closure( 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 26c9b8dfdc3..7be91d78e19 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -38,7 +38,7 @@ use std::ops::Deref; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, Applicability, Diag}; +use rustc_errors::{Applicability, Diag, struct_span_code_err}; use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer; @@ -58,18 +58,18 @@ use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt}; use rustc_session::parse::feature_err; use rustc_span::symbol::sym; -use rustc_span::{BytePos, DesugaringKind, Span, DUMMY_SP}; +use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Span}; use rustc_target::spec::abi::Abi; use rustc_trait_selection::infer::InferCtxtExt as _; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::{ self, NormalizeExt, ObligationCause, ObligationCauseCode, ObligationCtxt, }; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; -use crate::errors::SuggestBoxingForReturnImplTrait; use crate::FnCtxt; +use crate::errors::SuggestBoxingForReturnImplTrait; struct Coerce<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, @@ -534,24 +534,18 @@ fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceRe // 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(r_borrow, 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(r_borrow, 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, }; @@ -573,11 +567,11 @@ fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceRe let mut selcx = traits::SelectionContext::new(self); // Create an obligation for `Source: CoerceUnsized`. - let cause = ObligationCause::new( - self.cause.span, - self.body_id, - ObligationCauseCode::Coercion { source, target }, - ); + let cause = + ObligationCause::new(self.cause.span, self.body_id, ObligationCauseCode::Coercion { + source, + target, + }); // Use a FIFO queue for this custom fulfillment procedure. // @@ -1021,10 +1015,10 @@ fn coerce_unsafe_ptr( // 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))) @@ -1241,10 +1235,10 @@ fn try_find_coercion_lub( _ => 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/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 80a71f27a99..cfa8fc4bbf2 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -10,7 +10,7 @@ use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, AssocItem, Ty, TypeFoldable, TypeVisitableExt}; use rustc_span::symbol::sym; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::ObligationCause; use tracing::instrument; diff --git a/compiler/rustc_hir_typeck/src/diverges.rs b/compiler/rustc_hir_typeck/src/diverges.rs index 3066561a31d..1a10e19d0a5 100644 --- a/compiler/rustc_hir_typeck/src/diverges.rs +++ b/compiler/rustc_hir_typeck/src/diverges.rs @@ -1,6 +1,6 @@ use std::{cmp, ops}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; /// Tracks whether executing a node may exit normally (versus /// return/break/panic, which "diverge", leaving dead code in their diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 821a90d7a8c..015a7283250 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -7,7 +7,7 @@ use rustc_data_structures::unord::UnordMap; use rustc_errors::codes::*; use rustc_errors::{ - pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, StashKey, Subdiagnostic, + Applicability, Diag, ErrorGuaranteed, StashKey, Subdiagnostic, pluralize, struct_span_code_err, }; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::def_id::DefId; @@ -17,26 +17,28 @@ use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _; use rustc_infer::infer; use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; -use rustc_infer::traits::query::NoSolution; use rustc_infer::traits::ObligationCause; +use rustc_infer::traits::query::NoSolution; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_session::errors::ExprParenthesesNeeded; use rustc_session::parse::feature_err; +use rustc_span::Span; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::hygiene::DesugaringKind; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::Span; -use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt}; use smallvec::SmallVec; use tracing::{debug, instrument, trace}; use {rustc_ast as ast, rustc_hir as hir}; +use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation}; +use crate::TupleArgumentsFlag::DontTupleArguments; use crate::coercion::{CoerceMany, DynamicCoerceMany}; use crate::errors::{ AddressOfTemporaryTaken, FieldMultiplySpecifiedInInitializer, @@ -44,11 +46,9 @@ ReturnStmtOutsideOfFnBody, StructExprNonExhaustive, TypeMismatchFruTypo, YieldExprOutsideOfCoroutine, }; -use crate::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation}; -use crate::TupleArgumentsFlag::DontTupleArguments; use crate::{ - cast, fatally_break_rust, report_unexpected_variant_res, type_error_struct, BreakableCtxt, - CoroutineTypes, Diverges, FnCtxt, Needs, + BreakableCtxt, CoroutineTypes, Diverges, FnCtxt, Needs, cast, fatally_break_rust, + report_unexpected_variant_res, type_error_struct, }; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { @@ -72,10 +72,10 @@ pub(crate) fn check_expr_has_type_or_error( } 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; } @@ -1491,8 +1491,10 @@ fn check_expr_repeat( expr: &'tcx hir::Expr<'tcx>, ) -> Ty<'tcx> { let tcx = self.tcx; - let count = self.lower_array_length(count); - if let Some(count) = count.try_eval_target_usize(tcx, self.param_env) { + let count_span = count.span(); + let count = self.try_structurally_resolve_const(count_span, self.lower_array_length(count)); + + if let Some(count) = count.try_to_target_usize(tcx) { self.suggest_array_len(expr, count); } @@ -1520,19 +1522,24 @@ fn check_expr_repeat( return Ty::new_error(tcx, guar); } - self.check_repeat_element_needs_copy_bound(element, count, element_ty); + // If the length is 0, we don't create any elements, so we don't copy any. + // If the length is 1, we don't copy that one element, we move it. Only check + // for `Copy` if the length is larger, or unevaluated. + // FIXME(min_const_generic_exprs): We could perhaps defer this check so that + // we don't require `::CONST` doesn't unnecessarily require `Copy`. + if count.try_to_target_usize(tcx).is_none_or(|x| x > 1) { + self.enforce_repeat_element_needs_copy_bound(element, element_ty); + } let ty = Ty::new_array_with_const_len(tcx, t, count); - self.register_wf_obligation(ty.into(), expr.span, ObligationCauseCode::WellFormed(None)); - ty } - fn check_repeat_element_needs_copy_bound( + /// Requires that `element_ty` is `Copy` (unless it's a const expression itself). + fn enforce_repeat_element_needs_copy_bound( &self, element: &hir::Expr<'_>, - count: ty::Const<'tcx>, element_ty: Ty<'tcx>, ) { let tcx = self.tcx; @@ -1565,27 +1572,23 @@ fn check_repeat_element_needs_copy_bound( _ => traits::IsConstable::No, }; - // If the length is 0, we don't create any elements, so we don't copy any. If the length is 1, we - // don't copy that one element, we move it. Only check for Copy if the length is larger. - if count.try_eval_target_usize(tcx, self.param_env).is_none_or(|len| len > 1) { - let lang_item = self.tcx.require_lang_item(LangItem::Copy, None); - let code = traits::ObligationCauseCode::RepeatElementCopy { - is_constable, - elt_type: element_ty, - elt_span: element.span, - elt_stmt_span: self - .tcx - .hir() - .parent_iter(element.hir_id) - .find_map(|(_, node)| match node { - hir::Node::Item(it) => Some(it.span), - hir::Node::Stmt(stmt) => Some(stmt.span), - _ => None, - }) - .expect("array repeat expressions must be inside an item or statement"), - }; - self.require_type_meets(element_ty, element.span, code, lang_item); - } + let lang_item = self.tcx.require_lang_item(LangItem::Copy, None); + let code = traits::ObligationCauseCode::RepeatElementCopy { + is_constable, + elt_type: element_ty, + elt_span: element.span, + elt_stmt_span: self + .tcx + .hir() + .parent_iter(element.hir_id) + .find_map(|(_, node)| match node { + hir::Node::Item(it) => Some(it.span), + hir::Node::Stmt(stmt) => Some(stmt.span), + _ => None, + }) + .expect("array repeat expressions must be inside an item or statement"), + }; + self.require_type_meets(element_ty, element.span, code, lang_item); } fn check_expr_tuple( @@ -2800,9 +2803,10 @@ fn maybe_suggest_array_indexing( len: ty::Const<'tcx>, ) { err.span_label(field.span, "unknown field"); - if let (Some(len), Ok(user_index)) = - (len.try_eval_target_usize(self.tcx, self.param_env), field.as_str().parse::()) - { + if let (Some(len), Ok(user_index)) = ( + self.try_structurally_resolve_const(base.span, len).try_to_target_usize(self.tcx), + field.as_str().parse::(), + ) { let help = "instead of using tuple indexing, use array indexing"; let applicability = if len < user_index { Applicability::MachineApplicable diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 3b2ddf659a1..29feed56290 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -6,9 +6,9 @@ use std::ops::Deref; use std::slice::from_ref; +use hir::Expr; use hir::def::DefKind; use hir::pat_util::EnumerateAndAdjustIterator as _; -use hir::Expr; use rustc_data_structures::fx::FxIndexMap; use rustc_hir as hir; use rustc_hir::def::{CtorOf, Res}; @@ -20,11 +20,11 @@ pub use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection}; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty::{ - self, adjustment, AdtKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt as _, + self, AdtKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt as _, adjustment, }; use rustc_middle::{bug, span_bug}; use rustc_span::{ErrorGuaranteed, Span}; -use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; use rustc_trait_selection::infer::InferCtxtExt; use tracing::{debug, trace}; use ty::BorrowKind::ImmBorrow; @@ -151,7 +151,8 @@ pub trait TypeInformationCtxt<'tcx> { } impl<'tcx> TypeInformationCtxt<'tcx> for &FnCtxt<'_, 'tcx> { - type TypeckResults<'a> = Ref<'a, ty::TypeckResults<'tcx>> + type TypeckResults<'a> + = Ref<'a, ty::TypeckResults<'tcx>> where Self: 'a; @@ -195,7 +196,8 @@ fn tcx(&self) -> TyCtxt<'tcx> { } impl<'tcx> TypeInformationCtxt<'tcx> for (&LateContext<'tcx>, LocalDefId) { - type TypeckResults<'a> = &'tcx ty::TypeckResults<'tcx> + type TypeckResults<'a> + = &'tcx ty::TypeckResults<'tcx> where Self: 'a; diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 7a6ebf15fa9..4fd508ab896 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -5,18 +5,18 @@ use rustc_data_structures::graph::{self}; use rustc_data_structures::unord::{UnordBag, UnordMap, UnordSet}; use rustc_hir as hir; -use rustc_hir::intravisit::Visitor; use rustc_hir::HirId; +use rustc_hir::intravisit::Visitor; use rustc_infer::infer::{DefineOpaqueTypes, InferOk}; use rustc_middle::bug; use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable}; use rustc_session::lint; use rustc_span::def_id::LocalDefId; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::traits::{ObligationCause, ObligationCtxt}; use tracing::debug; -use crate::{errors, FnCtxt, TypeckRootCtxt}; +use crate::{FnCtxt, TypeckRootCtxt, errors}; #[derive(Copy, Clone)] pub(crate) enum DivergingFallbackBehavior { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 61898b06476..2c469c0d52c 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -28,10 +28,10 @@ }; use rustc_middle::{bug, span_bug}; use rustc_session::lint; +use rustc_span::Span; use rustc_span::def_id::LocalDefId; use rustc_span::hygiene::DesugaringKind; use rustc_span::symbol::kw; -use rustc_span::Span; use rustc_target::abi::FieldIdx; use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded; use rustc_trait_selection::traits::{ @@ -42,7 +42,7 @@ use crate::callee::{self, DeferredCallResolution}; use crate::errors::{self, CtorIsPrivate}; use crate::method::{self, MethodCallee}; -use crate::{rvalue_scopes, BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy}; +use crate::{BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy, rvalue_scopes}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Produces warning on the given node, if the current point in the @@ -224,10 +224,11 @@ pub fn write_user_type_annotation_from_args( debug!("fcx {}", self.tag()); if Self::can_contain_user_lifetime_bounds((args, user_self_ty)) { - let canonicalized = self.canonicalize_user_type_annotation(UserType::TypeOf( - def_id, - UserArgs { args, user_self_ty }, - )); + let canonicalized = + self.canonicalize_user_type_annotation(UserType::TypeOf(def_id, UserArgs { + args, + user_self_ty, + })); debug!(?canonicalized); self.write_user_type_annotation(hir_id, canonicalized); } @@ -270,13 +271,10 @@ pub fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec> } 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) { @@ -968,16 +966,11 @@ pub(crate) fn note_internal_mutation_in_method( 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 = @@ -1477,6 +1470,33 @@ pub fn try_structurally_resolve_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> } } + #[instrument(level = "debug", skip(self, sp), ret)] + pub fn try_structurally_resolve_const(&self, sp: Span, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { + // FIXME(min_const_generic_exprs): We could process obligations here if `ct` is a var. + + if self.next_trait_solver() + && let ty::ConstKind::Unevaluated(..) = ct.kind() + { + // We need to use a separate variable here as otherwise the temporary for + // `self.fulfillment_cx.borrow_mut()` is alive in the `Err` branch, resulting + // in a reentrant borrow, causing an ICE. + let result = self + .at(&self.misc(sp), self.param_env) + .structurally_normalize_const(ct, &mut **self.fulfillment_cx.borrow_mut()); + match result { + Ok(normalized_ct) => normalized_ct, + Err(errors) => { + let guar = self.err_ctxt().report_fulfillment_errors(errors); + return ty::Const::new_error(self.tcx, guar); + } + } + } else if self.tcx.features().generic_const_exprs { + ct.normalize(self.tcx, self.param_env) + } else { + ct + } + } + /// Resolves `ty` by a single level if `ty` is a type variable. /// /// When the new solver is enabled, this will also attempt to normalize diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index a8ba9f139cc..f93d0e93406 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -5,8 +5,8 @@ use rustc_hir::def_id::DefId; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor}; -use rustc_span::symbol::kw; use rustc_span::Span; +use rustc_span::symbol::kw; use rustc_trait_selection::traits; use crate::FnCtxt; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 8810f14aaa9..550c58b5a17 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -4,8 +4,8 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_errors::codes::*; use rustc_errors::{ - a_or_an, display_list_with_comma_and, pluralize, Applicability, Diag, ErrorGuaranteed, - MultiSpan, StashKey, + Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, a_or_an, + display_list_with_comma_and, pluralize, }; use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::DefId; @@ -22,28 +22,28 @@ use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_session::Session; -use rustc_span::symbol::{kw, Ident}; -use rustc_span::{sym, Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, kw}; +use rustc_span::{DUMMY_SP, Span, sym}; use rustc_trait_selection::error_reporting::infer::{FailureCode, ObligationCauseExt}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{self, ObligationCauseCode, ObligationCtxt, SelectionContext}; use tracing::debug; use {rustc_ast as ast, rustc_hir as hir}; +use crate::Expectation::*; +use crate::TupleArgumentsFlag::*; use crate::coercion::CoerceMany; use crate::errors::SuggestPtrNullMut; use crate::fn_ctxt::arg_matrix::{ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx}; use crate::fn_ctxt::infer::FnCall; use crate::gather_locals::Declaration; +use crate::method::MethodCallee; use crate::method::probe::IsSuggestion; use crate::method::probe::Mode::MethodCall; use crate::method::probe::ProbeScope::TraitsInScope; -use crate::method::MethodCallee; -use crate::Expectation::*; -use crate::TupleArgumentsFlag::*; use crate::{ - errors, struct_span_code_err, BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy, Needs, - TupleArgumentsFlag, + BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy, Needs, TupleArgumentsFlag, errors, + struct_span_code_err, }; #[derive(Clone, Copy, Default)] diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index a43d7aa31a5..e60bd1a312a 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -17,9 +17,9 @@ use rustc_middle::ty::{self, Const, Ty, TyCtxt, TypeVisitableExt}; use rustc_session::Session; use rustc_span::symbol::Ident; -use rustc_span::{self, sym, Span, DUMMY_SP}; -use rustc_trait_selection::error_reporting::infer::sub_relations::SubRelations; +use rustc_span::{self, DUMMY_SP, Span, sym}; use rustc_trait_selection::error_reporting::TypeErrCtxt; +use rustc_trait_selection::error_reporting::infer::sub_relations::SubRelations; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt}; use crate::coercion::DynamicCoerceMany; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index b71e34864fd..5f89f7dedc2 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -19,15 +19,15 @@ use rustc_middle::span_bug; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{ - self, suggest_constraining_type_params, Article, Binder, IsSuggestable, Ty, TyCtxt, - TypeVisitableExt, Upcast, + self, Article, Binder, IsSuggestable, Ty, TyCtxt, TypeVisitableExt, Upcast, + suggest_constraining_type_params, }; use rustc_session::errors::ExprParenthesesNeeded; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{sym, Ident}; +use rustc_span::symbol::{Ident, sym}; use rustc_span::{Span, Symbol}; -use rustc_trait_selection::error_reporting::traits::DefIdOrName; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; +use rustc_trait_selection::error_reporting::traits::DefIdOrName; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; @@ -1502,7 +1502,10 @@ pub(crate) fn suggest_deref_unwrap_or( // Create an dummy type `&[_]` so that both &[] and `&Vec` can coerce to it. let dummy_ty = if let ty::Array(elem_ty, size) = peeled.kind() && let ty::Infer(_) = elem_ty.kind() - && size.try_eval_target_usize(self.tcx, self.param_env) == Some(0) + && self + .try_structurally_resolve_const(provided_expr.span, *size) + .try_to_target_usize(self.tcx) + == Some(0) { let slice = Ty::new_slice(self.tcx, *elem_ty); Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, slice) @@ -2001,17 +2004,17 @@ pub(crate) fn suggest_missing_unwrap_expect( 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/gather_locals.rs b/compiler/rustc_hir_typeck/src/gather_locals.rs index 2f990de7e31..83c9a4878d2 100644 --- a/compiler/rustc_hir_typeck/src/gather_locals.rs +++ b/compiler/rustc_hir_typeck/src/gather_locals.rs @@ -3,8 +3,8 @@ use rustc_hir::{HirId, PatKind}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::ty::{Ty, UserType}; -use rustc_span::def_id::LocalDefId; use rustc_span::Span; +use rustc_span::def_id::LocalDefId; use tracing::debug; use crate::FnCtxt; diff --git a/compiler/rustc_hir_typeck/src/intrinsicck.rs b/compiler/rustc_hir_typeck/src/intrinsicck.rs index 81d940a3f9b..a4121adf628 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -101,7 +101,9 @@ pub(crate) fn check_transmute(&self, from: Ty<'tcx>, to: Ty<'tcx>, hir_id: HirId } } Ok(SizeSkeleton::Generic(size)) => { - if let Some(size) = size.try_eval_target_usize(tcx, self.param_env) { + if let Some(size) = + self.try_structurally_resolve_const(span, size).try_to_target_usize(tcx) + { format!("{size} bytes") } else { format!("generic size {size}") diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index e2c1eef837f..f8352d9d44a 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -43,7 +43,7 @@ use fn_ctxt::FnCtxt; use rustc_data_structures::unord::UnordSet; use rustc_errors::codes::*; -use rustc_errors::{pluralize, struct_span_code_err, Applicability, ErrorGuaranteed}; +use rustc_errors::{Applicability, ErrorGuaranteed, pluralize, struct_span_code_err}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::Visitor; @@ -55,8 +55,8 @@ use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_session::config; -use rustc_span::def_id::LocalDefId; use rustc_span::Span; +use rustc_span::def_id::LocalDefId; use tracing::{debug, instrument}; use typeck_root_ctxt::TypeckRootCtxt; diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 10a22eee7b7..e3b0fa78eb7 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -1,8 +1,8 @@ use std::ops::Deref; use rustc_hir as hir; -use rustc_hir::def_id::DefId; use rustc_hir::GenericArg; +use rustc_hir::def_id::DefId; use rustc_hir_analysis::hir_ty_lowering::generics::{ check_generic_arg_count_for_call, lower_generic_args, }; @@ -20,12 +20,12 @@ UserType, }; use rustc_middle::{bug, span_bug}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_trait_selection::traits; use tracing::debug; -use super::{probe, MethodCallee}; -use crate::{callee, FnCtxt}; +use super::{MethodCallee, probe}; +use crate::{FnCtxt, callee}; struct ConfirmContext<'a, 'tcx> { fcx: &'a FnCtxt<'a, 'tcx>, diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index 7019b718b16..586b753f454 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -18,14 +18,14 @@ self, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TypeVisitableExt, }; use rustc_middle::{bug, span_bug}; -use rustc_span::symbol::Ident; use rustc_span::Span; +use rustc_span::symbol::Ident; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::{self, NormalizeExt}; use tracing::{debug, instrument}; -use self::probe::{IsSuggestion, ProbeScope}; pub(crate) use self::MethodError::*; +use self::probe::{IsSuggestion, ProbeScope}; use crate::FnCtxt; pub(crate) fn provide(providers: &mut Providers) { diff --git a/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs b/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs index ac5e1040803..a8b5b6165db 100644 --- a/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs +++ b/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs @@ -8,14 +8,14 @@ use rustc_middle::span_bug; use rustc_middle::ty::{self, Ty}; use rustc_session::lint::builtin::{RUST_2021_PRELUDE_COLLISIONS, RUST_2024_PRELUDE_COLLISIONS}; -use rustc_span::symbol::kw::{Empty, Underscore}; -use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use rustc_span::symbol::kw::{Empty, Underscore}; +use rustc_span::symbol::{Ident, sym}; use rustc_trait_selection::infer::InferCtxtExt; use tracing::debug; -use crate::method::probe::{self, Pick}; use crate::FnCtxt; +use crate::method::probe::{self, Pick}; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(super) fn lint_edition_dependent_dot_call( diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index 17aa43ae7c0..3828b40b885 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -6,15 +6,15 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::Applicability; use rustc_hir as hir; -use rustc_hir::def::DefKind; use rustc_hir::HirId; +use rustc_hir::def::DefKind; use rustc_hir_analysis::autoderef::{self, Autoderef}; use rustc_infer::infer::canonical::{Canonical, OriginalQueryValues, QueryResponse}; use rustc_infer::infer::{self, DefineOpaqueTypes, InferOk, TyCtxtInferExt}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::middle::stability; use rustc_middle::query::Providers; -use rustc_middle::ty::fast_reject::{simplify_type, TreatParams}; +use rustc_middle::ty::fast_reject::{TreatParams, simplify_type}; use rustc_middle::ty::{ self, AssocItem, AssocItemContainer, GenericArgs, GenericArgsRef, GenericParamDefKind, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt, Upcast, @@ -25,22 +25,22 @@ use rustc_span::edit_distance::{ edit_distance_with_substrings, find_best_match_for_name_with_substrings, }; -use rustc_span::symbol::{sym, Ident}; -use rustc_span::{Span, Symbol, DUMMY_SP}; +use rustc_span::symbol::{Ident, sym}; +use rustc_span::{DUMMY_SP, Span, Symbol}; use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded; use rustc_trait_selection::infer::InferCtxtExt as _; +use rustc_trait_selection::traits::query::CanonicalTyGoal; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::query::method_autoderef::{ CandidateStep, MethodAutoderefBadTy, MethodAutoderefStepsResult, }; -use rustc_trait_selection::traits::query::CanonicalTyGoal; use rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; use self::CandidateKind::*; pub(crate) use self::PickKind::*; -use super::{suggest, CandidateSource, MethodError, NoMatchData}; +use super::{CandidateSource, MethodError, NoMatchData, suggest}; use crate::FnCtxt; /// Boolean flag used to indicate if this search is for a suggestion diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index deabf693af2..feb47209f5e 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -13,7 +13,7 @@ use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::unord::UnordSet; use rustc_errors::codes::*; -use rustc_errors::{pluralize, struct_span_code_err, Applicability, Diag, MultiSpan, StashKey}; +use rustc_errors::{Applicability, Diag, MultiSpan, StashKey, pluralize, struct_span_code_err}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{self, Visitor}; @@ -21,21 +21,21 @@ use rustc_hir::{self as hir, ExprKind, HirId, Node, PathSegment, QPath}; use rustc_infer::infer::{self, RegionVariableOrigin}; use rustc_middle::bug; -use rustc_middle::ty::fast_reject::{simplify_type, DeepRejectCtxt, TreatParams}; +use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams, simplify_type}; use rustc_middle::ty::print::{ - with_crate_prefix, with_forced_trimmed_paths, PrintTraitRefExt as _, + PrintTraitRefExt as _, with_crate_prefix, with_forced_trimmed_paths, }; use rustc_middle::ty::{self, GenericArgKind, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::def_id::DefIdSet; -use rustc_span::symbol::{kw, sym, Ident}; +use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{ - edit_distance, ErrorGuaranteed, ExpnKind, FileName, MacroKind, Span, Symbol, DUMMY_SP, + DUMMY_SP, ErrorGuaranteed, ExpnKind, FileName, MacroKind, Span, Symbol, edit_distance, }; use rustc_trait_selection::error_reporting::traits::on_unimplemented::OnUnimplementedNote; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; use rustc_trait_selection::traits::{ - supertraits, FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, + FulfillmentError, Obligation, ObligationCause, ObligationCauseCode, supertraits, }; use tracing::{debug, info, instrument}; @@ -1721,20 +1721,7 @@ fn report_no_match_method_error( } } - if item_name.name == sym::as_str && rcvr_ty.peel_refs().is_str() { - let msg = "remove this method call"; - let mut fallback_span = true; - if let SelfSource::MethodCall(expr) = source { - let call_expr = self.tcx.hir().expect_expr(self.tcx.parent_hir_id(expr.hir_id)); - if let Some(span) = call_expr.span.trim_start(expr.span) { - err.span_suggestion(span, msg, "", Applicability::MachineApplicable); - fallback_span = false; - } - } - if fallback_span { - err.span_label(span, msg); - } - } else if let Some(similar_candidate) = similar_candidate { + if let Some(similar_candidate) = similar_candidate { // Don't emit a suggestion if we found an actual method // that had unsatisfied trait bounds if unsatisfied_predicates.is_empty() diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index c74270fc0e6..1574e9e98d4 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -2,7 +2,7 @@ use rustc_data_structures::packed::Pu128; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, Applicability, Diag}; +use rustc_errors::{Applicability, Diag, struct_span_code_err}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, @@ -11,17 +11,17 @@ use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; use rustc_session::errors::ExprParenthesesNeeded; -use rustc_span::source_map::Spanned; -use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use rustc_span::source_map::Spanned; +use rustc_span::symbol::{Ident, sym}; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{FulfillmentError, ObligationCtxt}; use rustc_type_ir::TyKind::*; use tracing::debug; use {rustc_ast as ast, rustc_hir as hir}; -use super::method::MethodCallee; use super::FnCtxt; +use super::method::MethodCallee; use crate::Expectation; impl<'a, 'tcx> FnCtxt<'a, 'tcx> { @@ -896,17 +896,13 @@ fn lookup_op_method( let opname = Ident::with_dummy_span(opname); let (opt_rhs_expr, opt_rhs_ty) = opt_rhs.unzip(); let input_types = opt_rhs_ty.as_slice(); - 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(), diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index 7dd6deb4fe6..49c5a7d8a65 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -5,7 +5,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_errors::codes::*; use rustc_errors::{ - pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, + Applicability, Diag, ErrorGuaranteed, MultiSpan, pluralize, struct_span_code_err, }; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::pat_util::EnumerateAndAdjustIterator; @@ -18,8 +18,8 @@ use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::hygiene::DesugaringKind; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{kw, sym, Ident}; -use rustc_span::{BytePos, Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, kw, sym}; +use rustc_span::{BytePos, DUMMY_SP, Span}; use rustc_target::abi::FieldIdx; use rustc_trait_selection::infer::InferCtxtExt; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode}; @@ -28,7 +28,7 @@ use super::report_unexpected_variant_res; use crate::gather_locals::DeclOrigin; -use crate::{errors, FnCtxt, LoweredTy}; +use crate::{FnCtxt, LoweredTy, errors}; const CANNOT_IMPLICITLY_DEREF_POINTER_TRAIT_OBJ: &str = "\ This error indicates that a pointer to a trait type cannot be implicitly dereferenced by a \ @@ -2412,7 +2412,7 @@ fn check_array_pat_len( len: ty::Const<'tcx>, min_len: u64, ) -> (Option>, Ty<'tcx>) { - let len = len.try_eval_target_usize(self.tcx, self.param_env); + let len = self.try_structurally_resolve_const(span, len).try_to_target_usize(self.tcx); let guar = if let Some(len) = len { // Now we know the length... diff --git a/compiler/rustc_hir_typeck/src/place_op.rs b/compiler/rustc_hir_typeck/src/place_op.rs index e7f47ee56c9..8604f5f6920 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -7,8 +7,8 @@ PointerCoercion, }; use rustc_middle::ty::{self, Ty}; -use rustc_span::symbol::{sym, Ident}; use rustc_span::Span; +use rustc_span::symbol::{Ident, sym}; use tracing::debug; use {rustc_ast as ast, rustc_hir as hir}; @@ -30,13 +30,10 @@ pub(super) fn lookup_derefing( let ok = self.try_overloaded_deref(expr.span, oprnd_ty)?; let method = self.register_infer_ok_obligations(ok); if let ty::Ref(region, _, hir::Mutability::Not) = method.sig.inputs()[0].kind() { - self.apply_adjustments( - oprnd_expr, - vec![Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(*region, AutoBorrowMutability::Not)), - target: method.sig.inputs()[0], - }], - ); + self.apply_adjustments(oprnd_expr, vec![Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(*region, 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/rvalue_scopes.rs b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs index d65aaef4e8b..98d7f777d6b 100644 --- a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs +++ b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs @@ -1,5 +1,5 @@ -use hir::def_id::DefId; use hir::Node; +use hir::def_id::DefId; use rustc_hir as hir; use rustc_middle::bug; use rustc_middle::middle::region::{RvalueCandidateType, Scope, ScopeTree}; diff --git a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs index 52fa30a352f..18e40cfa428 100644 --- a/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs +++ b/compiler/rustc_hir_typeck/src/typeck_root_ctxt.rs @@ -9,8 +9,8 @@ use rustc_middle::span_bug; use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::def_id::LocalDefIdMap; use rustc_span::Span; +use rustc_span::def_id::LocalDefIdMap; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::{ self, FulfillmentError, PredicateObligation, TraitEngine, TraitEngineExt as _, diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 7688a63a30a..c5843b883a1 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -36,9 +36,9 @@ use rustc_data_structures::unord::{ExtendUnord, UnordSet}; use rustc_errors::{Applicability, MultiSpan}; use rustc_hir as hir; +use rustc_hir::HirId; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::HirId; use rustc_middle::hir::place::{Place, PlaceBase, PlaceWithHirId, Projection, ProjectionKind}; use rustc_middle::mir::FakeReadCause; use rustc_middle::traits::ObligationCauseCode; @@ -48,7 +48,7 @@ }; use rustc_middle::{bug, span_bug}; use rustc_session::lint; -use rustc_span::{sym, BytePos, Pos, Span, Symbol}; +use rustc_span::{BytePos, Pos, Span, Symbol, sym}; use rustc_target::abi::FIRST_VARIANT; use rustc_trait_selection::infer::InferCtxtExt; use tracing::{debug, instrument}; @@ -287,14 +287,11 @@ fn analyze_closure( 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, + })); } } @@ -381,11 +378,11 @@ fn analyze_closure( 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::BrEnv }, - ); + let closure_env_region: ty::Region<'_> = + ty::Region::new_bound(self.tcx, ty::INNERMOST, ty::BoundRegion { + var: ty::BoundVar::ZERO, + kind: ty::BoundRegionKind::BrEnv, + }); let num_args = args .as_coroutine_closure() @@ -2004,14 +2001,11 @@ fn consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>, diag_expr_id: HirId) 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")] @@ -2038,14 +2032,11 @@ fn borrow( capture_kind = ty::UpvarCapture::ByRef(ty::BorrowKind::ImmBorrow); } - 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_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 2fbbc3200e1..3254dddaee9 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -7,16 +7,16 @@ use rustc_data_structures::unord::ExtendUnord; use rustc_errors::{ErrorGuaranteed, StashKey}; use rustc_hir as hir; -use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::HirId; +use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::span_bug; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCoercion}; use rustc_middle::ty::fold::{TypeFoldable, TypeFolder}; use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{self, Ty, TyCtxt, TypeSuperFoldable}; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use rustc_trait_selection::error_reporting::infer::need_type_info::TypeAnnotationNeeded; use rustc_trait_selection::solve; use tracing::{debug, instrument}; diff --git a/compiler/rustc_incremental/src/assert_dep_graph.rs b/compiler/rustc_incremental/src/assert_dep_graph.rs index 46f30526d2a..646b9dbe133 100644 --- a/compiler/rustc_incremental/src/assert_dep_graph.rs +++ b/compiler/rustc_incremental/src/assert_dep_graph.rs @@ -38,17 +38,17 @@ use std::io::{BufWriter, Write}; use rustc_data_structures::fx::FxIndexSet; -use rustc_data_structures::graph::implementation::{Direction, NodeIndex, INCOMING, OUTGOING}; -use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_data_structures::graph::implementation::{Direction, INCOMING, NodeIndex, OUTGOING}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_middle::dep_graph::{ - dep_kinds, DepGraphQuery, DepKind, DepNode, DepNodeExt, DepNodeFilter, EdgeFilter, + DepGraphQuery, DepKind, DepNode, DepNodeExt, DepNodeFilter, EdgeFilter, dep_kinds, }; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_middle::{bug, span_bug}; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, sym}; use tracing::debug; use {rustc_ast as ast, rustc_graphviz as dot, rustc_hir as hir}; diff --git a/compiler/rustc_incremental/src/lib.rs b/compiler/rustc_incremental/src/lib.rs index c79d108183c..dda1232b80b 100644 --- a/compiler/rustc_incremental/src/lib.rs +++ b/compiler/rustc_incremental/src/lib.rs @@ -14,9 +14,9 @@ mod persist; pub use persist::{ - copy_cgu_workproduct_to_incr_comp_cache_dir, finalize_session_directory, in_incr_comp_dir, - in_incr_comp_dir_sess, load_query_result_cache, save_dep_graph, save_work_product_index, - setup_dep_graph, LoadResult, + LoadResult, copy_cgu_workproduct_to_incr_comp_cache_dir, finalize_session_directory, + in_incr_comp_dir, in_incr_comp_dir_sess, load_query_result_cache, save_dep_graph, + save_work_product_index, setup_dep_graph, }; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index cef0b23143d..9dc5cbaafce 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -23,12 +23,12 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::unord::UnordSet; use rustc_hir::def_id::LocalDefId; -use rustc_hir::{intravisit, ImplItemKind, ItemKind as HirItem, Node as HirNode, TraitItemKind}; -use rustc_middle::dep_graph::{label_strs, DepNode, DepNodeExt}; +use rustc_hir::{ImplItemKind, ItemKind as HirItem, Node as HirNode, TraitItemKind, intravisit}; +use rustc_middle::dep_graph::{DepNode, DepNodeExt, label_strs}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, sym}; use thin_vec::ThinVec; use tracing::debug; @@ -106,10 +106,11 @@ 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_incremental/src/persist/file_format.rs b/compiler/rustc_incremental/src/persist/file_format.rs index f834c48cbf8..4c664ea6ba0 100644 --- a/compiler/rustc_incremental/src/persist/file_format.rs +++ b/compiler/rustc_incremental/src/persist/file_format.rs @@ -15,8 +15,8 @@ use std::{env, fs}; use rustc_data_structures::memmap::Mmap; -use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_serialize::Encoder; +use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_session::Session; use tracing::debug; diff --git a/compiler/rustc_incremental/src/persist/fs.rs b/compiler/rustc_incremental/src/persist/fs.rs index feb25a9a89d..8769c4173c8 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -108,14 +108,14 @@ use std::path::{Path, PathBuf}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; -use rand::{thread_rng, RngCore}; -use rustc_data_structures::base_n::{BaseNString, ToBaseN, CASE_INSENSITIVE}; +use rand::{RngCore, thread_rng}; +use rustc_data_structures::base_n::{BaseNString, CASE_INSENSITIVE, ToBaseN}; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_data_structures::svh::Svh; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_data_structures::{base_n, flock}; use rustc_errors::ErrorGuaranteed; -use rustc_fs_util::{link_or_copy, try_canonicalize, LinkOrCopy}; +use rustc_fs_util::{LinkOrCopy, link_or_copy, try_canonicalize}; use rustc_middle::bug; use rustc_session::config::CrateType; use rustc_session::output::{collect_crate_types, find_crate_name}; diff --git a/compiler/rustc_incremental/src/persist/load.rs b/compiler/rustc_incremental/src/persist/load.rs index 18088a10dd0..c74804cc798 100644 --- a/compiler/rustc_incremental/src/persist/load.rs +++ b/compiler/rustc_incremental/src/persist/load.rs @@ -7,10 +7,10 @@ use rustc_data_structures::unord::UnordMap; use rustc_middle::dep_graph::{DepGraph, DepsType, SerializedDepGraph, WorkProductMap}; use rustc_middle::query::on_disk_cache::OnDiskCache; -use rustc_serialize::opaque::MemDecoder; use rustc_serialize::Decodable; -use rustc_session::config::IncrementalStateAssertion; +use rustc_serialize::opaque::MemDecoder; use rustc_session::Session; +use rustc_session::config::IncrementalStateAssertion; use rustc_span::ErrorGuaranteed; use tracing::{debug, warn}; diff --git a/compiler/rustc_incremental/src/persist/mod.rs b/compiler/rustc_incremental/src/persist/mod.rs index a529b1dcec0..186db0a60a3 100644 --- a/compiler/rustc_incremental/src/persist/mod.rs +++ b/compiler/rustc_incremental/src/persist/mod.rs @@ -11,6 +11,6 @@ mod work_product; pub use fs::{finalize_session_directory, in_incr_comp_dir, in_incr_comp_dir_sess}; -pub use load::{load_query_result_cache, setup_dep_graph, LoadResult}; +pub use load::{LoadResult, load_query_result_cache, setup_dep_graph}; pub use save::{save_dep_graph, save_work_product_index}; pub use work_product::copy_cgu_workproduct_to_incr_comp_cache_dir; diff --git a/compiler/rustc_incremental/src/persist/save.rs b/compiler/rustc_incremental/src/persist/save.rs index 58a03cb8b30..53726df4597 100644 --- a/compiler/rustc_incremental/src/persist/save.rs +++ b/compiler/rustc_incremental/src/persist/save.rs @@ -7,8 +7,8 @@ DepGraph, SerializedDepGraph, WorkProduct, WorkProductId, WorkProductMap, }; use rustc_middle::ty::TyCtxt; -use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_serialize::Encodable as RustcEncodable; +use rustc_serialize::opaque::{FileEncodeResult, FileEncoder}; use rustc_session::Session; use tracing::debug; diff --git a/compiler/rustc_index/src/bit_set.rs b/compiler/rustc_index/src/bit_set.rs index 506afbae40c..c2b9cae680b 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -3,11 +3,11 @@ use std::rc::Rc; use std::{fmt, iter, mem, slice}; +use Chunk::*; use arrayvec::ArrayVec; #[cfg(feature = "nightly")] use rustc_macros::{Decodable_Generic, Encodable_Generic}; -use smallvec::{smallvec, SmallVec}; -use Chunk::*; +use smallvec::{SmallVec, smallvec}; use crate::{Idx, IndexVec}; diff --git a/compiler/rustc_index/src/bit_set/tests.rs b/compiler/rustc_index/src/bit_set/tests.rs index 066aa46e350..21e681d63f6 100644 --- a/compiler/rustc_index/src/bit_set/tests.rs +++ b/compiler/rustc_index/src/bit_set/tests.rs @@ -182,10 +182,11 @@ 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)); @@ -204,10 +205,11 @@ 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 { @@ -222,20 +224,17 @@ 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 { @@ -250,14 +249,11 @@ 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); @@ -274,14 +270,11 @@ 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 { @@ -311,14 +304,11 @@ 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 381d79c24fc..9cee2f2f5b2 100644 --- a/compiler/rustc_index/src/vec/tests.rs +++ b/compiler/rustc_index/src/vec/tests.rs @@ -29,19 +29,21 @@ 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/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index 1930e357fc9..35ea4233825 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -15,10 +15,10 @@ use smallvec::SmallVec; use tracing::debug; +use crate::infer::InferCtxt; use crate::infer::canonical::{ Canonical, CanonicalTyVarKind, CanonicalVarInfo, CanonicalVarKind, OriginalQueryValues, }; -use crate::infer::InferCtxt; impl<'tcx> InferCtxt<'tcx> { /// Canonicalizes a query value `V`. When we canonicalize a query, diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index 95d7bb7eb38..7791bd73628 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -19,7 +19,7 @@ use rustc_middle::{bug, span_bug}; use tracing::{debug, instrument}; -use crate::infer::canonical::instantiate::{instantiate_value, CanonicalExt}; +use crate::infer::canonical::instantiate::{CanonicalExt, instantiate_value}; use crate::infer::canonical::{ Canonical, CanonicalQueryResponse, CanonicalVarValues, Certainty, OriginalQueryValues, QueryOutlivesConstraint, QueryRegionConstraints, QueryResponse, diff --git a/compiler/rustc_infer/src/infer/context.rs b/compiler/rustc_infer/src/infer/context.rs index 95888beb6b1..c06836edcfb 100644 --- a/compiler/rustc_infer/src/infer/context.rs +++ b/compiler/rustc_infer/src/infer/context.rs @@ -1,12 +1,12 @@ ///! Definition of `InferCtxtLike` from the librarified type layer. use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_middle::traits::solve::{Goal, NoSolution, SolverMode}; use rustc_middle::traits::ObligationCause; +use rustc_middle::traits::solve::{Goal, NoSolution, SolverMode}; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::DUMMY_SP; -use rustc_type_ir::relate::Relate; use rustc_type_ir::InferCtxtLike; +use rustc_type_ir::relate::Relate; use super::{BoundRegionConversionTime, InferCtxt, SubregionOrigin}; diff --git a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs index aab64883bc5..6af49accc84 100644 --- a/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs +++ b/compiler/rustc_infer/src/infer/lexical_region_resolve/mod.rs @@ -4,7 +4,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::graph::implementation::{ - Direction, Graph, NodeIndex, INCOMING, OUTGOING, + Direction, Graph, INCOMING, NodeIndex, OUTGOING, }; use rustc_data_structures::intern::Interned; use rustc_data_structures::unord::UnordSet; diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 0e767b7fb2e..5fa1bf51634 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -1,6 +1,9 @@ use std::cell::{Cell, RefCell}; use std::fmt; +pub use BoundRegionConversionTime::*; +pub use RegionVariableOrigin::*; +pub use SubregionOrigin::*; pub use at::DefineOpaqueTypes; use free_regions::RegionRelations; pub use freshen::TypeFreshener; @@ -10,8 +13,8 @@ use region_constraints::{ GenericKind, RegionConstraintCollector, RegionConstraintStorage, VarInfos, VerifyBound, }; -pub use relate::combine::{CombineFields, PredicateEmittingRelation}; pub use relate::StructurallyRelateAliases; +pub use relate::combine::{CombineFields, PredicateEmittingRelation}; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::sync::Lrc; @@ -26,29 +29,26 @@ use rustc_middle::infer::unify_key::{ ConstVariableOrigin, ConstVariableValue, ConstVidKey, EffectVarValue, EffectVidKey, }; -use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult}; use rustc_middle::mir::ConstraintCategory; +use rustc_middle::mir::interpret::{ErrorHandled, EvalToValTreeResult}; use rustc_middle::traits::select; use rustc_middle::traits::solve::{Goal, NoSolution}; +pub use rustc_middle::ty::IntVarValue; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fold::{ BoundVarReplacerDelegate, TypeFoldable, TypeFolder, TypeSuperFoldable, }; use rustc_middle::ty::visit::TypeVisitableExt; -pub use rustc_middle::ty::IntVarValue; use rustc_middle::ty::{ self, ConstVid, EffectVid, FloatVid, GenericArg, GenericArgKind, GenericArgs, GenericArgsRef, GenericParamDefKind, InferConst, IntVid, Ty, TyCtxt, TyVid, }; use rustc_middle::{bug, span_bug}; -use rustc_span::symbol::Symbol; use rustc_span::Span; +use rustc_span::symbol::Symbol; use snapshot::undo_log::InferCtxtUndoLogs; use tracing::{debug, instrument}; use type_variable::TypeVariableOrigin; -pub use BoundRegionConversionTime::*; -pub use RegionVariableOrigin::*; -pub use SubregionOrigin::*; use crate::infer::relate::RelateResult; use crate::traits::{self, ObligationCause, ObligationInspector, PredicateObligation, TraitEngine}; @@ -1776,16 +1776,13 @@ fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'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) } @@ -1793,17 +1790,14 @@ fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'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_infer/src/infer/opaque_types/mod.rs b/compiler/rustc_infer/src/infer/opaque_types/mod.rs index 5ceaaf1a3c4..55c51bc856f 100644 --- a/compiler/rustc_infer/src/infer/opaque_types/mod.rs +++ b/compiler/rustc_infer/src/infer/opaque_types/mod.rs @@ -2,8 +2,8 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync::Lrc; use rustc_hir as hir; -use rustc_middle::traits::solve::Goal; use rustc_middle::traits::ObligationCause; +use rustc_middle::traits::solve::Goal; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fold::BottomUpFolder; use rustc_middle::ty::{ diff --git a/compiler/rustc_infer/src/infer/outlives/env.rs b/compiler/rustc_infer/src/infer/outlives/env.rs index 77c711e57bb..a071b84a1a0 100644 --- a/compiler/rustc_infer/src/infer/outlives/env.rs +++ b/compiler/rustc_infer/src/infer/outlives/env.rs @@ -5,8 +5,8 @@ use tracing::{debug, instrument}; use super::explicit_outlives_bounds; -use crate::infer::free_regions::FreeRegionMap; use crate::infer::GenericKind; +use crate::infer::free_regions::FreeRegionMap; use crate::traits::query::OutlivesBound; /// The `OutlivesEnvironment` collects information about what outlives diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index 0c397350067..634cda86bc3 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -68,7 +68,7 @@ TypeFoldable as _, TypeVisitableExt, }; use rustc_span::DUMMY_SP; -use rustc_type_ir::outlives::{push_outlives_components, Component}; +use rustc_type_ir::outlives::{Component, push_outlives_components}; use smallvec::smallvec; use tracing::{debug, instrument}; @@ -101,19 +101,15 @@ pub fn register_region_obligation_with_cause( ) { 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, ..) - if !span.is_dummy() => - { - Some(*span) - } - _ => None, - }, - ) + infer::RelateParamBound(cause.span, sup_type, match cause.code().peel_derives() { + ObligationCauseCode::WhereClause(_, span) + | ObligationCauseCode::WhereClauseInExpr(_, 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/outlives/verify.rs b/compiler/rustc_infer/src/infer/outlives/verify.rs index 711f20444de..74a80a1b9aa 100644 --- a/compiler/rustc_infer/src/infer/outlives/verify.rs +++ b/compiler/rustc_infer/src/infer/outlives/verify.rs @@ -1,7 +1,7 @@ use std::assert_matches::assert_matches; use rustc_middle::ty::{self, OutlivesPredicate, Ty, TyCtxt}; -use rustc_type_ir::outlives::{compute_alias_components_recursive, Component}; +use rustc_type_ir::outlives::{Component, compute_alias_components_recursive}; use smallvec::smallvec; use tracing::{debug, instrument, trace}; diff --git a/compiler/rustc_infer/src/infer/relate/combine.rs b/compiler/rustc_infer/src/infer/relate/combine.rs index f2ec1dd3df7..e75d7b7db14 100644 --- a/compiler/rustc_infer/src/infer/relate/combine.rs +++ b/compiler/rustc_infer/src/infer/relate/combine.rs @@ -30,7 +30,7 @@ use super::lub::Lub; use super::type_relating::TypeRelating; use super::{RelateResult, StructurallyRelateAliases}; -use crate::infer::{relate, DefineOpaqueTypes, InferCtxt, TypeTrace}; +use crate::infer::{DefineOpaqueTypes, InferCtxt, TypeTrace, relate}; use crate::traits::{Obligation, PredicateObligation}; #[derive(Clone)] diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index fbe64f47741..a6d10aa5968 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -17,7 +17,7 @@ PredicateEmittingRelation, Relate, RelateResult, StructurallyRelateAliases, TypeRelation, }; use crate::infer::type_variable::TypeVariableValue; -use crate::infer::{relate, InferCtxt, RegionVariableOrigin}; +use crate::infer::{InferCtxt, RegionVariableOrigin, relate}; impl<'tcx> InferCtxt<'tcx> { /// The idea is that we should ensure that the type variable `target_vid` diff --git a/compiler/rustc_infer/src/infer/relate/glb.rs b/compiler/rustc_infer/src/infer/relate/glb.rs index 7b12003643e..ed108f42969 100644 --- a/compiler/rustc_infer/src/infer/relate/glb.rs +++ b/compiler/rustc_infer/src/infer/relate/glb.rs @@ -6,9 +6,9 @@ use rustc_span::Span; use tracing::{debug, instrument}; +use super::StructurallyRelateAliases; use super::combine::{CombineFields, PredicateEmittingRelation}; use super::lattice::{self, LatticeDir}; -use super::StructurallyRelateAliases; use crate::infer::{DefineOpaqueTypes, InferCtxt, SubregionOrigin}; use crate::traits::ObligationCause; diff --git a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs index ab6a19265f3..7908733e734 100644 --- a/compiler/rustc_infer/src/infer/relate/higher_ranked.rs +++ b/compiler/rustc_infer/src/infer/relate/higher_ranked.rs @@ -6,8 +6,8 @@ use tracing::{debug, instrument}; use super::RelateResult; -use crate::infer::snapshot::CombinedSnapshot; use crate::infer::InferCtxt; +use crate::infer::snapshot::CombinedSnapshot; impl<'tcx> InferCtxt<'tcx> { /// Replaces all bound variables (lifetimes, types, and constants) bound by @@ -34,22 +34,22 @@ pub fn enter_forall_and_leak_universe(&self, binder: ty::Binder<'tcx, T>) -> 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/infer/relate/lub.rs b/compiler/rustc_infer/src/infer/relate/lub.rs index bf4d68b9428..35c7ab5000d 100644 --- a/compiler/rustc_infer/src/infer/relate/lub.rs +++ b/compiler/rustc_infer/src/infer/relate/lub.rs @@ -6,9 +6,9 @@ use rustc_span::Span; use tracing::{debug, instrument}; +use super::StructurallyRelateAliases; use super::combine::{CombineFields, PredicateEmittingRelation}; use super::lattice::{self, LatticeDir}; -use super::StructurallyRelateAliases; use crate::infer::{DefineOpaqueTypes, InferCtxt, SubregionOrigin}; use crate::traits::ObligationCause; diff --git a/compiler/rustc_infer/src/infer/relate/type_relating.rs b/compiler/rustc_infer/src/infer/relate/type_relating.rs index be16fca4521..a402a8009ff 100644 --- a/compiler/rustc_infer/src/infer/relate/type_relating.rs +++ b/compiler/rustc_infer/src/infer/relate/type_relating.rs @@ -1,14 +1,14 @@ use rustc_middle::traits::solve::Goal; use rustc_middle::ty::relate::{ - relate_args_invariantly, relate_args_with_variances, Relate, RelateResult, TypeRelation, + Relate, RelateResult, TypeRelation, relate_args_invariantly, relate_args_with_variances, }; use rustc_middle::ty::{self, Ty, TyCtxt, TyVar}; use rustc_span::Span; use tracing::{debug, instrument}; use super::combine::CombineFields; -use crate::infer::relate::{PredicateEmittingRelation, StructurallyRelateAliases}; use crate::infer::BoundRegionConversionTime::HigherRankedType; +use crate::infer::relate::{PredicateEmittingRelation, StructurallyRelateAliases}; use crate::infer::{DefineOpaqueTypes, InferCtxt, SubregionOrigin}; /// Enforce that `a` is equal to or a subtype of `b`. diff --git a/compiler/rustc_infer/src/infer/snapshot/mod.rs b/compiler/rustc_infer/src/infer/snapshot/mod.rs index 20db6583a2b..964fb1f6819 100644 --- a/compiler/rustc_infer/src/infer/snapshot/mod.rs +++ b/compiler/rustc_infer/src/infer/snapshot/mod.rs @@ -2,8 +2,8 @@ use rustc_middle::ty; use tracing::{debug, instrument}; -use super::region_constraints::RegionSnapshot; use super::InferCtxt; +use super::region_constraints::RegionSnapshot; mod fudge; pub(crate) mod undo_log; diff --git a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs index 9aa02f89d2a..79ea0915c9c 100644 --- a/compiler/rustc_infer/src/infer/snapshot/undo_log.rs +++ b/compiler/rustc_infer/src/infer/snapshot/undo_log.rs @@ -6,7 +6,7 @@ use rustc_middle::ty::{self, OpaqueHiddenType, OpaqueTypeKey}; use tracing::debug; -use crate::infer::{region_constraints, type_variable, InferCtxtInner}; +use crate::infer::{InferCtxtInner, region_constraints, type_variable}; use crate::traits; pub struct Snapshot<'tcx> { diff --git a/compiler/rustc_infer/src/traits/engine.rs b/compiler/rustc_infer/src/traits/engine.rs index fd38040406d..a076cdad672 100644 --- a/compiler/rustc_infer/src/traits/engine.rs +++ b/compiler/rustc_infer/src/traits/engine.rs @@ -45,15 +45,12 @@ fn register_bound( 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/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index 3a05b576a97..34b0fe3e967 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -18,14 +18,14 @@ use rustc_middle::ty::{self, Ty, TyCtxt, Upcast}; use rustc_span::Span; +pub use self::ImplSource::*; +pub use self::SelectionError::*; pub use self::engine::{FromSolverError, ScrubbedTraitError, TraitEngine}; pub(crate) use self::project::UndoLog; pub use self::project::{ MismatchedProjectionTypes, Normalized, NormalizedTerm, ProjectionCache, ProjectionCacheEntry, ProjectionCacheKey, ProjectionCacheStorage, }; -pub use self::ImplSource::*; -pub use self::SelectionError::*; use crate::infer::InferCtxt; /// An `Obligation` represents some trait reference (e.g., `i32: Eq`) for diff --git a/compiler/rustc_infer/src/traits/project.rs b/compiler/rustc_infer/src/traits/project.rs index f6b05340952..fa813d0f90c 100644 --- a/compiler/rustc_infer/src/traits/project.rs +++ b/compiler/rustc_infer/src/traits/project.rs @@ -200,10 +200,10 @@ pub fn complete(&mut self, key: ProjectionCacheKey<'tcx>, result: EvaluationResu if result.must_apply_considering_regions() { ty.obligations = vec![]; } - 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_infer/src/traits/util.rs b/compiler/rustc_infer/src/traits/util.rs index 3e4f9b48166..a977bd15d3b 100644 --- a/compiler/rustc_infer/src/traits/util.rs +++ b/compiler/rustc_infer/src/traits/util.rs @@ -1,7 +1,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_middle::ty::{self, ToPolyTraitRef, TyCtxt}; -use rustc_span::symbol::Ident; use rustc_span::Span; +use rustc_span::symbol::Ident; pub use rustc_type_ir::elaborate::*; use crate::traits::{self, Obligation, ObligationCauseCode, PredicateObligation}; diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index 347dc185043..c2241773c8c 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -2,7 +2,7 @@ use std::result; use std::sync::Arc; -use rustc_ast::{token, LitKind, MetaItemKind}; +use rustc_ast::{LitKind, MetaItemKind, token}; use rustc_codegen_ssa::traits::CodegenBackend; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::stable_hasher::StableHasher; @@ -21,10 +21,10 @@ use rustc_session::config::{self, Cfg, CheckCfg, ExpectedValues, Input, OutFileName}; use rustc_session::filesearch::{self, sysroot_candidates}; use rustc_session::parse::ParseSess; -use rustc_session::{lint, CompilerIO, EarlyDiagCtxt, Session}; +use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, lint}; +use rustc_span::FileName; use rustc_span::source_map::{FileLoader, RealFileLoader, SourceMapInputs}; use rustc_span::symbol::sym; -use rustc_span::FileName; use tracing::trace; use crate::util; diff --git a/compiler/rustc_interface/src/lib.rs b/compiler/rustc_interface/src/lib.rs index 3b6c2acaf30..94ebe51f213 100644 --- a/compiler/rustc_interface/src/lib.rs +++ b/compiler/rustc_interface/src/lib.rs @@ -14,7 +14,7 @@ pub mod util; pub use callbacks::setup_callbacks; -pub use interface::{run_compiler, Config}; +pub use interface::{Config, run_compiler}; pub use passes::DEFAULT_QUERY_PROVIDERS; pub use queries::{Linker, Queries}; diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index b93bc3ed84f..617581cf667 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -13,10 +13,10 @@ use rustc_expand::base::{ExtCtxt, LintStoreExpand}; use rustc_feature::Features; use rustc_fs_util::try_canonicalize; -use rustc_hir::def_id::{StableCrateId, StableCrateIdMap, LOCAL_CRATE}; +use rustc_hir::def_id::{LOCAL_CRATE, StableCrateId, StableCrateIdMap}; use rustc_hir::definitions::Definitions; use rustc_incremental::setup_dep_graph; -use rustc_lint::{unerased_lint_store, BufferedEarlyLint, EarlyCheckNode, LintStore}; +use rustc_lint::{BufferedEarlyLint, EarlyCheckNode, LintStore, unerased_lint_store}; use rustc_metadata::creader::CStore; use rustc_middle::arena::Arena; use rustc_middle::ty::{self, GlobalCtxt, RegisteredTools, TyCtxt}; @@ -32,8 +32,8 @@ use rustc_session::output::{collect_crate_types, filename_for_input, find_crate_name}; use rustc_session::search_paths::PathKind; use rustc_session::{Limit, Session}; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::FileName; +use rustc_span::symbol::{Symbol, sym}; use rustc_target::spec::PanicStrategy; use rustc_trait_selection::traits; use tracing::{info, instrument}; @@ -980,19 +980,15 @@ fn analysis(tcx: TyCtxt<'_>, (): ()) -> Result<()> { std::ops::ControlFlow::Continue::(()) }); - sess.code_stats.record_vtable_size( - tr, - &name, - VTableSizeInfo { - trait_name: name.clone(), - entries: entries_ignoring_upcasting + entries_for_upcasting, - entries_ignoring_upcasting, - entries_for_upcasting, - upcasting_cost_percent: entries_for_upcasting as f64 - / entries_ignoring_upcasting as f64 - * 100., - }, - ) + sess.code_stats.record_vtable_size(tr, &name, VTableSizeInfo { + trait_name: name.clone(), + entries: entries_ignoring_upcasting + entries_for_upcasting, + entries_ignoring_upcasting, + entries_for_upcasting, + upcasting_cost_percent: entries_for_upcasting as f64 + / entries_ignoring_upcasting as f64 + * 100., + }) } } diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 44e07b36b61..3a1833452d4 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -3,8 +3,8 @@ use std::sync::Arc; use rustc_ast as ast; -use rustc_codegen_ssa::traits::CodegenBackend; use rustc_codegen_ssa::CodegenResults; +use rustc_codegen_ssa::traits::CodegenBackend; use rustc_data_structures::steal::Steal; use rustc_data_structures::svh::Svh; use rustc_data_structures::sync::{OnceLock, WorkerLocal}; @@ -13,8 +13,8 @@ use rustc_middle::dep_graph::DepGraph; use rustc_middle::ty::{GlobalCtxt, TyCtxt}; use rustc_serialize::opaque::FileEncodeResult; -use rustc_session::config::{self, OutputFilenames, OutputType}; use rustc_session::Session; +use rustc_session::config::{self, OutputFilenames, OutputType}; use crate::errors::FailedWritingFile; use crate::interface::{Compiler, Result}; diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index 080f2a1785a..57aa3deae80 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -6,22 +6,22 @@ use rustc_data_structures::profiling::TimePassesFormat; use rustc_errors::emitter::HumanReadableErrorType; -use rustc_errors::{registry, ColorConfig}; +use rustc_errors::{ColorConfig, registry}; use rustc_session::config::{ - build_configuration, build_session_options, rustc_optgroups, BranchProtection, CFGuard, Cfg, - CollapseMacroDebuginfo, CoverageLevel, CoverageOptions, DebugInfo, DumpMonoStatsFormat, - ErrorOutputType, ExternEntry, ExternLocation, Externs, FmtDebug, FunctionReturn, - InliningThreshold, Input, InstrumentCoverage, InstrumentXRay, LinkSelfContained, - LinkerPluginLto, LocationDetail, LtoCli, MirIncludeSpans, NextSolverConfig, OomStrategy, - Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, + BranchProtection, CFGuard, Cfg, CollapseMacroDebuginfo, CoverageLevel, CoverageOptions, + DebugInfo, DumpMonoStatsFormat, ErrorOutputType, ExternEntry, ExternLocation, Externs, + FmtDebug, FunctionReturn, InliningThreshold, Input, InstrumentCoverage, InstrumentXRay, + LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, MirIncludeSpans, NextSolverConfig, + OomStrategy, Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, PatchableFunctionEntry, Polonius, ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, - SymbolManglingVersion, WasiExecModel, + SymbolManglingVersion, WasiExecModel, build_configuration, build_session_options, + rustc_optgroups, }; use rustc_session::lint::Level; use rustc_session::search_paths::SearchPath; use rustc_session::utils::{CanonicalizedPath, NativeLib, NativeLibKind}; -use rustc_session::{build_session, filesearch, getopts, CompilerIO, EarlyDiagCtxt, Session}; -use rustc_span::edition::{Edition, DEFAULT_EDITION}; +use rustc_session::{CompilerIO, EarlyDiagCtxt, Session, build_session, filesearch, getopts}; +use rustc_span::edition::{DEFAULT_EDITION, Edition}; use rustc_span::source_map::{RealFileLoader, SourceMapInputs}; use rustc_span::symbol::sym; use rustc_span::{FileName, SourceFileHashAlgorithm}; diff --git a/compiler/rustc_interface/src/util.rs b/compiler/rustc_interface/src/util.rs index 761d288a7c2..71e8accf5a3 100644 --- a/compiler/rustc_interface/src/util.rs +++ b/compiler/rustc_interface/src/util.rs @@ -1,21 +1,21 @@ use std::env::consts::{DLL_PREFIX, DLL_SUFFIX}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::OnceLock; +use std::sync::atomic::{AtomicBool, Ordering}; use std::{env, iter, thread}; use rustc_ast as ast; use rustc_codegen_ssa::traits::CodegenBackend; #[cfg(parallel_compiler)] use rustc_data_structures::sync; -use rustc_metadata::{load_symbol_from_dylib, DylibError}; +use rustc_metadata::{DylibError, load_symbol_from_dylib}; use rustc_middle::ty::CurrentGcx; use rustc_parse::validate_attr; -use rustc_session::config::{host_triple, Cfg, OutFileName, OutputFilenames, OutputTypes}; +use rustc_session::config::{Cfg, OutFileName, OutputFilenames, OutputTypes, host_triple}; use rustc_session::filesearch::sysroot_candidates; use rustc_session::lint::{self, BuiltinLintDiag, LintBuffer}; -use rustc_session::output::{categorize_crate_type, CRATE_TYPES}; -use rustc_session::{filesearch, EarlyDiagCtxt, Session}; +use rustc_session::output::{CRATE_TYPES, categorize_crate_type}; +use rustc_session::{EarlyDiagCtxt, Session, filesearch}; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::edition::Edition; use rustc_span::source_map::SourceMapInputs; @@ -143,7 +143,7 @@ pub(crate) fn run_in_thread_pool_with_globals R + Send, use rustc_data_structures::{defer, jobserver}; use rustc_middle::ty::tls; use rustc_query_impl::QueryCtxt; - use rustc_query_system::query::{break_query_cycles, QueryContext}; + use rustc_query_system::query::{QueryContext, break_query_cycles}; let thread_stack_size = init_stack_size(thread_builder_diag); diff --git a/compiler/rustc_lexer/src/tests.rs b/compiler/rustc_lexer/src/tests.rs index 493ec2b0f60..556bbf1f518 100644 --- a/compiler/rustc_lexer/src/tests.rs +++ b/compiler/rustc_lexer/src/tests.rs @@ -1,4 +1,4 @@ -use expect_test::{expect, Expect}; +use expect_test::{Expect, expect}; use super::*; @@ -141,9 +141,7 @@ 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 } @@ -163,8 +161,7 @@ fn smoke_test() { Token { kind: Whitespace, len: 1 } Token { kind: CloseBrace, len: 1 } Token { kind: Whitespace, len: 1 } - "#]], - ) + "#]]) } #[test] @@ -207,47 +204,35 @@ 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 5b99495f475..6fa7a150516 100644 --- a/compiler/rustc_lexer/src/unescape/tests.rs +++ b/compiler/rustc_lexer/src/unescape/tests.rs @@ -108,15 +108,12 @@ fn check(literal: &str, expected: &[(Range, Result)]) 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/messages.ftl b/compiler/rustc_lint/messages.ftl index e71c5676ce4..83e97537c15 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -899,6 +899,8 @@ lint_unnameable_test_items = cannot test inner items lint_unnecessary_qualification = unnecessary qualification .suggestion = remove the unnecessary path segments +lint_unqualified_local_imports = `use` of a local item without leading `self::`, `super::`, or `crate::` + lint_unsafe_attr_outside_unsafe = unsafe attribute used without unsafe .label = usage of unsafe attribute lint_unsafe_attr_outside_unsafe_suggestion = wrap the attribute in `unsafe(...)` diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 8b92180e9bd..8bd9c899a62 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -28,10 +28,10 @@ use rustc_ast::{self as ast, *}; use rustc_ast_pretty::pprust::{self, expr_to_string}; use rustc_errors::{Applicability, LintDiagnostic}; -use rustc_feature::{deprecated_attributes, AttributeGate, BuiltinAttribute, GateIssue, Stability}; +use rustc_feature::{AttributeGate, BuiltinAttribute, GateIssue, Stability, deprecated_attributes}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_hir::intravisit::FnKind as HirFnKind; use rustc_hir::{Body, FnDecl, GenericParamKind, PatKind, PredicateOrigin}; use rustc_middle::bug; @@ -39,13 +39,13 @@ use rustc_middle::ty::layout::LayoutOf; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Upcast, VariantDef}; +use rustc_session::lint::FutureIncompatibilityReason; // hardwired lints from rustc_lint_defs pub use rustc_session::lint::builtin::*; -use rustc_session::lint::FutureIncompatibilityReason; use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass}; use rustc_span::edition::Edition; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use rustc_span::{BytePos, InnerSpan, Span}; use rustc_target::abi::Abi; use rustc_target::asm::InlineAsmArch; @@ -68,10 +68,10 @@ BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel, }; -use crate::nonstandard_style::{method_context, MethodLateContext}; +use crate::nonstandard_style::{MethodLateContext, method_context}; use crate::{ - fluent_generated as fluent, EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, - LintContext, + EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, LintContext, + fluent_generated as fluent, }; declare_lint! { @@ -120,11 +120,10 @@ fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { "{}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, + }); } } } @@ -436,11 +435,10 @@ fn check_missing_docs_attrs( 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, + }); } } } @@ -721,11 +719,10 @@ fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { .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, + }); } } } @@ -847,24 +844,21 @@ fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { 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; } } if attr.has_name(sym::no_start) || attr.has_name(sym::crate_id) { - cx.emit_span_lint( - DEPRECATED, - attr.span, - BuiltinDeprecatedAttrUsed { - name: pprust::path_to_string(&attr.get_normal_item().path), - suggestion: attr.span, - }, - ); + cx.emit_span_lint(DEPRECATED, attr.span, BuiltinDeprecatedAttrUsed { + name: pprust::path_to_string(&attr.get_normal_item().path), + suggestion: attr.span, + }); } } } @@ -899,11 +893,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, + }); } } } @@ -1033,11 +1027,9 @@ fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 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; } } @@ -1064,11 +1056,9 @@ fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { // 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, .. }) => { @@ -1316,15 +1306,11 @@ fn perform_lint( applicability = Applicability::MaybeIncorrect; } let def_span = cx.tcx.def_span(def_id); - cx.emit_span_lint( - UNREACHABLE_PUB, - def_span, - BuiltinUnreachablePub { - what, - suggestion: (vis_span, applicability), - help: exportable, - }, - ); + cx.emit_span_lint(UNREACHABLE_PUB, def_span, BuiltinUnreachablePub { + what, + suggestion: (vis_span, applicability), + help: exportable, + }); } } } @@ -1468,32 +1454,24 @@ fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 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, + }); } } } @@ -1579,11 +1557,10 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { | ClauseKind::ConstEvaluatable(..) => 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, + }); } } } @@ -1899,11 +1876,12 @@ fn check_ident_token( 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, + }); } } @@ -2322,11 +2300,11 @@ fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) { 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 }); } @@ -2647,17 +2625,13 @@ fn ty_find_init_error<'tcx>( 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, + }); } } } @@ -2735,11 +2709,9 @@ fn is_zero(expr: &hir::Expr<'_>) -> bool { if let rustc_hir::ExprKind::Unary(rustc_hir::UnOp::Deref, expr_deref) = expr.kind { if is_null_ptr(cx, expr_deref) { - cx.emit_span_lint( - DEREF_NULLPTR, - expr.span, - BuiltinDerefNullptr { label: expr.span }, - ); + cx.emit_span_lint(DEREF_NULLPTR, expr.span, BuiltinDerefNullptr { + label: expr.span, + }); } } } @@ -2956,18 +2928,14 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { 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 @@ -2977,11 +2945,10 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None ) => { - cx.emit_span_lint( - BINARY_ASM_LABELS, + cx.emit_span_lint(BINARY_ASM_LABELS, span, InvalidAsmLabel::Binary { + missing_precise_span, 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 c9e2eee16b3..39f90a8e9ed 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -29,15 +29,15 @@ use rustc_middle::bug; use rustc_middle::middle::privacy::EffectiveVisibilities; use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout}; -use rustc_middle::ty::print::{with_no_trimmed_paths, PrintError, PrintTraitRefExt as _, Printer}; +use rustc_middle::ty::print::{PrintError, PrintTraitRefExt as _, Printer, with_no_trimmed_paths}; use rustc_middle::ty::{self, GenericArg, RegisteredTools, Ty, TyCtxt}; use rustc_session::lint::{ BuiltinLintDiag, FutureIncompatibleInfo, Level, Lint, LintBuffer, LintExpectationId, LintId, }; use rustc_session::{LintStoreMarker, Session}; -use rustc_span::edit_distance::find_best_match_for_names; -use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; +use rustc_span::edit_distance::find_best_match_for_names; +use rustc_span::symbol::{Ident, Symbol, sym}; use rustc_target::abi; use tracing::debug; @@ -251,14 +251,11 @@ pub fn register_lints(&mut self, lints: &[&'static Lint]) { } 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( @@ -273,14 +270,11 @@ pub fn register_group( .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/context/diagnostics.rs b/compiler/rustc_lint/src/context/diagnostics.rs index fd13c418c09..168e3a8e92c 100644 --- a/compiler/rustc_lint/src/context/diagnostics.rs +++ b/compiler/rustc_lint/src/context/diagnostics.rs @@ -5,13 +5,13 @@ use rustc_ast::util::unicode::TEXT_FLOW_CONTROL_CHARS; use rustc_errors::{ - elided_lifetime_in_path_suggestion, Applicability, Diag, DiagArgValue, LintDiagnostic, + Applicability, Diag, DiagArgValue, LintDiagnostic, elided_lifetime_in_path_suggestion, }; use rustc_middle::middle::stability; -use rustc_session::lint::{BuiltinLintDiag, ElidedLifetimeResolution}; use rustc_session::Session; -use rustc_span::symbol::kw; +use rustc_session::lint::{BuiltinLintDiag, ElidedLifetimeResolution}; use rustc_span::BytePos; +use rustc_span::symbol::kw; use tracing::debug; use crate::lints::{self, ElidedNamedLifetime}; diff --git a/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs b/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs index 38c4e48928f..16994846545 100644 --- a/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs +++ b/compiler/rustc_lint/src/context/diagnostics/check_cfg.rs @@ -1,9 +1,9 @@ use rustc_middle::bug; -use rustc_session::config::ExpectedValues; use rustc_session::Session; +use rustc_session::config::ExpectedValues; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::symbol::Ident; -use rustc_span::{sym, Span, Symbol}; +use rustc_span::{Span, Symbol, sym}; use crate::lints; diff --git a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs index f174470b7a7..657642e093c 100644 --- a/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs +++ b/compiler/rustc_lint/src/deref_into_dyn_supertrait.rs @@ -86,19 +86,14 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { .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 a9de258e005..364c6fd488a 100644 --- a/compiler/rustc_lint/src/drop_forget_useless.rs +++ b/compiler/rustc_lint/src/drop_forget_useless.rs @@ -163,44 +163,32 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) { }; 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/early.rs b/compiler/rustc_lint/src/early.rs index 0ee9dda1fef..2285877c9ef 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -15,15 +15,15 @@ //! for all lint attributes. use rustc_ast::ptr::P; -use rustc_ast::visit::{self as ast_visit, walk_list, Visitor}; +use rustc_ast::visit::{self as ast_visit, Visitor, walk_list}; use rustc_ast::{self as ast, HasAttrs}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_feature::Features; use rustc_middle::ty::RegisteredTools; -use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass}; use rustc_session::Session; -use rustc_span::symbol::Ident; +use rustc_session::lint::{BufferedEarlyLint, LintBuffer, LintPass}; use rustc_span::Span; +use rustc_span::symbol::Ident; use tracing::debug; use crate::context::{EarlyContext, LintStore}; diff --git a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs index 4e3eca496ea..8e22a9bdc45 100644 --- a/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs +++ b/compiler/rustc_lint/src/enum_intrinsics_non_enums.rs @@ -1,9 +1,9 @@ use rustc_hir as hir; -use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::Ty; +use rustc_middle::ty::visit::TypeVisitableExt; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use crate::context::LintContext; use crate::lints::{EnumIntrinsicsMemDiscriminate, EnumIntrinsicsMemVariant}; @@ -55,11 +55,10 @@ 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/expect.rs b/compiler/rustc_lint/src/expect.rs index 2450afbca06..289e2c9b722 100644 --- a/compiler/rustc_lint/src/expect.rs +++ b/compiler/rustc_lint/src/expect.rs @@ -3,8 +3,8 @@ use rustc_middle::lint::LintExpectation; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; -use rustc_session::lint::builtin::UNFULFILLED_LINT_EXPECTATIONS; use rustc_session::lint::LintExpectationId; +use rustc_session::lint::builtin::UNFULFILLED_LINT_EXPECTATIONS; use rustc_span::Symbol; use crate::lints::{Expectation, ExpectationNote}; diff --git a/compiler/rustc_lint/src/for_loops_over_fallibles.rs b/compiler/rustc_lint/src/for_loops_over_fallibles.rs index 1b25f21ef84..fcb7a6108c0 100644 --- a/compiler/rustc_lint/src/for_loops_over_fallibles.rs +++ b/compiler/rustc_lint/src/for_loops_over_fallibles.rs @@ -4,7 +4,7 @@ use rustc_infer::traits::ObligationCause; use rustc_middle::ty; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::{sym, Span}; +use rustc_span::{Span, sym}; use rustc_trait_selection::traits::ObligationCtxt; use crate::lints::{ @@ -96,11 +96,14 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { 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/foreign_modules.rs b/compiler/rustc_lint/src/foreign_modules.rs index 33b8b7c544b..1ead377607f 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -5,12 +5,12 @@ use rustc_middle::query::Providers; use rustc_middle::ty::{self, AdtDef, Instance, Ty, TyCtxt}; use rustc_session::declare_lint; -use rustc_span::{sym, Span, Symbol}; +use rustc_span::{Span, Symbol, sym}; use rustc_target::abi::FIRST_VARIANT; use tracing::{debug, instrument}; use crate::lints::{BuiltinClashingExtern, BuiltinClashingExternSub}; -use crate::{types, LintVec}; +use crate::{LintVec, types}; pub(crate) fn provide(providers: &mut Providers) { *providers = Providers { clashing_extern_declarations, ..*providers }; diff --git a/compiler/rustc_lint/src/hidden_unicode_codepoints.rs b/compiler/rustc_lint/src/hidden_unicode_codepoints.rs index ebd8bd5605d..025fd452040 100644 --- a/compiler/rustc_lint/src/hidden_unicode_codepoints.rs +++ b/compiler/rustc_lint/src/hidden_unicode_codepoints.rs @@ -1,4 +1,4 @@ -use ast::util::unicode::{contains_text_flow_control_chars, TEXT_FLOW_CONTROL_CHARS}; +use ast::util::unicode::{TEXT_FLOW_CONTROL_CHARS, contains_text_flow_control_chars}; use rustc_ast as ast; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::{BytePos, Span, Symbol}; @@ -73,11 +73,13 @@ fn lint_text_direction_codepoint( 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, + }); } } impl EarlyLintPass for HiddenUnicodeCodepoints { diff --git a/compiler/rustc_lint/src/if_let_rescope.rs b/compiler/rustc_lint/src/if_let_rescope.rs index 7138d40a48f..229d0c36421 100644 --- a/compiler/rustc_lint/src/if_let_rescope.rs +++ b/compiler/rustc_lint/src/if_let_rescope.rs @@ -11,8 +11,8 @@ use rustc_middle::ty::TyCtxt; use rustc_session::lint::{FutureIncompatibilityReason, Level}; use rustc_session::{declare_lint, impl_lint_pass}; -use rustc_span::edition::Edition; use rustc_span::Span; +use rustc_span::edition::Edition; use crate::{LateContext, LateLintPass}; @@ -210,25 +210,20 @@ fn probe_if_cascade<'tcx>(&mut self, cx: &LateContext<'tcx>, mut expr: &'tcx hir } } 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 c43c650a9f9..a073d16f634 100644 --- a/compiler/rustc_lint/src/impl_trait_overcaptures.rs +++ b/compiler/rustc_lint/src/impl_trait_overcaptures.rs @@ -7,12 +7,12 @@ use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_macros::LintDiagnostic; use rustc_middle::middle::resolve_bound_vars::ResolvedArg; use rustc_middle::ty::relate::{ - structurally_relate_consts, structurally_relate_tys, Relate, RelateResult, TypeRelation, + Relate, RelateResult, TypeRelation, structurally_relate_consts, structurally_relate_tys, }; use rustc_middle::ty::{ self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, @@ -22,10 +22,10 @@ use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::edition::Edition; use rustc_span::{Span, Symbol}; -use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt; use rustc_trait_selection::traits::ObligationCtxt; +use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt; -use crate::{fluent_generated as fluent, LateContext, LateLintPass}; +use crate::{LateContext, LateLintPass, fluent_generated as fluent}; declare_lint! { /// The `impl_trait_overcaptures` lint warns against cases where lifetime @@ -309,10 +309,12 @@ fn visit_ty(&mut self, t: Ty<'tcx>) { // 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 9d637c1eb7f..94cc58e4956 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -10,9 +10,9 @@ }; use rustc_middle::ty::{self, GenericArgsRef, Ty as MiddleTy}; use rustc_session::{declare_lint_pass, declare_tool_lint}; -use rustc_span::hygiene::{ExpnKind, MacroKind}; -use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; +use rustc_span::hygiene::{ExpnKind, MacroKind}; +use rustc_span::symbol::{Symbol, kw, sym}; use tracing::debug; use crate::lints::{ @@ -48,11 +48,10 @@ fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) { 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,18 +106,14 @@ fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { if let Ok(Some(instance)) = ty::Instance::try_resolve(cx.tcx, cx.param_env, def_id, args) { 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), + }); } } } @@ -208,11 +203,9 @@ fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) { 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), } @@ -220,11 +213,10 @@ fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) { && 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, + }); } } _ => {} @@ -418,11 +410,9 @@ fn check_item(&mut self, cx: &LateContext<'_>, item: &rustc_hir::Item<'_>) { if is_doc_keyword(keyword) { return; } - cx.emit_span_lint( - EXISTING_DOC_KEYWORD, - attr.span, - NonExistentDocKeyword { keyword }, - ); + cx.emit_span_lint(EXISTING_DOC_KEYWORD, attr.span, NonExistentDocKeyword { + keyword, + }); } } } @@ -625,11 +615,9 @@ fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) { && 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/late.rs b/compiler/rustc_lint/src/late.rs index cb369d99a84..de401397150 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -18,14 +18,14 @@ use std::cell::Cell; use rustc_data_structures::stack::ensure_sufficient_stack; -use rustc_data_structures::sync::{join, Lrc}; +use rustc_data_structures::sync::{Lrc, join}; use rustc_hir as hir; use rustc_hir::def_id::{LocalDefId, LocalModDefId}; -use rustc_hir::{intravisit as hir_visit, HirId}; +use rustc_hir::{HirId, intravisit as hir_visit}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{self, TyCtxt}; -use rustc_session::lint::LintPass; use rustc_session::Session; +use rustc_session::lint::LintPass; use rustc_span::Span; use tracing::debug; diff --git a/compiler/rustc_lint/src/let_underscore.rs b/compiler/rustc_lint/src/let_underscore.rs index 1368cc87e3e..a12a97ee573 100644 --- a/compiler/rustc_lint/src/let_underscore.rs +++ b/compiler/rustc_lint/src/let_underscore.rs @@ -2,7 +2,7 @@ use rustc_hir as hir; use rustc_middle::ty; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::{sym, Symbol}; +use rustc_span::{Symbol, sym}; use crate::lints::{NonBindingLet, NonBindingLetSub}; use crate::{LateContext, LateLintPass, LintContext}; @@ -156,11 +156,10 @@ fn check_local(&mut self, cx: &LateContext<'_>, local: &hir::LetStmt<'_>) { }; 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/levels.rs b/compiler/rustc_lint/src/levels.rs index 796d66f13d4..007e86ae0d2 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -2,25 +2,25 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_errors::{Diag, LintDiagnostic, MultiSpan}; use rustc_feature::{Features, GateIssue}; -use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::HirId; +use rustc_hir::intravisit::{self, Visitor}; use rustc_index::IndexVec; use rustc_middle::bug; use rustc_middle::hir::nested_filter; use rustc_middle::lint::{ - lint_level, reveal_actual_level, LevelAndSource, LintExpectation, LintLevelSource, - ShallowLintLevelMap, + LevelAndSource, LintExpectation, LintLevelSource, ShallowLintLevelMap, lint_level, + reveal_actual_level, }; use rustc_middle::query::Providers; use rustc_middle::ty::{RegisteredTools, TyCtxt}; +use rustc_session::Session; use rustc_session::lint::builtin::{ self, FORBIDDEN_LINT_GROUPS, RENAMED_AND_REMOVED_LINTS, SINGLE_USE_LIFETIMES, UNFULFILLED_LINT_EXPECTATIONS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES, }; use rustc_session::lint::{Level, Lint, LintExpectationId, LintId}; -use rustc_session::Session; -use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Symbol, sym}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; use {rustc_ast as ast, rustc_hir as hir}; diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index d1da2809cc7..c74cb866f21 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -86,6 +86,7 @@ mod traits; mod types; mod unit_bindings; +mod unqualified_local_imports; mod unused; use async_closures::AsyncClosureUsage; @@ -126,6 +127,7 @@ use traits::*; use types::*; use unit_bindings::*; +use unqualified_local_imports::*; use unused::*; #[rustfmt::skip] @@ -133,7 +135,7 @@ pub use context::{ CheckLintNameResult, EarlyContext, FindLintError, LateContext, LintContext, LintStore, }; -pub use early::{check_ast_node, EarlyCheckNode}; +pub use early::{EarlyCheckNode, check_ast_node}; pub use late::{check_crate, late_lint_mod, unerased_lint_store}; pub use passes::{EarlyLintPass, LateLintPass}; pub use rustc_session::lint::Level::{self, *}; @@ -249,6 +251,7 @@ fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) { TailExprDropOrder: TailExprDropOrder, IfLetRescope: IfLetRescope::default(), StaticMutRefs: StaticMutRefs, + UnqualifiedLocalImports: UnqualifiedLocalImports, ] ] ); @@ -618,24 +621,19 @@ 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(EXISTING_DOC_KEYWORD), - 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(EXISTING_DOC_KEYWORD), + LintId::of(BAD_OPT_ACCESS), + LintId::of(SPAN_USE_EQ_CTXT), + ]); } #[cfg(test)] diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 11006862d05..6979d56844a 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -13,15 +13,15 @@ use rustc_macros::{LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::inhabitedness::InhabitedPredicate; use rustc_middle::ty::{Clause, PolyExistentialTraitRef, Ty, TyCtxt}; -use rustc_session::lint::AmbiguityErrorDiag; use rustc_session::Session; +use rustc_session::lint::AmbiguityErrorDiag; use rustc_span::edition::Edition; use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent}; -use rustc_span::{sym, Span, Symbol}; +use rustc_span::{Span, Symbol, sym}; use crate::builtin::{InitError, ShorthandAssocTyCollector, TypeAliasBounds}; use crate::errors::{OverruledAttributeSub, RequestedLevel}; -use crate::{fluent_generated as fluent, LateContext}; +use crate::{LateContext, fluent_generated as fluent}; // array_into_iter.rs #[derive(LintDiagnostic)] @@ -3093,3 +3093,7 @@ pub(crate) enum MutRefSugg { span: Span, }, } + +#[derive(LintDiagnostic)] +#[diag(lint_unqualified_local_imports)] +pub(crate) struct UnqualifiedLocalImportsDiag {} diff --git a/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs b/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs index e3b1967da09..23f4f728906 100644 --- a/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs +++ b/compiler/rustc_lint/src/macro_expr_fragment_specifier_2024_migration.rs @@ -8,8 +8,8 @@ use rustc_span::sym; use tracing::debug; -use crate::lints::MacroExprFragment2024; use crate::EarlyLintPass; +use crate::lints::MacroExprFragment2024; declare_lint! { /// The `edition_2024_expr_fragment_specifier` lint detects the use of diff --git a/compiler/rustc_lint/src/map_unit_fn.rs b/compiler/rustc_lint/src/map_unit_fn.rs index 3b27e456136..776d51a6727 100644 --- a/compiler/rustc_lint/src/map_unit_fn.rs +++ b/compiler/rustc_lint/src/map_unit_fn.rs @@ -60,39 +60,25 @@ fn check_stmt(&mut self, cx: &LateContext<'tcx>, stmt: &Stmt<'_>) { 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/methods.rs b/compiler/rustc_lint/src/methods.rs index dff72bb622f..df22bf0972d 100644 --- a/compiler/rustc_lint/src/methods.rs +++ b/compiler/rustc_lint/src/methods.rs @@ -1,8 +1,8 @@ use rustc_hir::{Expr, ExprKind}; use rustc_middle::ty; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use crate::lints::CStringPtr; use crate::{LateContext, LateLintPass, LintContext}; @@ -58,11 +58,10 @@ fn lint_cstring_as_ptr( if cx.tcx.is_diagnostic_item(sym::Result, def.did()) { if let ty::Adt(adt, _) = args.type_at(0).kind() { if cx.tcx.is_diagnostic_item(sym::cstring_type, adt.did()) { - cx.emit_span_lint( - TEMPORARY_CSTRING_AS_PTR, - as_ptr_span, - CStringPtr { as_ptr: as_ptr_span, unwrap: unwrap.span }, - ); + cx.emit_span_lint(TEMPORARY_CSTRING_AS_PTR, as_ptr_span, CStringPtr { + as_ptr: as_ptr_span, + unwrap: unwrap.span, + }); } } } diff --git a/compiler/rustc_lint/src/non_ascii_idents.rs b/compiler/rustc_lint/src/non_ascii_idents.rs index 08d054b6a8b..9b495c19990 100644 --- a/compiler/rustc_lint/src/non_ascii_idents.rs +++ b/compiler/rustc_lint/src/non_ascii_idents.rs @@ -209,30 +209,22 @@ fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) { 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", + }); } } } @@ -261,16 +253,12 @@ fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) { .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; @@ -382,11 +370,10 @@ enum ScriptSetUsage { 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 10a517bfbcb..51877e8a034 100644 --- a/compiler/rustc_lint/src/non_fmt_panic.rs +++ b/compiler/rustc_lint/src/non_fmt_panic.rs @@ -9,11 +9,11 @@ use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::edition::Edition; use rustc_span::symbol::kw; -use rustc_span::{hygiene, sym, InnerSpan, Span, Symbol}; +use rustc_span::{InnerSpan, Span, Symbol, hygiene, sym}; use rustc_trait_selection::infer::InferCtxtExt; use crate::lints::{NonFmtPanicBraces, NonFmtPanicUnused}; -use crate::{fluent_generated as fluent, LateContext, LateLintPass, LintContext}; +use crate::{LateContext, LateLintPass, LintContext, fluent_generated as fluent}; declare_lint! { /// The `non_fmt_panics` lint detects `panic!(..)` invocations where the first @@ -255,14 +255,10 @@ 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 1546d79e4fd..ef7ab7efd54 100644 --- a/compiler/rustc_lint/src/non_local_def.rs +++ b/compiler/rustc_lint/src/non_local_def.rs @@ -10,14 +10,14 @@ use rustc_session::{declare_lint, impl_lint_pass}; use rustc_span::def_id::{DefId, LOCAL_CRATE}; use rustc_span::symbol::kw; -use rustc_span::{sym, ExpnKind, MacroKind, Span, Symbol}; +use rustc_span::{ExpnKind, MacroKind, Span, Symbol, sym}; use rustc_trait_selection::error_reporting::traits::ambiguity::{ - compute_applicable_impls_for_diagnostics, CandidateSource, + CandidateSource, compute_applicable_impls_for_diagnostics, }; use rustc_trait_selection::infer::TyCtxtInferExt; use crate::lints::{NonLocalDefinitionsCargoUpdateNote, NonLocalDefinitionsDiag}; -use crate::{fluent_generated as fluent, LateContext, LateLintPass, LintContext}; +use crate::{LateContext, LateLintPass, LintContext, fluent_generated as fluent}; declare_lint! { /// The `non_local_definitions` lint checks for `impl` blocks and `#[macro_export]` @@ -277,26 +277,22 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'tcx>) { 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, - self_ty_str, - of_trait_str, - move_to, - doctest, - may_remove, - has_trait: impl_.of_trait.is_some(), - 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, + self_ty_str, + of_trait_str, + move_to, + doctest, + may_remove, + has_trait: impl_.of_trait.is_some(), + 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 ce4ee45c485..83a8ca4307e 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -5,7 +5,7 @@ use rustc_session::config::CrateType; use rustc_session::{declare_lint, declare_lint_pass}; use rustc_span::def_id::LocalDefId; -use rustc_span::symbol::{sym, Ident}; +use rustc_span::symbol::{Ident, sym}; use rustc_span::{BytePos, Span}; use rustc_target::spec::abi::Abi; use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; @@ -151,11 +151,11 @@ fn check_case(&self, cx: &EarlyContext<'_>, sort: &str, ident: &Ident) { } 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, + }); } } } @@ -489,11 +489,11 @@ fn check_upper_case(cx: &LateContext<'_>, sort: &str, ident: &Ident) { } 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 d08a959f654..4890a93fa76 100644 --- a/compiler/rustc_lint/src/noop_method_call.rs +++ b/compiler/rustc_lint/src/noop_method_call.rs @@ -128,17 +128,13 @@ fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { 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.name, - orig_ty, - trait_, - label: span, - suggest_derive, - }, - ); + cx.emit_span_lint(NOOP_METHOD_CALL, span, NoopMethodCallDiag { + method: call.ident.name, + 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 c9ca1ea5e7a..83652bbf546 100644 --- a/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs +++ b/compiler/rustc_lint/src/opaque_hidden_inferred_bound.rs @@ -5,8 +5,8 @@ use rustc_middle::ty::print::{PrintTraitPredicateExt as _, TraitPredPrintModifiersAndPath}; use rustc_middle::ty::{self, Ty, TypeFoldable}; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::symbol::kw; use rustc_span::Span; +use rustc_span::symbol::kw; use rustc_trait_selection::traits::{self, ObligationCtxt}; use crate::{LateContext, LateLintPass, LintContext}; diff --git a/compiler/rustc_lint/src/pass_by_value.rs b/compiler/rustc_lint/src/pass_by_value.rs index 23b200998a5..ec306f5f834 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -31,11 +31,10 @@ fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx hir::Ty<'tcx>) { } } 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/passes.rs b/compiler/rustc_lint/src/passes.rs index bf16e3b7d15..a1d436e0d3d 100644 --- a/compiler/rustc_lint/src/passes.rs +++ b/compiler/rustc_lint/src/passes.rs @@ -1,5 +1,5 @@ -use rustc_session::lint::builtin::HardwiredLints; use rustc_session::lint::LintPass; +use rustc_session::lint::builtin::HardwiredLints; use crate::context::{EarlyContext, LateContext}; @@ -14,6 +14,8 @@ macro_rules! late_lint_methods { fn check_mod(a: &'tcx rustc_hir::Mod<'tcx>, b: rustc_hir::HirId); fn check_foreign_item(a: &'tcx rustc_hir::ForeignItem<'tcx>); fn check_item(a: &'tcx rustc_hir::Item<'tcx>); + /// This is called *after* recursing into the item + /// (in contrast to `check_item`, which is checked before). fn check_item_post(a: &'tcx rustc_hir::Item<'tcx>); fn check_local(a: &'tcx rustc_hir::LetStmt<'tcx>); fn check_block(a: &'tcx rustc_hir::Block<'tcx>); @@ -135,6 +137,8 @@ macro_rules! early_lint_methods { fn check_crate(a: &rustc_ast::Crate); fn check_crate_post(a: &rustc_ast::Crate); fn check_item(a: &rustc_ast::Item); + /// This is called *after* recursing into the item + /// (in contrast to `check_item`, which is checked before). fn check_item_post(a: &rustc_ast::Item); fn check_local(a: &rustc_ast::Local); fn check_block(a: &rustc_ast::Block); diff --git a/compiler/rustc_lint/src/redundant_semicolon.rs b/compiler/rustc_lint/src/redundant_semicolon.rs index b43e4938b73..036bfd06856 100644 --- a/compiler/rustc_lint/src/redundant_semicolon.rs +++ b/compiler/rustc_lint/src/redundant_semicolon.rs @@ -50,10 +50,9 @@ 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 bb122509d0a..a73904cd776 100644 --- a/compiler/rustc_lint/src/shadowed_into_iter.rs +++ b/compiler/rustc_lint/src/shadowed_into_iter.rs @@ -146,10 +146,11 @@ fn is_ref_to_boxed_slice(ty: Ty<'_>) -> bool { 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 3dd26fb9c53..5d78b41944f 100644 --- a/compiler/rustc_lint/src/static_mut_refs.rs +++ b/compiler/rustc_lint/src/static_mut_refs.rs @@ -3,8 +3,8 @@ use rustc_middle::ty::{Mutability, TyKind}; use rustc_session::lint::FutureIncompatibilityReason; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::edition::Edition; use rustc_span::Span; +use rustc_span::edition::Edition; use crate::lints::{MutRefSugg, RefOfMutStatic}; use crate::{LateContext, LateLintPass, LintContext}; @@ -146,9 +146,11 @@ fn emit_static_mut_refs( } }; - cx.emit_span_lint( - STATIC_MUT_REFS, + cx.emit_span_lint(STATIC_MUT_REFS, span, RefOfMutStatic { span, - RefOfMutStatic { span, sugg, shared_label, shared_note, mut_note }, - ); + sugg, + shared_label, + shared_note, + mut_note, + }); } diff --git a/compiler/rustc_lint/src/tail_expr_drop_order.rs b/compiler/rustc_lint/src/tail_expr_drop_order.rs index 91f3e2e3bb6..44a36142ed4 100644 --- a/compiler/rustc_lint/src/tail_expr_drop_order.rs +++ b/compiler/rustc_lint/src/tail_expr_drop_order.rs @@ -8,8 +8,8 @@ use rustc_middle::ty; use rustc_session::lint::FutureIncompatibilityReason; use rustc_session::{declare_lint, declare_lint_pass}; -use rustc_span::edition::Edition; use rustc_span::Span; +use rustc_span::edition::Edition; use crate::{LateContext, LateLintPass}; diff --git a/compiler/rustc_lint/src/tests.rs b/compiler/rustc_lint/src/tests.rs index 988d1645fba..7fbf381a8d3 100644 --- a/compiler/rustc_lint/src/tests.rs +++ b/compiler/rustc_lint/src/tests.rs @@ -1,4 +1,4 @@ -use rustc_span::{create_default_session_globals_then, Symbol}; +use rustc_span::{Symbol, create_default_session_globals_then}; use crate::levels::parse_lint_and_tool_name; diff --git a/compiler/rustc_lint/src/traits.rs b/compiler/rustc_lint/src/traits.rs index a0fe4b5af74..c0a01b0065e 100644 --- a/compiler/rustc_lint/src/traits.rs +++ b/compiler/rustc_lint/src/traits.rs @@ -101,11 +101,11 @@ fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { 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 3d042f21745..f5a24f9808d 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -12,7 +12,7 @@ use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass}; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::sym; -use rustc_span::{source_map, Span, Symbol}; +use rustc_span::{Span, Symbol, source_map}; use rustc_target::abi::{Abi, TagEncoding, Variants, WrappingRange}; use rustc_target::spec::abi::Abi as SpecAbi; use tracing::debug; @@ -24,7 +24,7 @@ AtomicOrderingStore, ImproperCTypes, InvalidAtomicOrderingDiag, InvalidNanComparisons, InvalidNanComparisonsSuggestion, UnusedComparisons, VariantSizeDifferencesDiag, }; -use crate::{fluent_generated as fluent, LateContext, LateLintPass, LintContext}; +use crate::{LateContext, LateLintPass, LintContext, fluent_generated as fluent}; mod literal; @@ -434,16 +434,13 @@ fn is_valid(binop: hir::BinOp, v: T, min: T, max: T) -> bool { } 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( @@ -1193,11 +1190,14 @@ fn emit_ffi_unsafe_type_lint( } 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 { @@ -1666,11 +1666,11 @@ fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) { } 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 67404be24b5..d1e850990dc 100644 --- a/compiler/rustc_lint/src/types/literal.rs +++ b/compiler/rustc_lint/src/types/literal.rs @@ -1,18 +1,18 @@ -use hir::{is_range_literal, ExprKind, Node}; -use rustc_middle::ty::layout::IntegerExt; +use hir::{ExprKind, Node, is_range_literal}; use rustc_middle::ty::Ty; +use rustc_middle::ty::layout::IntegerExt; use rustc_middle::{bug, ty}; use rustc_target::abi::{Integer, Size}; use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; +use crate::LateContext; use crate::context::LintContext; use crate::lints::{ OnlyCastu8ToChar, OverflowingBinHex, OverflowingBinHexSign, OverflowingBinHexSignBitSub, OverflowingBinHexSub, OverflowingInt, OverflowingIntHelp, OverflowingLiteral, OverflowingUInt, RangeEndpointOutOfRange, UseInclusiveRange, }; -use crate::types::{TypeLimits, OVERFLOWING_LITERALS}; -use crate::LateContext; +use crate::types::{OVERFLOWING_LITERALS, TypeLimits}; /// Attempts to special-case the overflowing literal lint when it occurs as a range endpoint (`expr..MAX+1`). /// Returns `true` iff the lint was emitted. @@ -74,11 +74,10 @@ 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 @@ -187,19 +186,15 @@ fn report_bin_hex_error( }) .flatten(); - cx.emit_span_lint( - OVERFLOWING_LITERALS, - expr.span, - OverflowingBinHex { - ty: t, - lit: repr_str.clone(), - dec: val, - actually, - sign, - sub, - sign_bit_sub, - }, - ) + cx.emit_span_lint(OVERFLOWING_LITERALS, expr.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 @@ -266,11 +261,13 @@ fn lint_int_literal<'tcx>( let help = get_type_suggestion(cx.typeck_results().node_type(e.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, + }); } } @@ -294,11 +291,10 @@ 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; } } @@ -321,20 +317,16 @@ fn lint_uint_literal<'tcx>( ); return; } - cx.emit_span_lint( - OVERFLOWING_LITERALS, - e.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, e.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, + }); } } @@ -367,18 +359,14 @@ pub(crate) fn lint_literal<'tcx>( _ => bug!(), }; if is_infinite == Ok(true) { - cx.emit_span_lint( - OVERFLOWING_LITERALS, - e.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, e.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 ed015908ae5..3c2c5f8fae0 100644 --- a/compiler/rustc_lint/src/unit_bindings.rs +++ b/compiler/rustc_lint/src/unit_bindings.rs @@ -63,11 +63,9 @@ fn check_local(&mut self, cx: &crate::LateContext<'tcx>, local: &'tcx hir::LetSt && !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/unqualified_local_imports.rs b/compiler/rustc_lint/src/unqualified_local_imports.rs new file mode 100644 index 00000000000..bea01a33bd6 --- /dev/null +++ b/compiler/rustc_lint/src/unqualified_local_imports.rs @@ -0,0 +1,85 @@ +use rustc_hir::def::{DefKind, Res}; +use rustc_hir::{self as hir}; +use rustc_session::{declare_lint, declare_lint_pass}; +use rustc_span::symbol::kw; + +use crate::{LateContext, LateLintPass, LintContext, lints}; + +declare_lint! { + /// The `unqualified_local_imports` lint checks for `use` items that import a local item using a + /// path that does not start with `self::`, `super::`, or `crate::`. + /// + /// ### Example + /// + /// ```rust,edition2018 + /// #![warn(unqualified_local_imports)] + /// + /// mod localmod { + /// pub struct S; + /// } + /// + /// use localmod::S; + /// # // We have to actually use `S`, or else the `unused` warnings suppress the lint we care about. + /// # pub fn main() { + /// # let _x = S; + /// # } + /// ``` + /// + /// {{produces}} + /// + /// ### Explanation + /// + /// This lint is meant to be used with the (unstable) rustfmt setting `group_imports = "StdExternalCrate"`. + /// That setting makes rustfmt group `self::`, `super::`, and `crate::` imports separately from those + /// refering to other crates. However, rustfmt cannot know whether `use c::S;` refers to a local module `c` + /// or an external crate `c`, so it always gets categorized as an import from another crate. + /// To ensure consistent grouping of imports from the local crate, all local imports must + /// start with `self::`, `super::`, or `crate::`. This lint can be used to enforce that style. + pub UNQUALIFIED_LOCAL_IMPORTS, + Allow, + "`use` of a local item without leading `self::`, `super::`, or `crate::`", + @feature_gate = unqualified_local_imports; +} + +declare_lint_pass!(UnqualifiedLocalImports => [UNQUALIFIED_LOCAL_IMPORTS]); + +impl<'tcx> LateLintPass<'tcx> for UnqualifiedLocalImports { + fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { + let hir::ItemKind::Use(path, _kind) = item.kind else { return }; + // `path` has three resolutions for the type, module, value namespaces. + // Check if any of them qualifies: local crate, and not a macro. + // (Macros can't be imported any other way so we don't complain about them.) + let is_local_import = |res: &Res| { + matches!( + res, + hir::def::Res::Def(def_kind, def_id) + if def_id.is_local() && !matches!(def_kind, DefKind::Macro(_)), + ) + }; + if !path.res.iter().any(is_local_import) { + return; + } + // So this does refer to something local. Let's check whether it starts with `self`, + // `super`, or `crate`. If the path is empty, that means we have a `use *`, which is + // equivalent to `use crate::*` so we don't fire the lint in that case. + let Some(first_seg) = path.segments.first() else { return }; + if matches!(first_seg.ident.name, kw::SelfLower | kw::Super | kw::Crate) { + return; + } + + let encl_item_id = cx.tcx.hir().get_parent_item(item.hir_id()); + let encl_item = cx.tcx.hir_node_by_def_id(encl_item_id.def_id); + if encl_item.fn_kind().is_some() { + // `use` in a method -- don't lint, that leads to too many undesirable lints + // when a function imports all variants of an enum. + return; + } + + // This `use` qualifies for our lint! + cx.emit_span_lint( + UNQUALIFIED_LOCAL_IMPORTS, + first_seg.ident.span, + lints::UnqualifiedLocalImportsDiag {}, + ); + } +} diff --git a/compiler/rustc_lint/src/unused.rs b/compiler/rustc_lint/src/unused.rs index b7f7b782c77..12d5b5cf979 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -4,14 +4,14 @@ use rustc_ast as ast; use rustc_ast::util::{classify, parser}; use rustc_ast::{ExprKind, StmtKind}; -use rustc_errors::{pluralize, MultiSpan}; +use rustc_errors::{MultiSpan, pluralize}; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem}; use rustc_infer::traits::util::elaborate; -use rustc_middle::ty::{self, adjustment, Ty}; +use rustc_middle::ty::{self, Ty, adjustment}; use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass}; -use rustc_span::symbol::{kw, sym, Symbol}; +use rustc_span::symbol::{Symbol, kw, sym}; use rustc_span::{BytePos, Span}; use tracing::instrument; @@ -185,22 +185,18 @@ fn check_stmt(&mut self, cx: &LateContext<'_>, s: &hir::Stmt<'_>) { 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; } @@ -497,39 +493,35 @@ fn emit_must_use_untranslated( ); } 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() } + }), + }); } } } @@ -791,7 +783,7 @@ fn emit_unused_delims_expr( // ``` // fn f(){(print!(á // ``` - use rustc_ast::visit::{walk_expr, Visitor}; + use rustc_ast::visit::{Visitor, walk_expr}; struct ErrExprVisitor; impl<'ast> Visitor<'ast> for ErrExprVisitor { type Result = ControlFlow<()>; @@ -869,11 +861,11 @@ fn emit_unused_delims( 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,11 +1550,9 @@ fn check_use_tree(&self, cx: &EarlyContext<'_>, use_tree: &ast::UseTree, item: & 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_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index acdedb06141..549dc64a562 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -9,7 +9,7 @@ use rustc_span::edition::Edition; -use crate::{declare_lint, declare_lint_pass, FutureIncompatibilityReason}; +use crate::{FutureIncompatibilityReason, declare_lint, declare_lint_pass}; declare_lint_pass! { /// Does nothing as a lint pass, but registers some `Lint`s diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index f5ed69658ce..734e7069c90 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -14,7 +14,7 @@ use rustc_macros::{Decodable, Encodable, HashStable_Generic}; pub use rustc_span::edition::Edition; use rustc_span::symbol::{Ident, MacroRulesNormalizedIdent}; -use rustc_span::{sym, Span, Symbol}; +use rustc_span::{Span, Symbol, sym}; use rustc_target::spec::abi::Abi; use serde::{Deserialize, Serialize}; diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index 9f3e0080110..165fb7aa6c3 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -485,6 +485,22 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( Options.EmitStackSizeSection = EmitStackSizeSection; if (ArgsCstrBuff != nullptr) { +#if LLVM_VERSION_GE(20, 0) + int buffer_offset = 0; + assert(ArgsCstrBuff[ArgsCstrBuffLen - 1] == '\0'); + auto Arg0 = std::string(ArgsCstrBuff); + buffer_offset = Arg0.size() + 1; + auto ArgsCppStr = + std::string(ArgsCstrBuff + buffer_offset, ArgsCstrBuffLen - 1); + auto i = 0; + while (i != std::string::npos) { + i = ArgsCppStr.find('\0', i + 1); + if (i != std::string::npos) + ArgsCppStr.replace(i, i + 1, " "); + } + Options.MCOptions.Argv0 = Arg0; + Options.MCOptions.CommandlineArgs = ArgsCppStr; +#else int buffer_offset = 0; assert(ArgsCstrBuff[ArgsCstrBuffLen - 1] == '\0'); @@ -510,6 +526,7 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( Options.MCOptions.Argv0 = arg0; Options.MCOptions.CommandLineArgs = llvm::ArrayRef(cmd_arg_strings, num_cmd_arg_strings); +#endif } TargetMachine *TM = TheTarget->createTargetMachine( @@ -518,10 +535,11 @@ extern "C" LLVMTargetMachineRef LLVMRustCreateTargetMachine( } extern "C" void LLVMRustDisposeTargetMachine(LLVMTargetMachineRef TM) { - +#if LLVM_VERSION_LT(20, 0) MCTargetOptions &MCOptions = unwrap(TM)->Options.MCOptions; delete[] MCOptions.Argv0; delete[] MCOptions.CommandLineArgs.data(); +#endif delete unwrap(TM); } diff --git a/compiler/rustc_log/src/lib.rs b/compiler/rustc_log/src/lib.rs index b6d870768a8..a3890fc937e 100644 --- a/compiler/rustc_log/src/lib.rs +++ b/compiler/rustc_log/src/lib.rs @@ -44,8 +44,8 @@ use tracing_core::{Event, Subscriber}; use tracing_subscriber::filter::{Directive, EnvFilter, LevelFilter}; -use tracing_subscriber::fmt::format::{self, FormatEvent, FormatFields}; use tracing_subscriber::fmt::FmtContext; +use tracing_subscriber::fmt::format::{self, FormatEvent, FormatFields}; use tracing_subscriber::layer::SubscriberExt; /// The values of all the environment variables that matter for configuring a logger. diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic.rs b/compiler/rustc_macros/src/diagnostics/diagnostic.rs index 52d892a20f4..185d0704966 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic.rs @@ -8,7 +8,7 @@ use synstructure::Structure; use crate::diagnostics::diagnostic_builder::DiagnosticDeriveKind; -use crate::diagnostics::error::{span_err, DiagnosticDeriveError}; +use crate::diagnostics::error::{DiagnosticDeriveError, span_err}; use crate::diagnostics::utils::SetOnce; /// The central struct for constructing the `into_diag` method from an annotated struct. diff --git a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs index 5c2a429a1eb..72f1e599247 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic_builder.rs @@ -3,17 +3,17 @@ use proc_macro2::{Ident, Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; use syn::spanned::Spanned; -use syn::{parse_quote, Attribute, Meta, Path, Token, Type}; +use syn::{Attribute, Meta, Path, Token, Type, parse_quote}; use synstructure::{BindingInfo, Structure, VariantInfo}; use super::utils::SubdiagnosticVariant; use crate::diagnostics::error::{ - span_err, throw_invalid_attr, throw_span_err, DiagnosticDeriveError, + DiagnosticDeriveError, span_err, throw_invalid_attr, throw_span_err, }; use crate::diagnostics::utils::{ + FieldInfo, FieldInnerTy, FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind, build_field_mapping, is_doc_comment, report_error_if_not_applied_to_span, report_type_error, - should_generate_arg, type_is_bool, type_is_unit, type_matches_path, FieldInfo, FieldInnerTy, - FieldMap, HasFieldMap, SetOnce, SpannedOption, SubdiagnosticKind, + should_generate_arg, type_is_bool, type_is_unit, type_matches_path, }; /// What kind of diagnostic is being derived - a fatal/error/warning or a lint? diff --git a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs index 5d5d279eaf0..909083d5e86 100644 --- a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs @@ -8,13 +8,13 @@ use super::utils::SubdiagnosticVariant; use crate::diagnostics::error::{ - invalid_attr, span_err, throw_invalid_attr, throw_span_err, DiagnosticDeriveError, + DiagnosticDeriveError, invalid_attr, span_err, throw_invalid_attr, throw_span_err, }; use crate::diagnostics::utils::{ - build_field_mapping, build_suggestion_code, is_doc_comment, new_code_ident, - report_error_if_not_applied_to_applicability, report_error_if_not_applied_to_span, - should_generate_arg, AllowMultipleAlternatives, FieldInfo, FieldInnerTy, FieldMap, HasFieldMap, - SetOnce, SpannedOption, SubdiagnosticKind, + AllowMultipleAlternatives, FieldInfo, FieldInnerTy, FieldMap, HasFieldMap, SetOnce, + SpannedOption, SubdiagnosticKind, build_field_mapping, build_suggestion_code, is_doc_comment, + new_code_ident, report_error_if_not_applied_to_applicability, + report_error_if_not_applied_to_span, should_generate_arg, }; /// The central struct for constructing the `add_to_diag` method from an annotated struct. diff --git a/compiler/rustc_macros/src/diagnostics/utils.rs b/compiler/rustc_macros/src/diagnostics/utils.rs index 0d3b2f52fa2..5946b11828e 100644 --- a/compiler/rustc_macros/src/diagnostics/utils.rs +++ b/compiler/rustc_macros/src/diagnostics/utils.rs @@ -5,16 +5,16 @@ use proc_macro::Span; use proc_macro2::{Ident, TokenStream}; -use quote::{format_ident, quote, ToTokens}; +use quote::{ToTokens, format_ident, quote}; use syn::meta::ParseNestedMeta; use syn::punctuated::Punctuated; use syn::spanned::Spanned; -use syn::{parenthesized, Attribute, Field, LitStr, Meta, Path, Token, Type, TypeTuple}; +use syn::{Attribute, Field, LitStr, Meta, Path, Token, Type, TypeTuple, parenthesized}; use synstructure::{BindingInfo, VariantInfo}; use super::error::invalid_attr; use crate::diagnostics::error::{ - span_err, throw_invalid_attr, throw_span_err, DiagnosticDeriveError, + DiagnosticDeriveError, span_err, throw_invalid_attr, throw_span_err, }; thread_local! { diff --git a/compiler/rustc_macros/src/extension.rs b/compiler/rustc_macros/src/extension.rs index bbaa477237b..781a06f32eb 100644 --- a/compiler/rustc_macros/src/extension.rs +++ b/compiler/rustc_macros/src/extension.rs @@ -4,9 +4,9 @@ use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ - braced, parse_macro_input, Attribute, Generics, ImplItem, Pat, PatIdent, Path, Signature, - Token, TraitItem, TraitItemConst, TraitItemFn, TraitItemMacro, TraitItemType, Type, Visibility, - WhereClause, + Attribute, Generics, ImplItem, Pat, PatIdent, Path, Signature, Token, TraitItem, + TraitItemConst, TraitItemFn, TraitItemMacro, TraitItemType, Type, Visibility, WhereClause, + braced, parse_macro_input, }; pub(crate) fn extension( diff --git a/compiler/rustc_macros/src/lift.rs b/compiler/rustc_macros/src/lift.rs index bf4a7665ceb..341447f7e6f 100644 --- a/compiler/rustc_macros/src/lift.rs +++ b/compiler/rustc_macros/src/lift.rs @@ -40,14 +40,11 @@ pub(super) fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::To }); s.add_impl_generic(newtcx); - s.bound_impl( - quote!(::rustc_middle::ty::Lift<::rustc_middle::ty::TyCtxt<'__lifted>>), - quote! { - type Lifted = #lifted; + s.bound_impl(quote!(::rustc_middle::ty::Lift<::rustc_middle::ty::TyCtxt<'__lifted>>), quote! { + type Lifted = #lifted; - fn lift_to_interner(self, __tcx: ::rustc_middle::ty::TyCtxt<'__lifted>) -> Option<#lifted> { - Some(match self { #body }) - } - }, - ) + fn lift_to_interner(self, __tcx: ::rustc_middle::ty::TyCtxt<'__lifted>) -> Option<#lifted> { + Some(match self { #body }) + } + }) } diff --git a/compiler/rustc_macros/src/query.rs b/compiler/rustc_macros/src/query.rs index 886a38c8ff2..88ea6e07d6e 100644 --- a/compiler/rustc_macros/src/query.rs +++ b/compiler/rustc_macros/src/query.rs @@ -4,8 +4,8 @@ use syn::punctuated::Punctuated; use syn::spanned::Spanned; use syn::{ - braced, parenthesized, parse_macro_input, parse_quote, token, AttrStyle, Attribute, Block, - Error, Expr, Ident, Pat, ReturnType, Token, Type, + AttrStyle, Attribute, Block, Error, Expr, Ident, Pat, ReturnType, Token, Type, braced, + parenthesized, parse_macro_input, parse_quote, token, }; mod kw { diff --git a/compiler/rustc_macros/src/serialize.rs b/compiler/rustc_macros/src/serialize.rs index 2c33a0ac0aa..ce692abfb98 100644 --- a/compiler/rustc_macros/src/serialize.rs +++ b/compiler/rustc_macros/src/serialize.rs @@ -105,14 +105,11 @@ 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 { @@ -288,16 +285,13 @@ 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.rs b/compiler/rustc_macros/src/symbols.rs index 341186ac1ca..2552c0a0cfc 100644 --- a/compiler/rustc_macros/src/symbols.rs +++ b/compiler/rustc_macros/src/symbols.rs @@ -30,7 +30,7 @@ use quote::quote; use syn::parse::{Parse, ParseStream, Result}; use syn::punctuated::Punctuated; -use syn::{braced, Expr, Ident, Lit, LitStr, Macro, Token}; +use syn::{Expr, Ident, Lit, LitStr, Macro, Token, braced}; #[cfg(test)] mod tests; diff --git a/compiler/rustc_macros/src/symbols/tests.rs b/compiler/rustc_macros/src/symbols/tests.rs index 9c53453df5b..b32ce60e204 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_macros/src/type_foldable.rs b/compiler/rustc_macros/src/type_foldable.rs index 8ddfa96e095..bc3b82c2893 100644 --- a/compiler/rustc_macros/src/type_foldable.rs +++ b/compiler/rustc_macros/src/type_foldable.rs @@ -1,4 +1,4 @@ -use quote::{quote, ToTokens}; +use quote::{ToTokens, quote}; use syn::parse_quote; pub(super) fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 14a1a7f67e5..8adec7554a8 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -8,7 +8,7 @@ use std::{cmp, env, iter}; use proc_macro::bridge::client::ProcMacro; -use rustc_ast::expand::allocator::{alloc_error_handler_name, global_fn_name, AllocatorKind}; +use rustc_ast::expand::allocator::{AllocatorKind, alloc_error_handler_name, global_fn_name}; use rustc_ast::{self as ast, *}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::owned_slice::OwnedSlice; @@ -17,7 +17,7 @@ use rustc_errors::DiagCtxtHandle; use rustc_expand::base::SyntaxExtension; use rustc_fs_util::try_canonicalize; -use rustc_hir::def_id::{CrateNum, LocalDefId, StableCrateId, LOCAL_CRATE}; +use rustc_hir::def_id::{CrateNum, LOCAL_CRATE, LocalDefId, StableCrateId}; use rustc_hir::definitions::Definitions; use rustc_index::IndexVec; use rustc_middle::bug; @@ -28,8 +28,8 @@ use rustc_session::output::validate_crate_name; use rustc_session::search_paths::PathKind; use rustc_span::edition::Edition; -use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Symbol, sym}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::spec::{PanicStrategy, Target, TargetTriple}; use tracing::{debug, info, trace}; @@ -1063,15 +1063,12 @@ pub fn process_extern_crate( 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!(), @@ -1081,16 +1078,13 @@ pub fn process_extern_crate( 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_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index 42dec978b78..6587125ec67 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -4,7 +4,7 @@ use rustc_errors::codes::*; use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, EmissionGuarantee, Level}; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_span::{sym, Span, Symbol}; +use rustc_span::{Span, Symbol, sym}; use rustc_target::spec::{PanicStrategy, TargetTriple}; use crate::fluent_generated as fluent; diff --git a/compiler/rustc_metadata/src/fs.rs b/compiler/rustc_metadata/src/fs.rs index b2a979ed6d8..a58f3c6b5ca 100644 --- a/compiler/rustc_metadata/src/fs.rs +++ b/compiler/rustc_metadata/src/fs.rs @@ -12,7 +12,7 @@ BinaryOutputToTty, FailedCopyToStdout, FailedCreateEncodedMetadata, FailedCreateFile, FailedCreateTempdir, FailedWriteError, }; -use crate::{encode_metadata, EncodedMetadata}; +use crate::{EncodedMetadata, encode_metadata}; // FIXME(eddyb) maybe include the crate name in this? pub const METADATA_FILENAME: &str = "lib.rmeta"; diff --git a/compiler/rustc_metadata/src/lib.rs b/compiler/rustc_metadata/src/lib.rs index 02a9ce455b2..1759ea7d441 100644 --- a/compiler/rustc_metadata/src/lib.rs +++ b/compiler/rustc_metadata/src/lib.rs @@ -34,12 +34,12 @@ pub mod fs; pub mod locator; -pub use creader::{load_symbol_from_dylib, DylibError}; -pub use fs::{emit_wrapper_file, METADATA_FILENAME}; +pub use creader::{DylibError, load_symbol_from_dylib}; +pub use fs::{METADATA_FILENAME, emit_wrapper_file}; pub use native_libs::{ find_native_static_library, try_find_native_dynamic_library, try_find_native_static_library, walk_native_lib_search_dirs, }; -pub use rmeta::{encode_metadata, rendered_const, EncodedMetadata, METADATA_HEADER}; +pub use rmeta::{EncodedMetadata, METADATA_HEADER, encode_metadata, rendered_const}; rustc_fluent_macro::fluent_messages! { "../messages.ftl" } diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 90228db378a..089ac060ba8 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -224,20 +224,20 @@ use rustc_data_structures::svh::Svh; use rustc_errors::{DiagArgValue, IntoDiagArg}; use rustc_fs_util::try_canonicalize; +use rustc_session::Session; use rustc_session::cstore::CrateSource; use rustc_session::filesearch::FileSearch; use rustc_session::search_paths::PathKind; use rustc_session::utils::CanonicalizedPath; -use rustc_session::Session; -use rustc_span::symbol::Symbol; use rustc_span::Span; +use rustc_span::symbol::Symbol; use rustc_target::spec::{Target, TargetTriple}; use snap::read::FrameDecoder; use tracing::{debug, info}; use crate::creader::{Library, MetadataLoader}; use crate::errors; -use crate::rmeta::{rustc_version, MetadataBlob, METADATA_HEADER}; +use crate::rmeta::{METADATA_HEADER, MetadataBlob, rustc_version}; #[derive(Clone)] pub(crate) struct CrateLocator<'a> { diff --git a/compiler/rustc_metadata/src/native_libs.rs b/compiler/rustc_metadata/src/native_libs.rs index 0329a193d89..82b907d2501 100644 --- a/compiler/rustc_metadata/src/native_libs.rs +++ b/compiler/rustc_metadata/src/native_libs.rs @@ -1,11 +1,12 @@ use std::ops::ControlFlow; use std::path::{Path, PathBuf}; -use rustc_ast::{NestedMetaItem, CRATE_NODE_ID}; +use rustc_ast::{CRATE_NODE_ID, NestedMetaItem}; use rustc_attr as attr; use rustc_data_structures::fx::FxHashSet; use rustc_middle::query::LocalCrate; use rustc_middle::ty::{List, ParamEnv, ParamEnvAnd, Ty, TyCtxt}; +use rustc_session::Session; use rustc_session::config::CrateType; use rustc_session::cstore::{ DllCallingConvention, DllImport, ForeignModule, NativeLib, PeImportNameType, @@ -13,11 +14,10 @@ use rustc_session::parse::feature_err; use rustc_session::search_paths::PathKind; use rustc_session::utils::NativeLibKind; -use rustc_session::Session; use rustc_span::def_id::{DefId, LOCAL_CRATE}; -use rustc_span::symbol::{sym, Symbol}; -use rustc_target::spec::abi::Abi; +use rustc_span::symbol::{Symbol, sym}; use rustc_target::spec::LinkSelfContainedComponents; +use rustc_target::spec::abi::Abi; use crate::{errors, fluent_generated}; diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index f3ae24a5895..4425c93211a 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -22,16 +22,16 @@ use rustc_index::Idx; use rustc_middle::middle::lib_features::LibFeatures; use rustc_middle::mir::interpret::{AllocDecodingSession, AllocDecodingState}; -use rustc_middle::ty::codec::TyDecoder; use rustc_middle::ty::Visibility; +use rustc_middle::ty::codec::TyDecoder; use rustc_middle::{bug, implement_ty_decoder}; use rustc_serialize::opaque::MemDecoder; use rustc_serialize::{Decodable, Decoder}; -use rustc_session::cstore::{CrateSource, ExternCrate}; use rustc_session::Session; +use rustc_session::cstore::{CrateSource, ExternCrate}; use rustc_span::hygiene::HygieneDecodeContext; use rustc_span::symbol::kw; -use rustc_span::{BytePos, Pos, SpanData, SpanDecoder, SyntaxContext, DUMMY_SP}; +use rustc_span::{BytePos, DUMMY_SP, Pos, SpanData, SpanDecoder, SyntaxContext}; use tracing::debug; use crate::creader::CStore; diff --git a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs index b9d287730fa..53d2089296d 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder/cstore_impl.rs @@ -18,14 +18,14 @@ use rustc_middle::util::Providers; use rustc_session::cstore::{CrateStore, ExternCrate}; use rustc_session::{Session, StableCrateId}; -use rustc_span::hygiene::ExpnId; -use rustc_span::symbol::{kw, Symbol}; use rustc_span::Span; +use rustc_span::hygiene::ExpnId; +use rustc_span::symbol::{Symbol, kw}; use super::{Decodable, DecodeContext, DecodeIterator}; use crate::creader::{CStore, LoadedMacro}; -use crate::rmeta::table::IsDefault; use crate::rmeta::AttrFlags; +use crate::rmeta::table::IsDefault; use crate::{foreign_modules, native_libs}; trait ProcessQueryValue<'tcx, T> { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 46dc0696638..891f1793441 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -7,11 +7,11 @@ use rustc_ast::Attribute; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::memmap::{Mmap, MmapMut}; -use rustc_data_structures::sync::{join, par_for_each_in, Lrc}; +use rustc_data_structures::sync::{Lrc, join, par_for_each_in}; use rustc_data_structures::temp_dir::MaybeTempDir; use rustc_feature::Features; use rustc_hir as hir; -use rustc_hir::def_id::{LocalDefId, LocalDefIdSet, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE}; +use rustc_hir::def_id::{CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE, LocalDefId, LocalDefIdSet}; use rustc_hir::definitions::DefPathData; use rustc_hir_pretty::id_to_string; use rustc_middle::middle::dependency_format::Linkage; @@ -24,7 +24,7 @@ use rustc_middle::ty::{AssocItemContainer, SymbolName}; use rustc_middle::util::common::to_readable_str; use rustc_middle::{bug, span_bug}; -use rustc_serialize::{opaque, Decodable, Decoder, Encodable, Encoder}; +use rustc_serialize::{Decodable, Decoder, Encodable, Encoder, opaque}; use rustc_session::config::{CrateType, OptLevel}; use rustc_span::hygiene::HygieneEncodeContext; use rustc_span::symbol::sym; diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index c791a1f541c..79bd1c13b12 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -5,7 +5,7 @@ use decoder::{DecodeContext, Metadata}; use def_path_hash_map::DefPathHashMapRef; use encoder::EncodeContext; -pub use encoder::{encode_metadata, rendered_const, EncodedMetadata}; +pub use encoder::{EncodedMetadata, encode_metadata, rendered_const}; use rustc_ast::expand::StrippedCfgItem; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::svh::Svh; @@ -13,8 +13,8 @@ use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, DefIndex, DefPathHash, StableCrateId}; use rustc_hir::definitions::DefKey; use rustc_hir::lang_items::LangItem; -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_macros::{ Decodable, Encodable, MetadataDecodable, MetadataEncodable, TyDecodable, TyEncodable, }; diff --git a/compiler/rustc_middle/src/dep_graph/dep_node.rs b/compiler/rustc_middle/src/dep_graph/dep_node.rs index 2d47d1d19af..87bbeb178ee 100644 --- a/compiler/rustc_middle/src/dep_graph/dep_node.rs +++ b/compiler/rustc_middle/src/dep_graph/dep_node.rs @@ -57,12 +57,12 @@ //! [dependency graph]: https://rustc-dev-guide.rust-lang.org/query.html use rustc_data_structures::fingerprint::Fingerprint; -use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, ModDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalModDefId, ModDefId}; use rustc_hir::definitions::DefPathHash; use rustc_hir::{HirId, ItemLocalId, OwnerId}; -pub use rustc_query_system::dep_graph::dep_node::DepKind; pub use rustc_query_system::dep_graph::DepNode; use rustc_query_system::dep_graph::FingerprintStyle; +pub use rustc_query_system::dep_graph::dep_node::DepKind; pub(crate) use rustc_query_system::dep_graph::{DepContext, DepNodeParams}; use rustc_span::symbol::Symbol; diff --git a/compiler/rustc_middle/src/dep_graph/mod.rs b/compiler/rustc_middle/src/dep_graph/mod.rs index b24954584fe..2090c3e6da6 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -7,12 +7,12 @@ #[macro_use] mod dep_node; -pub use dep_node::{dep_kinds, label_strs, DepKind, DepNode, DepNodeExt}; +pub use dep_node::{DepKind, DepNode, DepNodeExt, dep_kinds, label_strs}; pub(crate) use dep_node::{make_compile_codegen_unit, make_compile_mono_item}; pub use rustc_query_system::dep_graph::debug::{DepNodeFilter, EdgeFilter}; pub use rustc_query_system::dep_graph::{ - hash_result, DepContext, DepGraphQuery, DepNodeIndex, Deps, SerializedDepGraph, - SerializedDepNodeIndex, TaskDepsRef, WorkProduct, WorkProductId, WorkProductMap, + DepContext, DepGraphQuery, DepNodeIndex, Deps, SerializedDepGraph, SerializedDepNodeIndex, + TaskDepsRef, WorkProduct, WorkProductId, WorkProductMap, hash_result, }; pub type DepGraph = rustc_query_system::dep_graph::DepGraph; diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 8b0a855612c..167b5aef68b 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -1,16 +1,16 @@ -use rustc_ast::visit::{walk_list, VisitorResult}; +use rustc_ast::visit::{VisitorResult, walk_list}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::svh::Svh; -use rustc_data_structures::sync::{par_for_each_in, try_par_for_each_in, DynSend, DynSync}; +use rustc_data_structures::sync::{DynSend, DynSync, par_for_each_in, try_par_for_each_in}; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId, LocalModDefId}; use rustc_hir::definitions::{DefKey, DefPath, DefPathHash}; use rustc_hir::intravisit::Visitor; use rustc_hir::*; use rustc_middle::hir::nested_filter; use rustc_span::def_id::StableCrateId; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use rustc_span::{ErrorGuaranteed, Span}; use rustc_target::spec::abi::Abi; use {rustc_ast as ast, rustc_hir_pretty as pprust_hir}; diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 596d9f07737..7a07ef80ded 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -9,7 +9,7 @@ use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::sorted_map::SortedMap; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; -use rustc_data_structures::sync::{try_par_for_each_in, DynSend, DynSync}; +use rustc_data_structures::sync::{DynSend, DynSync, try_par_for_each_in}; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId}; use rustc_hir::*; diff --git a/compiler/rustc_middle/src/hooks/mod.rs b/compiler/rustc_middle/src/hooks/mod.rs index bde05210d9f..742797fdeef 100644 --- a/compiler/rustc_middle/src/hooks/mod.rs +++ b/compiler/rustc_middle/src/hooks/mod.rs @@ -6,7 +6,7 @@ use rustc_hir::def_id::{DefId, DefPathHash}; use rustc_session::StableCrateId; use rustc_span::def_id::{CrateNum, LocalDefId}; -use rustc_span::{ExpnHash, ExpnId, DUMMY_SP}; +use rustc_span::{DUMMY_SP, ExpnHash, ExpnId}; use tracing::instrument; use crate::mir; diff --git a/compiler/rustc_middle/src/infer/unify_key.rs b/compiler/rustc_middle/src/infer/unify_key.rs index 3fd4aba3169..cf692b145b8 100644 --- a/compiler/rustc_middle/src/infer/unify_key.rs +++ b/compiler/rustc_middle/src/infer/unify_key.rs @@ -2,8 +2,8 @@ use std::marker::PhantomData; use rustc_data_structures::unify::{NoError, UnifyKey, UnifyValue}; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; use crate::ty::{self, Ty, TyCtxt}; diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 70da66af64b..b5862565e8e 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -5,11 +5,11 @@ use rustc_errors::{Diag, MultiSpan}; use rustc_hir::{HirId, ItemLocalId}; use rustc_macros::HashStable; +use rustc_session::Session; use rustc_session::lint::builtin::{self, FORBIDDEN_LINT_GROUPS}; use rustc_session::lint::{FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId}; -use rustc_session::Session; use rustc_span::hygiene::{ExpnKind, MacroKind}; -use rustc_span::{symbol, DesugaringKind, Span, Symbol, DUMMY_SP}; +use rustc_span::{DUMMY_SP, DesugaringKind, Span, Symbol, symbol}; use tracing::instrument; use crate::ty::TyCtxt; diff --git a/compiler/rustc_middle/src/middle/lang_items.rs b/compiler/rustc_middle/src/middle/lang_items.rs index f141af44900..b20673fe8da 100644 --- a/compiler/rustc_middle/src/middle/lang_items.rs +++ b/compiler/rustc_middle/src/middle/lang_items.rs @@ -7,8 +7,8 @@ //! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`. //! * Functions called by the compiler itself. -use rustc_hir::def_id::DefId; use rustc_hir::LangItem; +use rustc_hir::def_id::DefId; use rustc_span::Span; use rustc_target::spec::PanicStrategy; diff --git a/compiler/rustc_middle/src/middle/limits.rs b/compiler/rustc_middle/src/middle/limits.rs index 70810f51a1f..270bcabcc86 100644 --- a/compiler/rustc_middle/src/middle/limits.rs +++ b/compiler/rustc_middle/src/middle/limits.rs @@ -12,7 +12,7 @@ use rustc_ast::Attribute; use rustc_session::{Limit, Limits, Session}; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; use crate::error::LimitInvalid; use crate::query::Providers; diff --git a/compiler/rustc_middle/src/middle/mod.rs b/compiler/rustc_middle/src/middle/mod.rs index 0c4f37ab14f..83873439bd9 100644 --- a/compiler/rustc_middle/src/middle/mod.rs +++ b/compiler/rustc_middle/src/middle/mod.rs @@ -6,8 +6,8 @@ pub mod lib_features { use rustc_data_structures::unord::UnordMap; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; - use rustc_span::symbol::Symbol; use rustc_span::Span; + use rustc_span::symbol::Symbol; #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[derive(HashStable, TyEncodable, TyDecodable)] diff --git a/compiler/rustc_middle/src/middle/privacy.rs b/compiler/rustc_middle/src/middle/privacy.rs index db70f53b7b4..03549091d62 100644 --- a/compiler/rustc_middle/src/middle/privacy.rs +++ b/compiler/rustc_middle/src/middle/privacy.rs @@ -9,7 +9,7 @@ use rustc_hir::def::DefKind; use rustc_macros::HashStable; use rustc_query_system::ich::StableHashingContext; -use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID}; +use rustc_span::def_id::{CRATE_DEF_ID, LocalDefId}; use crate::ty::{TyCtxt, Visibility}; diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index 999743ed73b..4e44de33611 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -14,7 +14,7 @@ use rustc_hir as hir; use rustc_hir::{HirId, HirIdMap, Node}; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::debug; use crate::ty::TyCtxt; diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index 86dca27f04f..54cfd995832 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -15,12 +15,12 @@ use rustc_hir::{self as hir, HirId}; use rustc_macros::{Decodable, Encodable, HashStable, Subdiagnostic}; use rustc_middle::ty::print::with_no_trimmed_paths; +use rustc_session::Session; use rustc_session::lint::builtin::{DEPRECATED, DEPRECATED_IN_FUTURE, SOFT_UNSTABLE}; use rustc_session::lint::{BuiltinLintDiag, DeprecatedSinceKind, Level, Lint, LintBuffer}; use rustc_session::parse::feature_err_issue; -use rustc_session::Session; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, sym}; use tracing::debug; pub use self::StabilityLevel::*; diff --git a/compiler/rustc_middle/src/mir/basic_blocks.rs b/compiler/rustc_middle/src/mir/basic_blocks.rs index 63ce47ef327..4602c918160 100644 --- a/compiler/rustc_middle/src/mir/basic_blocks.rs +++ b/compiler/rustc_middle/src/mir/basic_blocks.rs @@ -1,6 +1,6 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::graph; -use rustc_data_structures::graph::dominators::{dominators, Dominators}; +use rustc_data_structures::graph::dominators::{Dominators, dominators}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::sync::OnceLock; use rustc_index::{IndexSlice, IndexVec}; @@ -9,7 +9,7 @@ use smallvec::SmallVec; use crate::mir::traversal::Postorder; -use crate::mir::{BasicBlock, BasicBlockData, Terminator, TerminatorKind, START_BLOCK}; +use crate::mir::{BasicBlock, BasicBlockData, START_BLOCK, Terminator, TerminatorKind}; #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable, TypeVisitable)] pub struct BasicBlocks<'tcx> { diff --git a/compiler/rustc_middle/src/mir/consts.rs b/compiler/rustc_middle/src/mir/consts.rs index c6105d1f383..89d4c460160 100644 --- a/compiler/rustc_middle/src/mir/consts.rs +++ b/compiler/rustc_middle/src/mir/consts.rs @@ -2,13 +2,13 @@ use rustc_hir::def_id::DefId; use rustc_macros::{HashStable, Lift, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; -use rustc_session::config::RemapPathScopeComponents; use rustc_session::RemapFileNameExt; -use rustc_span::{Span, DUMMY_SP}; +use rustc_session::config::RemapPathScopeComponents; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi::{HasDataLayout, Size}; -use crate::mir::interpret::{alloc_range, AllocId, ConstAllocation, ErrorHandled, Scalar}; -use crate::mir::{pretty_print_const_value, Promoted}; +use crate::mir::interpret::{AllocId, ConstAllocation, ErrorHandled, Scalar, alloc_range}; +use crate::mir::{Promoted, pretty_print_const_value}; use crate::ty::print::{pretty_print_const, with_no_trimmed_paths}; use crate::ty::{self, GenericArgsRef, ScalarInt, Ty, TyCtxt}; diff --git a/compiler/rustc_middle/src/mir/interpret/allocation.rs b/compiler/rustc_middle/src/mir/interpret/allocation.rs index 4c5da188860..b8ecfa3c3f9 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation.rs @@ -18,9 +18,9 @@ use rustc_target::abi::{Align, HasDataLayout, Size}; use super::{ - read_target_uint, write_target_uint, AllocId, BadBytesAccess, CtfeProvenance, InterpError, - InterpResult, Pointer, PointerArithmetic, Provenance, ResourceExhaustionInfo, Scalar, - ScalarSizeMismatch, UndefinedBehaviorInfo, UnsupportedOpInfo, + AllocId, BadBytesAccess, CtfeProvenance, InterpError, InterpResult, Pointer, PointerArithmetic, + Provenance, ResourceExhaustionInfo, Scalar, ScalarSizeMismatch, UndefinedBehaviorInfo, + UnsupportedOpInfo, read_target_uint, write_target_uint, }; use crate::ty; diff --git a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs index 4fe219441a0..b3940530f69 100644 --- a/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs +++ b/compiler/rustc_middle/src/mir/interpret/allocation/provenance_map.rs @@ -9,7 +9,7 @@ use rustc_target::abi::{HasDataLayout, Size}; use tracing::trace; -use super::{alloc_range, AllocError, AllocRange, AllocResult, CtfeProvenance, Provenance}; +use super::{AllocError, AllocRange, AllocResult, CtfeProvenance, Provenance, alloc_range}; /// Stores the provenance information of pointers stored in memory. #[derive(Clone, PartialEq, Eq, Hash, Debug)] diff --git a/compiler/rustc_middle/src/mir/interpret/error.rs b/compiler/rustc_middle/src/mir/interpret/error.rs index 8c89c15f961..89507f1049a 100644 --- a/compiler/rustc_middle/src/mir/interpret/error.rs +++ b/compiler/rustc_middle/src/mir/interpret/error.rs @@ -10,13 +10,13 @@ use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_session::CtfeBacktrace; use rustc_span::def_id::DefId; -use rustc_span::{Span, Symbol, DUMMY_SP}; -use rustc_target::abi::{call, Align, Size, VariantIdx, WrappingRange}; +use rustc_span::{DUMMY_SP, Span, Symbol}; +use rustc_target::abi::{Align, Size, VariantIdx, WrappingRange, call}; use super::{AllocId, AllocRange, ConstAllocation, Pointer, Scalar}; use crate::error; use crate::mir::{ConstAlloc, ConstValue}; -use crate::ty::{self, layout, tls, Ty, TyCtxt, ValTree}; +use crate::ty::{self, Ty, TyCtxt, ValTree, layout, tls}; #[derive(Debug, Copy, Clone, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)] pub enum ErrorHandled { diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 91e71c12cae..3af8f0db3f7 100644 --- a/compiler/rustc_middle/src/mir/interpret/mod.rs +++ b/compiler/rustc_middle/src/mir/interpret/mod.rs @@ -30,8 +30,8 @@ }; pub use self::allocation::{ - alloc_range, AllocBytes, AllocError, AllocRange, AllocResult, Allocation, ConstAllocation, - InitChunk, InitChunkIter, + AllocBytes, AllocError, AllocRange, AllocResult, Allocation, ConstAllocation, InitChunk, + InitChunkIter, alloc_range, }; pub use self::error::{ BadBytesAccess, CheckAlignMsg, CheckInAllocMsg, ErrorHandled, EvalStaticInitializerRawResult, diff --git a/compiler/rustc_middle/src/mir/interpret/queries.rs b/compiler/rustc_middle/src/mir/interpret/queries.rs index 675e78603ae..59bc55269a3 100644 --- a/compiler/rustc_middle/src/mir/interpret/queries.rs +++ b/compiler/rustc_middle/src/mir/interpret/queries.rs @@ -1,7 +1,7 @@ use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_session::lint; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; use super::{ diff --git a/compiler/rustc_middle/src/mir/interpret/value.rs b/compiler/rustc_middle/src/mir/interpret/value.rs index 989f03d3d13..c6c2ab414ed 100644 --- a/compiler/rustc_middle/src/mir/interpret/value.rs +++ b/compiler/rustc_middle/src/mir/interpret/value.rs @@ -1,8 +1,8 @@ use std::fmt; use either::{Either, Left, Right}; -use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::Float; +use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_target::abi::{HasDataLayout, Size}; diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index 54dcfaf5d54..cd148aef29b 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -16,7 +16,7 @@ use rustc_data_structures::graph::dominators::Dominators; use rustc_errors::{DiagArgName, DiagArgValue, DiagMessage, ErrorGuaranteed, IntoDiagArg}; use rustc_hir::def::{CtorKind, Namespace}; -use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; use rustc_hir::{ self as hir, BindingMode, ByRef, CoroutineDesugaring, CoroutineKind, HirId, ImplicitSelfKind, }; @@ -26,7 +26,7 @@ use rustc_serialize::{Decodable, Encodable}; use rustc_span::source_map::Spanned; use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi::{FieldIdx, VariantIdx}; use tracing::trace; @@ -36,7 +36,7 @@ use crate::mir::visit::MirVisitable; use crate::ty::codec::{TyDecoder, TyEncoder}; use crate::ty::fold::{FallibleTypeFolder, TypeFoldable}; -use crate::ty::print::{pretty_print_const, with_no_trimmed_paths, FmtPrinter, Printer}; +use crate::ty::print::{FmtPrinter, Printer, pretty_print_const, with_no_trimmed_paths}; use crate::ty::visit::TypeVisitableExt; use crate::ty::{ self, AdtDef, GenericArg, GenericArgsRef, Instance, InstanceKind, List, Ty, TyCtxt, @@ -72,7 +72,7 @@ pub use self::generic_graph::graphviz_safe_def_name; pub use self::graphviz::write_mir_graphviz; pub use self::pretty::{ - create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty, PassWhere, + PassWhere, create_dump_file, display_allocation, dump_enabled, dump_mir, write_mir_pretty, }; /// Types for locals @@ -1399,10 +1399,10 @@ pub fn expand_statements(&mut self, mut f: F) // 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/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 69b5e0a79c7..954f746ce5b 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -2,19 +2,19 @@ use std::hash::Hash; use rustc_attr::InlineAttr; -use rustc_data_structures::base_n::{BaseNString, ToBaseN, CASE_INSENSITIVE}; +use rustc_data_structures::base_n::{BaseNString, CASE_INSENSITIVE, ToBaseN}; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hasher::{Hash128, HashStable, StableHasher, ToStableHashKey}; use rustc_data_structures::unord::UnordMap; -use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc_hir::ItemId; +use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use rustc_index::Idx; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; use rustc_query_system::ich::StableHashingContext; use rustc_session::config::OptLevel; -use rustc_span::symbol::Symbol; use rustc_span::Span; +use rustc_span::symbol::Symbol; use tracing::debug; use crate::dep_graph::{DepNode, WorkProduct, WorkProductId}; diff --git a/compiler/rustc_middle/src/mir/pretty.rs b/compiler/rustc_middle/src/mir/pretty.rs index d66d0be1009..612055eb879 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -6,8 +6,8 @@ use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; use rustc_middle::mir::interpret::{ - alloc_range, read_target_uint, AllocBytes, AllocId, Allocation, GlobalAlloc, Pointer, - Provenance, + AllocBytes, AllocId, Allocation, GlobalAlloc, Pointer, Provenance, alloc_range, + read_target_uint, }; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index a36e49f6ee0..1002f64f849 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -10,8 +10,8 @@ use rustc_index::bit_set::BitMatrix; use rustc_index::{Idx, IndexVec}; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; -use rustc_span::symbol::Symbol; use rustc_span::Span; +use rustc_span::symbol::Symbol; use rustc_target::abi::{FieldIdx, VariantIdx}; use smallvec::SmallVec; diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index f5590aa2762..231eb198983 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -5,14 +5,14 @@ use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece, Mutability}; use rustc_data_structures::packed::Pu128; -use rustc_hir::def_id::DefId; use rustc_hir::CoroutineKind; +use rustc_hir::def_id::DefId; use rustc_index::IndexVec; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; +use rustc_span::Span; use rustc_span::def_id::LocalDefId; use rustc_span::source_map::Spanned; use rustc_span::symbol::Symbol; -use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_target::asm::InlineAsmRegOrRegClass; use smallvec::SmallVec; diff --git a/compiler/rustc_middle/src/mir/terminator.rs b/compiler/rustc_middle/src/mir/terminator.rs index c34e22eb873..783952fb9cb 100644 --- a/compiler/rustc_middle/src/mir/terminator.rs +++ b/compiler/rustc_middle/src/mir/terminator.rs @@ -5,7 +5,7 @@ use rustc_data_structures::packed::Pu128; use rustc_hir::LangItem; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use super::{TerminatorKind, *}; diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index 6562d46d7b8..80adbe74fe7 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -1,10 +1,10 @@ //! Defines the set of legal keys that can be used in queries. -use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalModDefId, ModDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalModDefId, ModDefId}; use rustc_hir::hir_id::{HirId, OwnerId}; use rustc_query_system::query::{DefIdCache, DefaultCache, SingleCache, VecCache}; use rustc_span::symbol::{Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi; use crate::infer::canonical::Canonical; diff --git a/compiler/rustc_middle/src/query/mod.rs b/compiler/rustc_middle/src/query/mod.rs index 969374cb0e5..00036097ef5 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -12,8 +12,8 @@ use std::sync::Arc; use rustc_arena::TypedArena; -use rustc_ast::expand::allocator::AllocatorKind; use rustc_ast::expand::StrippedCfgItem; +use rustc_ast::expand::allocator::AllocatorKind; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::steal::Steal; @@ -30,16 +30,16 @@ use rustc_index::IndexVec; use rustc_macros::rustc_queries; use rustc_query_system::ich::StableHashingContext; -use rustc_query_system::query::{try_get_cached, QueryCache, QueryMode, QueryState}; +use rustc_query_system::query::{QueryCache, QueryMode, QueryState, try_get_cached}; +use rustc_session::Limits; use rustc_session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion}; use rustc_session::cstore::{ CrateDepKind, CrateSource, ExternCrate, ForeignModule, LinkagePreference, NativeLib, }; use rustc_session::lint::LintExpectationId; -use rustc_session::Limits; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi; use rustc_target::spec::PanicStrategy; use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; @@ -59,9 +59,9 @@ EvalToValTreeResult, GlobalId, LitToConstError, LitToConstInput, }; use crate::mir::mono::CodegenUnit; -use crate::query::erase::{erase, restore, Erase}; +use crate::query::erase::{Erase, erase, restore}; use crate::query::plumbing::{ - query_ensure, query_ensure_error_guaranteed, query_get_at, CyclePlaceholder, DynamicQuery, + CyclePlaceholder, DynamicQuery, query_ensure, query_ensure_error_guaranteed, query_get_at, }; use crate::traits::query::{ CanonicalAliasGoal, CanonicalPredicateGoal, CanonicalTyGoal, @@ -70,12 +70,12 @@ MethodAutoderefStepsResult, NoSolution, NormalizationResult, OutlivesBound, }; use crate::traits::{ - specialization_graph, CodegenObligationError, EvaluationResult, ImplSource, - ObjectSafetyViolation, ObligationCause, OverflowError, WellFormedLoc, + CodegenObligationError, EvaluationResult, ImplSource, ObjectSafetyViolation, ObligationCause, + OverflowError, WellFormedLoc, specialization_graph, }; use crate::ty::fast_reject::SimplifiedType; use crate::ty::layout::ValidityRequirement; -use crate::ty::print::{describe_as_module, PrintTraitRefExt}; +use crate::ty::print::{PrintTraitRefExt, describe_as_module}; use crate::ty::util::AlwaysRequiresDrop; use crate::ty::{ self, CrateInherentImpls, GenericArg, GenericArgsRef, ParamEnvAnd, Ty, TyCtxt, TyCtxtFeed, diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index ca52358218e..06c9ebc87b5 100644 --- a/compiler/rustc_middle/src/query/on_disk_cache.rs +++ b/compiler/rustc_middle/src/query/on_disk_cache.rs @@ -6,7 +6,7 @@ use rustc_data_structures::sync::{HashMapExt, Lock, Lrc, RwLock}; use rustc_data_structures::unhash::UnhashMap; use rustc_data_structures::unord::{UnordMap, UnordSet}; -use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, StableCrateId, LOCAL_CRATE}; +use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, LocalDefId, StableCrateId}; use rustc_hir::definitions::DefPathHash; use rustc_index::{Idx, IndexVec}; use rustc_macros::{Decodable, Encodable}; @@ -328,18 +328,15 @@ pub fn serialize(&self, tcx: TyCtxt<'_>, encoder: FileEncoder) -> FileEncodeResu // 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/query/plumbing.rs b/compiler/rustc_middle/src/query/plumbing.rs index 0320a91d142..564d274bc8b 100644 --- a/compiler/rustc_middle/src/query/plumbing.rs +++ b/compiler/rustc_middle/src/query/plumbing.rs @@ -5,11 +5,11 @@ use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::hir_id::OwnerId; use rustc_macros::HashStable; +use rustc_query_system::HandleCycleError; use rustc_query_system::dep_graph::{DepNodeIndex, SerializedDepNodeIndex}; pub(crate) use rustc_query_system::query::QueryJobId; use rustc_query_system::query::*; -use rustc_query_system::HandleCycleError; -use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use crate::dep_graph; use crate::dep_graph::DepKind; diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index aca1390935e..32234d6b55d 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -16,7 +16,7 @@ use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::{BindingMode, ByRef, HirId, MatchSource, RangeEnd}; -use rustc_index::{newtype_index, IndexVec}; +use rustc_index::{IndexVec, newtype_index}; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeVisitable}; use rustc_middle::middle::region; use rustc_middle::mir::interpret::AllocId; diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index a3277fb96d2..c3295a9ce51 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -14,17 +14,17 @@ use rustc_data_structures::sync::Lrc; use rustc_errors::{Applicability, Diag, EmissionGuarantee}; use rustc_hir as hir; -use rustc_hir::def_id::DefId; use rustc_hir::HirId; +use rustc_hir::def_id::DefId; use rustc_macros::{ Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable, }; -use rustc_span::def_id::{LocalDefId, CRATE_DEF_ID}; +use rustc_span::def_id::{CRATE_DEF_ID, LocalDefId}; use rustc_span::symbol::Symbol; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; // FIXME: Remove this import and import via `solve::` pub use rustc_type_ir::solve::{BuiltinImplSource, Reveal}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache}; use crate::mir::ConstraintCategory; diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 204f61b4804..8f89f5c25af 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -17,7 +17,7 @@ use rustc_query_system::ich::StableHashingContext; use rustc_session::DataTypeKind; use rustc_span::symbol::sym; -use rustc_target::abi::{ReprOptions, VariantIdx, FIRST_VARIANT}; +use rustc_target::abi::{FIRST_VARIANT, ReprOptions, VariantIdx}; use tracing::{debug, info, trace}; use super::{ diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index 809801c33e1..9ee82942911 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -3,8 +3,8 @@ use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::FxIndexMap; use rustc_hir as hir; -use rustc_hir::def_id::LocalDefId; use rustc_hir::HirId; +use rustc_hir::def_id::LocalDefId; use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; use rustc_span::def_id::LocalDefIdMap; use rustc_span::symbol::Ident; diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 1a584cf2890..73d0acf95f4 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -18,7 +18,7 @@ pub use int::*; pub use kind::*; -use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; pub use valtree::*; pub type ConstKind<'tcx> = ir::ConstKind>; @@ -242,13 +242,10 @@ pub fn from_anon_const(tcx: TyCtxt<'tcx>, def: LocalDefId) -> Self { match Self::try_from_lit_or_param(tcx, ty, expr) { Some(v) => v, - None => ty::Const::new_unevaluated( - tcx, - ty::UnevaluatedConst { - def: def.to_def_id(), - args: GenericArgs::identity_for_item(tcx, def.to_def_id()), - }, - ), + None => ty::Const::new_unevaluated(tcx, ty::UnevaluatedConst { + def: def.to_def_id(), + args: GenericArgs::identity_for_item(tcx, def.to_def_id()), + }), } } diff --git a/compiler/rustc_middle/src/ty/consts/int.rs b/compiler/rustc_middle/src/ty/consts/int.rs index 0024a2ae756..1732374ab8c 100644 --- a/compiler/rustc_middle/src/ty/consts/int.rs +++ b/compiler/rustc_middle/src/ty/consts/int.rs @@ -1,8 +1,8 @@ use std::fmt; use std::num::NonZero; -use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::Float; +use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_errors::{DiagArgValue, IntoDiagArg}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use rustc_target::abi::Size; diff --git a/compiler/rustc_middle/src/ty/consts/kind.rs b/compiler/rustc_middle/src/ty/consts/kind.rs index c7c2e8afa1e..91b764ae1d4 100644 --- a/compiler/rustc_middle/src/ty/consts/kind.rs +++ b/compiler/rustc_middle/src/ty/consts/kind.rs @@ -1,6 +1,6 @@ use std::assert_matches::assert_matches; -use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; +use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable, extension}; use super::Const; use crate::mir; @@ -31,13 +31,10 @@ fn prepare_for_eval( // FIXME(eddyb, skinny121) pass `InferCtxt` into here when it's available, so that // we can call `infcx.const_eval_resolve` which handles inference variables. if (param_env, self).has_non_region_infer() { - ( - tcx.param_env(self.def), - ty::UnevaluatedConst { - def: self.def, - args: ty::GenericArgs::identity_for_item(tcx, self.def), - }, - ) + (tcx.param_env(self.def), ty::UnevaluatedConst { + def: self.def, + args: ty::GenericArgs::identity_for_item(tcx, self.def), + }) } else { (tcx.erase_regions(param_env).with_reveal_all_normalized(tcx), tcx.erase_regions(self)) } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index cd06d7b8e53..f017216489d 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -30,7 +30,7 @@ }; use rustc_hir as hir; use rustc_hir::def::DefKind; -use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::definitions::Definitions; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; @@ -45,17 +45,17 @@ use rustc_session::cstore::{CrateStoreDyn, Untracked}; use rustc_session::lint::Lint; use rustc_session::{Limit, MetadataKind, Session}; -use rustc_span::def_id::{DefPathHash, StableCrateId, CRATE_DEF_ID}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::def_id::{CRATE_DEF_ID, DefPathHash, StableCrateId}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi::{FieldIdx, Layout, LayoutS, TargetDataLayout, VariantIdx}; use rustc_target::spec::abi; +use rustc_type_ir::TyKind::*; use rustc_type_ir::fold::TypeFoldable; use rustc_type_ir::lang_items::TraitSolverLangItem; pub use rustc_type_ir::lift::Lift; use rustc_type_ir::solve::SolverMode; -use rustc_type_ir::TyKind::*; -use rustc_type_ir::{search_graph, CollectAndApply, Interner, TypeFlags, WithCachedTypeInfo}; +use rustc_type_ir::{CollectAndApply, Interner, TypeFlags, WithCachedTypeInfo, search_graph}; use tracing::{debug, instrument}; use crate::arena::Arena; @@ -1015,10 +1015,10 @@ fn new(interners: &CtxtInterners<'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::BrAnon }, - )) + mk(ty::ReBound(ty::DebruijnIndex::from(i), ty::BoundRegion { + var: ty::BoundVar::from(v), + kind: ty::BrAnon, + })) }) .collect() }) @@ -3052,15 +3052,12 @@ pub fn map_opaque_lifetime_to_parent_lifetime( } 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()), + }); } Some(resolve_bound_vars::ResolvedArg::LateBound(_, _, lbv)) => { let new_parent = self.local_parent(lbv); diff --git a/compiler/rustc_middle/src/ty/diagnostics.rs b/compiler/rustc_middle/src/ty/diagnostics.rs index c14dadc68c9..992eb264163 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -5,7 +5,7 @@ use std::ops::ControlFlow; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{into_diag_arg_using_display, Applicability, Diag, DiagArgValue, IntoDiagArg}; +use rustc_errors::{Applicability, Diag, DiagArgValue, IntoDiagArg, into_diag_arg_using_display}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, LangItem, PredicateOrigin, WherePredicate}; diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index d974a86a303..b02eff3bfd6 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -8,7 +8,7 @@ use rustc_macros::extension; pub use rustc_type_ir::error::ExpectedFound; -use crate::ty::print::{with_forced_trimmed_paths, FmtPrinter, PrettyPrinter}; +use crate::ty::print::{FmtPrinter, PrettyPrinter, with_forced_trimmed_paths}; use crate::ty::{self, Ty, TyCtxt}; pub type TypeError<'tcx> = rustc_type_ir::error::TypeError>; diff --git a/compiler/rustc_middle/src/ty/fold.rs b/compiler/rustc_middle/src/ty/fold.rs index 7892ef81819..2ee7497497a 100644 --- a/compiler/rustc_middle/src/ty/fold.rs +++ b/compiler/rustc_middle/src/ty/fold.rs @@ -1,7 +1,7 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_hir::def_id::DefId; pub use rustc_type_ir::fold::{ - shift_region, shift_vars, FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable, + FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable, shift_region, shift_vars, }; use tracing::{debug, instrument}; @@ -336,26 +336,21 @@ pub fn shift_bound_var_indices(self, bound_vars: usize, value: T) -> T 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 }, - ) - }, - 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)), + 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)), + }) } /// Replaces any late-bound regions bound in `value` with `'erased`. Useful in codegen but also diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 80c31e236e2..daf1362e25c 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -11,7 +11,7 @@ use rustc_data_structures::intern::Interned; use rustc_errors::{DiagArgValue, IntoDiagArg}; use rustc_hir::def_id::DefId; -use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable}; +use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable, extension}; use rustc_serialize::{Decodable, Encodable}; use rustc_type_ir::WithCachedTypeInfo; use smallvec::SmallVec; diff --git a/compiler/rustc_middle/src/ty/generics.rs b/compiler/rustc_middle/src/ty/generics.rs index 5f9a89c3a5b..660686f4aa2 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -2,8 +2,8 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::DefId; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; -use rustc_span::symbol::{kw, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, kw}; use tracing::instrument; use super::{Clause, InstantiatedPredicates, ParamConst, ParamTy, Ty, TyCtxt}; diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 072951d1319..bfef4c4c8c6 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -12,12 +12,12 @@ use rustc_macros::{Decodable, Encodable, HashStable, Lift, TyDecodable, TyEncodable}; use rustc_middle::ty::normalize_erasing_regions::NormalizationError; use rustc_span::def_id::LOCAL_CRATE; -use rustc_span::{Span, Symbol, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span, Symbol}; use tracing::{debug, instrument}; use crate::error; use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; -use crate::ty::print::{shrunk_instance_name, FmtPrinter, Printer}; +use crate::ty::print::{FmtPrinter, Printer, shrunk_instance_name}; use crate::ty::{ self, EarlyBinder, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, diff --git a/compiler/rustc_middle/src/ty/intrinsic.rs b/compiler/rustc_middle/src/ty/intrinsic.rs index 41a966da8aa..ed0fb37d3b8 100644 --- a/compiler/rustc_middle/src/ty/intrinsic.rs +++ b/compiler/rustc_middle/src/ty/intrinsic.rs @@ -1,6 +1,6 @@ use rustc_macros::{Decodable, Encodable, HashStable}; -use rustc_span::def_id::DefId; use rustc_span::Symbol; +use rustc_span::def_id::DefId; use super::TyCtxt; diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 941091b71d3..cf0c29e0c8c 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -7,13 +7,13 @@ Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, EmissionGuarantee, IntoDiagArg, Level, }; use rustc_hir as hir; -use rustc_hir::def_id::DefId; use rustc_hir::LangItem; +use rustc_hir::def_id::DefId; use rustc_index::IndexVec; -use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable}; +use rustc_macros::{HashStable, TyDecodable, TyEncodable, extension}; use rustc_session::config::OptLevel; -use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; +use rustc_span::symbol::{Symbol, sym}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use rustc_target::abi::call::FnAbi; use rustc_target::abi::*; use rustc_target::spec::abi::Abi as SpecAbi; @@ -1295,11 +1295,10 @@ fn fn_abi_of_instance( // However, we don't do this early in order to avoid calling // `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/list.rs b/compiler/rustc_middle/src/ty/list.rs index af76d5b7d92..ec9ca65dbda 100644 --- a/compiler/rustc_middle/src/ty/list.rs +++ b/compiler/rustc_middle/src/ty/list.rs @@ -4,7 +4,7 @@ use std::ops::Deref; use std::{fmt, iter, mem, ptr, slice}; -use rustc_data_structures::aligned::{align_of, Aligned}; +use rustc_data_structures::aligned::{Aligned, align_of}; #[cfg(parallel_compiler)] use rustc_data_structures::sync::DynSync; use rustc_serialize::{Encodable, Encoder}; diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index e637ced7139..2b1212a5eb5 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -26,52 +26,55 @@ pub use intrinsic::IntrinsicDef; use rustc_ast::expand::StrippedCfgItem; use rustc_ast::node_id::NodeMap; -pub use rustc_ast_ir::{try_visit, Movability, Mutability}; +pub use rustc_ast_ir::{Movability, Mutability, try_visit}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::steal::Steal; use rustc_data_structures::tagged_ptr::CopyTaggedPtr; use rustc_errors::{Diag, ErrorGuaranteed, StashKey}; +use rustc_hir::LangItem; use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap}; -use rustc_hir::LangItem; use rustc_index::IndexVec; use rustc_macros::{ - extension, Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, - TypeVisitable, + Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable, + extension, }; use rustc_query_system::ich::StableHashingContext; use rustc_serialize::{Decodable, Encodable}; use rustc_session::lint::LintBuffer; pub use rustc_session::lint::RegisteredTools; use rustc_span::hygiene::MacroKind; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use rustc_span::{ExpnId, ExpnKind, Span}; use rustc_target::abi::{Align, FieldIdx, Integer, IntegerType, VariantIdx}; pub use rustc_target::abi::{ReprFlags, ReprOptions}; -pub use rustc_type_ir::relate::VarianceDiagInfo; pub use rustc_type_ir::ConstKind::{ Bound as BoundCt, Error as ErrorCt, Expr as ExprCt, Infer as InferCt, Param as ParamCt, Placeholder as PlaceholderCt, Unevaluated, Value, }; +pub use rustc_type_ir::relate::VarianceDiagInfo; pub use rustc_type_ir::*; use tracing::{debug, instrument}; pub use vtable::*; use {rustc_ast as ast, rustc_attr as attr, rustc_hir as hir}; +pub use self::AssocItemContainer::*; +pub use self::BorrowKind::*; +pub use self::IntVarValue::*; pub use self::closure::{ - analyze_coroutine_closure_captures, is_ancestor_or_same_capture, place_to_string_for_capture, - BorrowKind, CaptureInfo, CapturedPlace, ClosureTypeInfo, MinCaptureInformationMap, - MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId, UpvarPath, - CAPTURE_STRUCT_LOCAL, + BorrowKind, CAPTURE_STRUCT_LOCAL, CaptureInfo, CapturedPlace, ClosureTypeInfo, + MinCaptureInformationMap, MinCaptureList, RootVariableMinCaptureList, UpvarCapture, UpvarId, + UpvarPath, analyze_coroutine_closure_captures, is_ancestor_or_same_capture, + place_to_string_for_capture, }; pub use self::consts::{ Const, ConstInt, ConstKind, Expr, ExprKind, FeedConstTy, ScalarInt, UnevaluatedConst, ValTree, }; pub use self::context::{ - tls, CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, - TyCtxt, TyCtxtFeed, + CtxtInterners, CurrentGcx, DeducedParamAttrs, Feed, FreeRegionInfo, GlobalCtxt, Lift, TyCtxt, + TyCtxtFeed, tls, }; pub use self::fold::{FallibleTypeFolder, TypeFoldable, TypeFolder, TypeSuperFoldable}; pub use self::instance::{Instance, InstanceKind, ReifyReason, ShortInstance, UnusedGenericParams}; @@ -104,9 +107,6 @@ TypeckResults, UserType, UserTypeAnnotationIndex, }; pub use self::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor}; -pub use self::AssocItemContainer::*; -pub use self::BorrowKind::*; -pub use self::IntVarValue::*; use crate::error::{OpaqueHiddenTypeMismatch, TypeMismatchReason}; use crate::metadata::ModChild; use crate::middle::privacy::EffectiveVisibilities; diff --git a/compiler/rustc_middle/src/ty/opaque_types.rs b/compiler/rustc_middle/src/ty/opaque_types.rs index d3f44326c27..cf789807bb0 100644 --- a/compiler/rustc_middle/src/ty/opaque_types.rs +++ b/compiler/rustc_middle/src/ty/opaque_types.rs @@ -1,6 +1,6 @@ use rustc_data_structures::fx::FxHashMap; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; use tracing::{debug, instrument, trace}; use crate::error::ConstNotUsedTraitAlias; diff --git a/compiler/rustc_middle/src/ty/predicate.rs b/compiler/rustc_middle/src/ty/predicate.rs index 8e72505b862..534a8c99c5a 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -3,7 +3,7 @@ use rustc_data_structures::captures::Captures; use rustc_data_structures::intern::Interned; use rustc_hir::def_id::DefId; -use rustc_macros::{extension, HashStable}; +use rustc_macros::{HashStable, extension}; use rustc_type_ir as ir; use tracing::instrument; diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 988516d100f..5b4ee2791f8 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -3,23 +3,23 @@ use std::iter; use std::ops::{Deref, DerefMut}; -use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::Float; +use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_data_structures::unord::UnordMap; use rustc_hir as hir; -use rustc_hir::def::{self, CtorKind, DefKind, Namespace}; -use rustc_hir::def_id::{DefIdMap, DefIdSet, ModDefId, CRATE_DEF_ID, LOCAL_CRATE}; -use rustc_hir::definitions::{DefKey, DefPathDataName}; use rustc_hir::LangItem; -use rustc_macros::{extension, Lift}; -use rustc_session::cstore::{ExternCrate, ExternCrateSource}; +use rustc_hir::def::{self, CtorKind, DefKind, Namespace}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefIdMap, DefIdSet, LOCAL_CRATE, ModDefId}; +use rustc_hir::definitions::{DefKey, DefPathDataName}; +use rustc_macros::{Lift, extension}; use rustc_session::Limit; -use rustc_span::symbol::{kw, Ident, Symbol}; +use rustc_session::cstore::{ExternCrate, ExternCrateSource}; use rustc_span::FileNameDisplayPreference; +use rustc_span::symbol::{Ident, Symbol, kw}; use rustc_target::abi::Size; use rustc_target::spec::abi::Abi; -use rustc_type_ir::{elaborate, Upcast as _}; +use rustc_type_ir::{Upcast as _, elaborate}; use smallvec::SmallVec; // `pretty` is a separate module only for organization. diff --git a/compiler/rustc_middle/src/ty/region.rs b/compiler/rustc_middle/src/ty/region.rs index 44956d5b0a6..be4772e888f 100644 --- a/compiler/rustc_middle/src/ty/region.rs +++ b/compiler/rustc_middle/src/ty/region.rs @@ -4,8 +4,8 @@ use rustc_errors::MultiSpan; use rustc_hir::def_id::DefId; use rustc_macros::{HashStable, TyDecodable, TyEncodable}; -use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_span::{ErrorGuaranteed, DUMMY_SP}; +use rustc_span::symbol::{Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed}; use rustc_type_ir::RegionKind as IrRegionKind; pub use rustc_type_ir::RegionVid; use tracing::debug; diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 80b33c2cda9..cd9ff9b60d8 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -16,7 +16,7 @@ use super::{GenericArg, GenericArgKind, Pattern, Region}; use crate::mir::interpret; use crate::ty::fold::{FallibleTypeFolder, TypeFoldable, TypeSuperFoldable}; -use crate::ty::print::{with_no_trimmed_paths, FmtPrinter, Printer}; +use crate::ty::print::{FmtPrinter, Printer, with_no_trimmed_paths}; use crate::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor}; use crate::ty::{self, InferConst, Lift, Term, TermKind, Ty, TyCtxt}; diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 44309697ba9..db9978a7f53 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -11,15 +11,15 @@ use rustc_data_structures::captures::Captures; use rustc_errors::{ErrorGuaranteed, MultiSpan}; use rustc_hir as hir; -use rustc_hir::def_id::DefId; use rustc_hir::LangItem; -use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable, TypeFoldable}; -use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{Span, DUMMY_SP}; -use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; +use rustc_hir::def_id::DefId; +use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, extension}; +use rustc_span::symbol::{Symbol, sym}; +use rustc_span::{DUMMY_SP, Span}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; use rustc_target::spec::abi; -use rustc_type_ir::visit::TypeVisitableExt; use rustc_type_ir::TyKind::*; +use rustc_type_ir::visit::TypeVisitableExt; use rustc_type_ir::{self as ir, BoundVar, CollectAndApply, DynKind}; use ty::util::{AsyncDropGlueMorphology, IntTypeExt}; diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index a92bdb2eae0..17280c3d047 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -23,8 +23,8 @@ use crate::infer::canonical::Canonical; use crate::traits::ObligationCause; use crate::ty::{ - self, tls, BoundVar, CanonicalPolyFnSig, ClosureSizeProfileData, GenericArgKind, GenericArgs, - GenericArgsRef, Ty, UserArgs, + self, BoundVar, CanonicalPolyFnSig, ClosureSizeProfileData, GenericArgKind, GenericArgs, + GenericArgsRef, Ty, UserArgs, tls, }; #[derive(TyEncodable, TyDecodable, Debug, HashStable)] diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index a0262f12cb5..321b51289fb 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -11,12 +11,12 @@ use rustc_hir::def::{CtorOf, DefKind, Res}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_index::bit_set::GrowableBitSet; -use rustc_macros::{extension, HashStable, TyDecodable, TyEncodable}; +use rustc_macros::{HashStable, TyDecodable, TyEncodable, extension}; use rustc_session::Limit; use rustc_span::sym; use rustc_target::abi::{Float, Integer, IntegerType, Size}; use rustc_target::spec::abi::Abi; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument, trace}; use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; diff --git a/compiler/rustc_middle/src/ty/vtable.rs b/compiler/rustc_middle/src/ty/vtable.rs index 951112dfe85..963fa12a8c7 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -3,7 +3,7 @@ use rustc_ast::Mutability; use rustc_macros::HashStable; -use crate::mir::interpret::{alloc_range, AllocId, Allocation, Pointer, Scalar, CTFE_ALLOC_SALT}; +use crate::mir::interpret::{AllocId, Allocation, CTFE_ALLOC_SALT, Pointer, Scalar, alloc_range}; use crate::ty::{self, Instance, PolyTraitRef, Ty, TyCtxt}; #[derive(Clone, Copy, PartialEq, HashStable)] diff --git a/compiler/rustc_middle/src/ty/walk.rs b/compiler/rustc_middle/src/ty/walk.rs index abd6df17514..a93a146ec7c 100644 --- a/compiler/rustc_middle/src/ty/walk.rs +++ b/compiler/rustc_middle/src/ty/walk.rs @@ -2,7 +2,7 @@ //! WARNING: this does not keep track of the region depth. use rustc_data_structures::sso::SsoHashSet; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use tracing::debug; use crate::ty::{self, GenericArg, GenericArgKind, Ty}; diff --git a/compiler/rustc_middle/src/util/bug.rs b/compiler/rustc_middle/src/util/bug.rs index 32f5251568f..b99336c2c85 100644 --- a/compiler/rustc_middle/src/util/bug.rs +++ b/compiler/rustc_middle/src/util/bug.rs @@ -1,12 +1,12 @@ // These functions are used by macro expansion for bug! and span_bug! use std::fmt; -use std::panic::{panic_any, Location}; +use std::panic::{Location, panic_any}; use rustc_errors::MultiSpan; use rustc_span::Span; -use crate::ty::{tls, TyCtxt}; +use crate::ty::{TyCtxt, tls}; #[cold] #[inline(never)] diff --git a/compiler/rustc_middle/src/util/call_kind.rs b/compiler/rustc_middle/src/util/call_kind.rs index 75ae4e11fa9..fe30cbfae4e 100644 --- a/compiler/rustc_middle/src/util/call_kind.rs +++ b/compiler/rustc_middle/src/util/call_kind.rs @@ -3,9 +3,9 @@ //! context. use rustc_hir::def_id::DefId; -use rustc_hir::{lang_items, LangItem}; +use rustc_hir::{LangItem, lang_items}; use rustc_span::symbol::Ident; -use rustc_span::{sym, DesugaringKind, Span}; +use rustc_span::{DesugaringKind, Span, sym}; use tracing::debug; use crate::ty::{AssocItemContainer, GenericArgsRef, Instance, ParamEnv, Ty, TyCtxt}; diff --git a/compiler/rustc_middle/src/util/mod.rs b/compiler/rustc_middle/src/util/mod.rs index 8c95988477d..8dafc422644 100644 --- a/compiler/rustc_middle/src/util/mod.rs +++ b/compiler/rustc_middle/src/util/mod.rs @@ -3,7 +3,7 @@ pub mod common; pub mod find_self_call; -pub use call_kind::{call_kind, CallDesugaringKind, CallKind}; +pub use call_kind::{CallDesugaringKind, CallKind, call_kind}; pub use find_self_call::find_self_call; #[derive(Default, Copy, Clone)] diff --git a/compiler/rustc_middle/src/values.rs b/compiler/rustc_middle/src/values.rs index 6163fa2932d..c98d88e22d4 100644 --- a/compiler/rustc_middle/src/values.rs +++ b/compiler/rustc_middle/src/values.rs @@ -4,12 +4,12 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::codes::*; -use rustc_errors::{pluralize, struct_span_code_err, Applicability, MultiSpan}; +use rustc_errors::{Applicability, MultiSpan, pluralize, struct_span_code_err}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_middle::ty::{self, Representability, Ty, TyCtxt}; -use rustc_query_system::query::{report_cycle, CycleError}; use rustc_query_system::Value; +use rustc_query_system::query::{CycleError, report_cycle}; use rustc_span::def_id::LocalDefId; use rustc_span::{ErrorGuaranteed, Span}; diff --git a/compiler/rustc_mir_build/src/build/block.rs b/compiler/rustc_mir_build/src/build/block.rs index 7afa628843f..89e64015bc4 100644 --- a/compiler/rustc_mir_build/src/build/block.rs +++ b/compiler/rustc_mir_build/src/build/block.rs @@ -5,8 +5,8 @@ use rustc_span::Span; use tracing::debug; -use crate::build::matches::{DeclareLetBindings, EmitStorageLive, ScheduleDrops}; use crate::build::ForGuard::OutsideGuard; +use crate::build::matches::{DeclareLetBindings, EmitStorageLive, ScheduleDrops}; use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder}; impl<'a, 'tcx> Builder<'a, 'tcx> { diff --git a/compiler/rustc_mir_build/src/build/cfg.rs b/compiler/rustc_mir_build/src/build/cfg.rs index e80b654309e..9c5ee5b0996 100644 --- a/compiler/rustc_mir_build/src/build/cfg.rs +++ b/compiler/rustc_mir_build/src/build/cfg.rs @@ -40,10 +40,10 @@ pub(crate) fn push_assign( 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/build/custom/mod.rs b/compiler/rustc_mir_build/src/build/custom/mod.rs index 1e1fa21b5f3..4815db47b16 100644 --- a/compiler/rustc_mir_build/src/build/custom/mod.rs +++ b/compiler/rustc_mir_build/src/build/custom/mod.rs @@ -19,8 +19,8 @@ use rustc_ast::Attribute; use rustc_data_structures::fx::FxHashMap; -use rustc_hir::def_id::DefId; use rustc_hir::HirId; +use rustc_hir::def_id::DefId; use rustc_index::{IndexSlice, IndexVec}; use rustc_middle::mir::*; use rustc_middle::span_bug; diff --git a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs index 0cbd2da10db..9e3af891052 100644 --- a/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs +++ b/compiler/rustc_mir_build/src/build/custom/parse/instruction.rs @@ -4,11 +4,11 @@ use rustc_middle::thir::*; use rustc_middle::ty; use rustc_middle::ty::cast::mir_cast_kind; -use rustc_span::source_map::Spanned; use rustc_span::Span; +use rustc_span::source_map::Spanned; use rustc_target::abi::{FieldIdx, VariantIdx}; -use super::{parse_by_kind, PResult, ParseCtxt}; +use super::{PResult, ParseCtxt, parse_by_kind}; use crate::build::custom::ParseError; use crate::build::expr::as_constant::as_constant_inner; diff --git a/compiler/rustc_mir_build/src/build/expr/as_constant.rs b/compiler/rustc_mir_build/src/build/expr/as_constant.rs index 4f1166f9111..ae164cf7605 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_constant.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_constant.rs @@ -3,7 +3,7 @@ use rustc_ast as ast; use rustc_hir::LangItem; use rustc_middle::mir::interpret::{ - Allocation, LitToConstError, LitToConstInput, Scalar, CTFE_ALLOC_SALT, + Allocation, CTFE_ALLOC_SALT, LitToConstError, LitToConstInput, Scalar, }; use rustc_middle::mir::*; use rustc_middle::thir::*; @@ -14,7 +14,7 @@ use rustc_target::abi::Size; use tracing::{instrument, trace}; -use crate::build::{parse_float_into_constval, Builder}; +use crate::build::{Builder, parse_float_into_constval}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Compile `expr`, yielding a compile-time constant. Assumes that diff --git a/compiler/rustc_mir_build/src/build/expr/as_place.rs b/compiler/rustc_mir_build/src/build/expr/as_place.rs index 07784982631..2084bcae7b7 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_place.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_place.rs @@ -12,11 +12,11 @@ use rustc_middle::ty::{self, AdtDef, CanonicalUserTypeAnnotation, Ty, Variance}; use rustc_middle::{bug, span_bug}; use rustc_span::Span; -use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; use tracing::{debug, instrument, trace}; -use crate::build::expr::category::Category; use crate::build::ForGuard::{OutsideGuard, RefWithinGuard}; +use crate::build::expr::category::Category; use crate::build::{BlockAnd, BlockAndExtension, Builder, Capture, CaptureMap}; /// The "outermost" place that holds this value. @@ -483,19 +483,16 @@ fn expr_as_place( }); let place = place_builder.to_place(this); - this.cfg.push( - block, - Statement { - source_info, - kind: StatementKind::AscribeUserType( - Box::new(( - place, - UserTypeProjection { base: annotation_index, projs: vec![] }, - )), - Variance::Invariant, - ), - }, - ); + this.cfg.push(block, Statement { + source_info, + kind: StatementKind::AscribeUserType( + Box::new((place, UserTypeProjection { + base: annotation_index, + projs: vec![], + })), + Variance::Invariant, + ), + }); } block.and(place_builder) } @@ -511,19 +508,16 @@ fn expr_as_place( user_ty: user_ty.clone(), inferred_ty: expr.ty, }); - this.cfg.push( - block, - Statement { - 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, + 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/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs index 0c9571da3cf..ffedee8a1e8 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs @@ -7,12 +7,12 @@ use rustc_middle::mir::interpret::Scalar; use rustc_middle::mir::*; use rustc_middle::thir::*; -use rustc_middle::ty::cast::{mir_cast_kind, CastTy}; +use rustc_middle::ty::cast::{CastTy, mir_cast_kind}; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, Ty, UpvarArgs}; use rustc_span::source_map::Spanned; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi::{Abi, FieldIdx, Primitive}; use tracing::debug; @@ -57,7 +57,7 @@ pub(crate) fn as_rvalue( this.in_scope(region_scope, lint_level, |this| this.as_rvalue(block, scope, value)) } ExprKind::Repeat { value, count } => { - if Some(0) == count.try_eval_target_usize(this.tcx, this.param_env) { + if Some(0) == count.try_to_target_usize(this.tcx) { this.build_zero_repeat(block, value, scope, source_info) } else { let value_operand = unpack!( @@ -147,23 +147,19 @@ pub(crate) fn as_rvalue( ); 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 +167,10 @@ pub(crate) fn as_rvalue( // 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 { // schedule a shallow free of that memory, lest we unwind: this.schedule_drop_storage_and_value(expr_span, scope, result); @@ -268,15 +264,12 @@ pub(crate) fn as_rvalue( ); 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) @@ -721,16 +714,12 @@ fn build_zero_repeat( ); 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/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index 1c805ed20cc..86fe447f399 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -221,14 +221,10 @@ pub(crate) fn expr_into_dest( 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 @@ -259,30 +255,26 @@ pub(crate) fn expr_into_dest( 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.param_env) - .then_some(success), - call_source: if from_hir_call { - CallSource::Normal - } else { - CallSource::OverloadedOperator - }, - 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.param_env) + .then_some(success), + call_source: if from_hir_call { + CallSource::Normal + } else { + CallSource::OverloadedOperator }, - ); + fn_span, + }); this.diverge_from(block); success.unit() } @@ -469,11 +461,9 @@ pub(crate) fn expr_into_dest( 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 } } @@ -484,22 +474,18 @@ pub(crate) fn expr_into_dest( this.cfg.push_assign_unit(block, source_info, destination, this.tcx); } - this.cfg.terminate( - block, - source_info, - TerminatorKind::InlineAsm { - 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 { + 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); } @@ -562,11 +548,12 @@ pub(crate) fn expr_into_dest( ) ); 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/build/expr/stmt.rs b/compiler/rustc_mir_build/src/build/expr/stmt.rs index b38f0a41e5d..76034c03b4b 100644 --- a/compiler/rustc_mir_build/src/build/expr/stmt.rs +++ b/compiler/rustc_mir_build/src/build/expr/stmt.rs @@ -123,11 +123,11 @@ pub(crate) fn stmt_expr( 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/build/matches/match_pair.rs b/compiler/rustc_mir_build/src/build/matches/match_pair.rs index ab2bfcbca3a..6df50057ee8 100644 --- a/compiler/rustc_mir_build/src/build/matches/match_pair.rs +++ b/compiler/rustc_mir_build/src/build/matches/match_pair.rs @@ -2,9 +2,9 @@ use rustc_middle::thir::{self, *}; use rustc_middle::ty::{self, Ty, TypeVisitableExt}; +use crate::build::Builder; use crate::build::expr::as_place::{PlaceBase, PlaceBuilder}; use crate::build::matches::{FlatPat, MatchPairTree, TestCase}; -use crate::build::Builder; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Builds and returns [`MatchPairTree`] subtrees, one for each pattern in @@ -42,7 +42,12 @@ fn prefix_slice_suffix<'pat>( let tcx = self.tcx; let (min_length, exact_size) = if let Some(place_resolved) = place.try_to_place(self) { match place_resolved.ty(&self.local_decls, tcx).ty.kind() { - ty::Array(_, length) => (length.eval_target_usize(tcx, self.param_env), true), + ty::Array(_, length) => ( + length + .try_to_target_usize(tcx) + .expect("expected len of array pat to be definite"), + true, + ), _ => ((prefix.len() + suffix.len()).try_into().unwrap(), false), } } else { @@ -162,13 +167,10 @@ pub(in crate::build) fn for_pattern( 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::TypeOf( def.to_def_id(), diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index cae4aa7bad3..51ead570205 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -18,9 +18,9 @@ use rustc_target::abi::VariantIdx; use tracing::{debug, instrument}; +use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard}; use crate::build::expr::as_place::PlaceBuilder; use crate::build::scope::DropKind; -use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard}; use crate::build::{ BlockAnd, BlockAndExtension, Builder, GuardFrame, GuardFrameLocal, LocalsForNode, }; @@ -104,11 +104,11 @@ pub(crate) fn then_else_break( 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,24 +134,16 @@ fn then_else_break_inner( 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 - }, - ) - }); - let rhs_success_block = this - .then_else_break_inner( - failure_block, - rhs, - ThenElseArgs { + 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 + }) .into_block(); // Make the LHS and RHS success arms converge to a common block. @@ -178,14 +170,10 @@ fn then_else_break_inner( 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() @@ -638,30 +626,27 @@ pub(super) fn expr_into_pattern( 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() @@ -2559,19 +2544,13 @@ fn ascribe_types( 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/build/matches/simplify.rs b/compiler/rustc_mir_build/src/build/matches/simplify.rs index 04cf81d54e9..5b402604395 100644 --- a/compiler/rustc_mir_build/src/build/matches/simplify.rs +++ b/compiler/rustc_mir_build/src/build/matches/simplify.rs @@ -16,8 +16,8 @@ use tracing::{debug, instrument}; -use crate::build::matches::{MatchPairTree, PatternExtraData, TestCase}; use crate::build::Builder; +use crate::build::matches::{MatchPairTree, PatternExtraData, TestCase}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Simplify a list of match pairs so they all require a test. Stores relevant bindings and diff --git a/compiler/rustc_mir_build/src/build/matches/test.rs b/compiler/rustc_mir_build/src/build/matches/test.rs index 7af1ede24a4..63873aad02a 100644 --- a/compiler/rustc_mir_build/src/build/matches/test.rs +++ b/compiler/rustc_mir_build/src/build/matches/test.rs @@ -16,12 +16,12 @@ use rustc_middle::{bug, span_bug}; use rustc_span::def_id::DefId; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Symbol, sym}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; -use crate::build::matches::{Candidate, MatchPairTree, Test, TestBranch, TestCase, TestKind}; use crate::build::Builder; +use crate::build::matches::{Candidate, MatchPairTree, Test, TestBranch, TestCase, TestKind}; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Identifies what test is needed to decide if `match_pair` is applicable. @@ -322,23 +322,15 @@ pub(super) fn call_deref( ); // `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 @@ -466,33 +458,29 @@ fn non_scalar_compare( 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: Operand::Copy(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, - }, - ); + const_: method, + })), + args: [Spanned { node: Operand::Copy(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, + }); self.diverge_from(block); // check the result diff --git a/compiler/rustc_mir_build/src/build/matches/util.rs b/compiler/rustc_mir_build/src/build/matches/util.rs index 8491b5fe380..555684ded81 100644 --- a/compiler/rustc_mir_build/src/build/matches/util.rs +++ b/compiler/rustc_mir_build/src/build/matches/util.rs @@ -4,9 +4,9 @@ use rustc_span::Span; use tracing::debug; +use crate::build::Builder; use crate::build::expr::as_place::PlaceBase; use crate::build::matches::{Binding, Candidate, FlatPat, MatchPairTree, TestCase}; -use crate::build::Builder; impl<'a, 'tcx> Builder<'a, 'tcx> { /// Creates a false edge to `imaginary_target` and a real edge to @@ -20,11 +20,10 @@ pub(crate) fn false_edges( 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/build/misc.rs b/compiler/rustc_mir_build/src/build/misc.rs index 26906973ca8..53cb99d44e8 100644 --- a/compiler/rustc_mir_build/src/build/misc.rs +++ b/compiler/rustc_mir_build/src/build/misc.rs @@ -45,16 +45,11 @@ pub(crate) fn push_usize( ) -> 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/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index b98deda8fd0..8c20d2e0d3a 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -1,6 +1,6 @@ use itertools::Itertools; -use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::Float; +use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_ast::attr; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sorted_map::SortedIndexMultiMap; diff --git a/compiler/rustc_mir_build/src/build/scope.rs b/compiler/rustc_mir_build/src/build/scope.rs index 693037d03e0..dfc82f705a8 100644 --- a/compiler/rustc_mir_build/src/build/scope.rs +++ b/compiler/rustc_mir_build/src/build/scope.rs @@ -92,7 +92,7 @@ use rustc_middle::{bug, span_bug}; use rustc_session::lint::Level; use rustc_span::source_map::Spanned; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; use crate::build::{BlockAnd, BlockAndExtension, BlockFrame, Builder, CFG}; @@ -510,16 +510,12 @@ pub(crate) fn in_breakable_scope( (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() } } @@ -806,25 +802,21 @@ pub(crate) fn break_for_tail_call( 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::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), + }); } } } @@ -1283,16 +1275,12 @@ pub(crate) fn build_drop_and_replace( 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() @@ -1312,17 +1300,13 @@ pub(crate) fn assert( 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 @@ -1397,16 +1381,12 @@ 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::Storage => { diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 4fe984b961e..8512763a595 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -12,11 +12,11 @@ use rustc_middle::thir::*; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt}; -use rustc_session::lint::builtin::{DEPRECATED_SAFE_2024, UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE}; use rustc_session::lint::Level; +use rustc_session::lint::builtin::{DEPRECATED_SAFE_2024, UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE}; use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::symbol::Symbol; -use rustc_span::{sym, Span}; +use rustc_span::{Span, sym}; use crate::build::ExprCategory; use crate::errors::*; @@ -499,10 +499,11 @@ fn visit_expr(&mut self, expr: &'a Expr<'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, + }); } } } @@ -1052,11 +1053,9 @@ 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/errors.rs b/compiler/rustc_mir_build/src/errors.rs index 411e9420914..42be7f9402e 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -7,8 +7,8 @@ use rustc_middle::ty::{self, Ty}; use rustc_pattern_analysis::errors::Uncovered; use rustc_pattern_analysis::rustc::RustcPatCtxt; -use rustc_span::symbol::Symbol; use rustc_span::Span; +use rustc_span::symbol::Symbol; use crate::fluent_generated as fluent; diff --git a/compiler/rustc_mir_build/src/lints.rs b/compiler/rustc_mir_build/src/lints.rs index 80e91811b1c..cb9a4e2604e 100644 --- a/compiler/rustc_mir_build/src/lints.rs +++ b/compiler/rustc_mir_build/src/lints.rs @@ -54,12 +54,10 @@ 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_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 3f730b5d183..55236933922 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -17,13 +17,13 @@ UserType, }; use rustc_middle::{bug, span_bug}; -use rustc_span::{sym, Span}; -use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; +use rustc_span::{Span, sym}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx}; use tracing::{debug, info, instrument, trace}; use crate::errors; -use crate::thir::cx::region::Scope; use crate::thir::cx::Cx; +use crate::thir::cx::region::Scope; use crate::thir::util::UserAnnotatedTyHelpers; impl<'tcx> Cx<'tcx> { diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index 5b5f97cb514..377931e3be7 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -5,10 +5,10 @@ use rustc_data_structures::steal::Steal; use rustc_errors::ErrorGuaranteed; use rustc_hir as hir; +use rustc_hir::HirId; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::lang_items::LangItem; -use rustc_hir::HirId; use rustc_middle::bug; use rustc_middle::middle::region; use rustc_middle::thir::*; @@ -182,9 +182,11 @@ fn explicit_params<'a>( 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_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 3fde6466d8c..ae77bce6bb1 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -3,7 +3,7 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, Applicability, ErrorGuaranteed, MultiSpan}; +use rustc_errors::{Applicability, ErrorGuaranteed, MultiSpan, struct_span_code_err}; use rustc_hir::def::*; use rustc_hir::def_id::LocalDefId; use rustc_hir::{self as hir, BindingMode, ByRef, HirId}; @@ -22,7 +22,7 @@ BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS, }; use rustc_span::hygiene::DesugaringKind; -use rustc_span::{sym, Span}; +use rustc_span::{Span, sym}; use tracing::instrument; use crate::errors::*; diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 53393046610..2c3611afca9 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -10,8 +10,8 @@ use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, ValTree}; use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; -use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use rustc_trait_selection::traits::ObligationCause; +use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use tracing::{debug, instrument, trace}; use super::PatCtxt; diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index d78e1f5da09..04e921ecc2e 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -441,7 +441,9 @@ fn slice_or_array_pattern( ty::Slice(..) => PatKind::Slice { prefix, slice, suffix }, // Fixed-length array, `[T; len]`. ty::Array(_, len) => { - let len = len.eval_target_usize(self.tcx, self.param_env); + let len = len + .try_to_target_usize(self.tcx) + .expect("expected len of array pat to be definite"); assert!(len >= prefix.len() as u64 + suffix.len() as u64); PatKind::Array { prefix, slice, suffix } } diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index c4d06cbb1b0..f2541c37167 100644 --- a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs +++ b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs @@ -8,9 +8,9 @@ use rustc_middle::traits::Reveal; use rustc_middle::ty::util::IntTypeExt; use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt}; -use rustc_span::source_map::Spanned; use rustc_span::DUMMY_SP; -use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; +use rustc_span::source_map::Spanned; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; use tracing::{debug, instrument}; /// The value of an inserted drop flag. @@ -233,15 +233,12 @@ pub fn elaborate_drop(&mut self, bb: BasicBlock) { .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); @@ -732,15 +729,12 @@ fn drop_loop( }; 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/engine.rs b/compiler/rustc_mir_dataflow/src/framework/engine.rs index 54206501d9f..947bdf860b5 100644 --- a/compiler/rustc_mir_dataflow/src/framework/engine.rs +++ b/compiler/rustc_mir_dataflow/src/framework/engine.rs @@ -7,17 +7,17 @@ use rustc_hir::def_id::DefId; use rustc_index::{Idx, IndexVec}; use rustc_middle::bug; -use rustc_middle::mir::{self, create_dump_file, dump_enabled, traversal, BasicBlock}; -use rustc_middle::ty::print::with_no_trimmed_paths; +use rustc_middle::mir::{self, BasicBlock, create_dump_file, dump_enabled, traversal}; use rustc_middle::ty::TyCtxt; -use rustc_span::symbol::{sym, Symbol}; +use rustc_middle::ty::print::with_no_trimmed_paths; +use rustc_span::symbol::{Symbol, sym}; use tracing::{debug, error}; use {rustc_ast as ast, rustc_graphviz as dot}; use super::fmt::DebugWithContext; use super::{ - graphviz, visit_results, Analysis, AnalysisDomain, Direction, GenKill, GenKillAnalysis, - GenKillSet, JoinSemiLattice, ResultsCursor, ResultsVisitor, + Analysis, AnalysisDomain, Direction, GenKill, GenKillAnalysis, GenKillSet, JoinSemiLattice, + ResultsCursor, ResultsVisitor, graphviz, visit_results, }; use crate::errors::{ DuplicateValuesFor, PathMustEndInFilename, RequiresAnArgument, UnknownFormatter, diff --git a/compiler/rustc_mir_dataflow/src/framework/fmt.rs b/compiler/rustc_mir_dataflow/src/framework/fmt.rs index 5e4f36e4ae3..ed540cd148c 100644 --- a/compiler/rustc_mir_dataflow/src/framework/fmt.rs +++ b/compiler/rustc_mir_dataflow/src/framework/fmt.rs @@ -3,8 +3,8 @@ use std::fmt; -use rustc_index::bit_set::{BitSet, ChunkedBitSet, HybridBitSet}; use rustc_index::Idx; +use rustc_index::bit_set::{BitSet, ChunkedBitSet, HybridBitSet}; use super::lattice::MaybeReachable; diff --git a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs index e72dca2c834..96a70f4fa5b 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -8,7 +8,7 @@ use regex::Regex; use rustc_graphviz as dot; use rustc_index::bit_set::BitSet; -use rustc_middle::mir::{self, graphviz_safe_def_name, BasicBlock, Body, Location}; +use rustc_middle::mir::{self, BasicBlock, Body, Location, graphviz_safe_def_name}; use super::fmt::{DebugDiffWithAdapter, DebugWithAdapter, DebugWithContext}; use super::{Analysis, CallReturnPlaces, Direction, Results, ResultsCursor, ResultsVisitor}; @@ -502,10 +502,10 @@ fn write_row_with_full_state( 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/mod.rs b/compiler/rustc_mir_dataflow/src/framework/mod.rs index 6da3a20dc02..d0472e35fe0 100644 --- a/compiler/rustc_mir_dataflow/src/framework/mod.rs +++ b/compiler/rustc_mir_dataflow/src/framework/mod.rs @@ -32,8 +32,8 @@ use std::cmp::Ordering; -use rustc_index::bit_set::{BitSet, ChunkedBitSet, HybridBitSet}; use rustc_index::Idx; +use rustc_index::bit_set::{BitSet, ChunkedBitSet, HybridBitSet}; use rustc_middle::mir::{self, BasicBlock, CallReturnPlaces, Location, TerminatorEdges}; use rustc_middle::ty::TyCtxt; @@ -49,7 +49,7 @@ pub use self::direction::{Backward, Direction, Forward}; pub use self::engine::{Engine, Results}; pub use self::lattice::{JoinSemiLattice, MaybeReachable}; -pub use self::visitor::{visit_results, ResultsVisitable, ResultsVisitor}; +pub use self::visitor::{ResultsVisitable, ResultsVisitor, visit_results}; /// Analysis domains are all bitsets of various kinds. This trait holds /// operations needed by all of them. diff --git a/compiler/rustc_mir_dataflow/src/framework/tests.rs b/compiler/rustc_mir_dataflow/src/framework/tests.rs index 52db931b68e..1861f4cffc7 100644 --- a/compiler/rustc_mir_dataflow/src/framework/tests.rs +++ b/compiler/rustc_mir_dataflow/src/framework/tests.rs @@ -30,32 +30,26 @@ 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_dataflow/src/impls/initialized.rs b/compiler/rustc_mir_dataflow/src/impls/initialized.rs index a88927427ba..25e8726cf61 100644 --- a/compiler/rustc_mir_dataflow/src/impls/initialized.rs +++ b/compiler/rustc_mir_dataflow/src/impls/initialized.rs @@ -1,7 +1,7 @@ use std::assert_matches::assert_matches; -use rustc_index::bit_set::{BitSet, ChunkedBitSet}; use rustc_index::Idx; +use rustc_index::bit_set::{BitSet, ChunkedBitSet}; use rustc_middle::bug; use rustc_middle::mir::{self, Body, CallReturnPlaces, Location, TerminatorEdges}; use rustc_middle::ty::{self, TyCtxt}; @@ -11,9 +11,9 @@ use crate::framework::SwitchIntEdgeEffects; use crate::move_paths::{HasMoveData, InitIndex, InitKind, LookupResult, MoveData, MovePathIndex}; use crate::{ - drop_flag_effects, drop_flag_effects_for_function_entry, drop_flag_effects_for_location, - lattice, on_all_children_bits, on_lookup_result_bits, AnalysisDomain, GenKill, GenKillAnalysis, - MaybeReachable, + AnalysisDomain, GenKill, GenKillAnalysis, MaybeReachable, drop_flag_effects, + drop_flag_effects_for_function_entry, drop_flag_effects_for_location, lattice, + on_all_children_bits, on_lookup_result_bits, }; /// `MaybeInitializedPlaces` tracks all places that might be diff --git a/compiler/rustc_mir_dataflow/src/impls/mod.rs b/compiler/rustc_mir_dataflow/src/impls/mod.rs index f283660e1e7..9b5bfa9bfa0 100644 --- a/compiler/rustc_mir_dataflow/src/impls/mod.rs +++ b/compiler/rustc_mir_dataflow/src/impls/mod.rs @@ -7,7 +7,7 @@ mod liveness; mod storage_liveness; -pub use self::borrowed_locals::{borrowed_locals, MaybeBorrowedLocals}; +pub use self::borrowed_locals::{MaybeBorrowedLocals, borrowed_locals}; pub use self::initialized::{ DefinitelyInitializedPlaces, EverInitializedPlaces, MaybeInitializedPlaces, MaybeUninitializedPlaces, diff --git a/compiler/rustc_mir_dataflow/src/lib.rs b/compiler/rustc_mir_dataflow/src/lib.rs index 9385b52103f..cb7c7edc413 100644 --- a/compiler/rustc_mir_dataflow/src/lib.rs +++ b/compiler/rustc_mir_dataflow/src/lib.rs @@ -17,9 +17,9 @@ move_path_children_matching, on_all_children_bits, on_lookup_result_bits, }; pub use self::framework::{ - fmt, graphviz, lattice, visit_results, Analysis, AnalysisDomain, Backward, Direction, Engine, - Forward, GenKill, GenKillAnalysis, JoinSemiLattice, MaybeReachable, Results, ResultsCursor, - ResultsVisitable, ResultsVisitor, SwitchIntEdgeEffects, + Analysis, AnalysisDomain, Backward, Direction, Engine, Forward, GenKill, GenKillAnalysis, + JoinSemiLattice, MaybeReachable, Results, ResultsCursor, ResultsVisitable, ResultsVisitor, + SwitchIntEdgeEffects, fmt, graphviz, lattice, visit_results, }; use self::move_paths::MoveData; diff --git a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs index 87ea7299238..3c8be2f73e1 100644 --- a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs +++ b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs @@ -5,7 +5,7 @@ use rustc_middle::mir::*; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use tracing::debug; use super::abs_domain::Lift; diff --git a/compiler/rustc_mir_dataflow/src/points.rs b/compiler/rustc_mir_dataflow/src/points.rs index adfa94464a0..73abb669a11 100644 --- a/compiler/rustc_mir_dataflow/src/points.rs +++ b/compiler/rustc_mir_dataflow/src/points.rs @@ -3,7 +3,7 @@ use rustc_index::{Idx, IndexVec}; use rustc_middle::mir::{self, BasicBlock, Body, Location}; -use crate::framework::{visit_results, ResultsVisitable, ResultsVisitor}; +use crate::framework::{ResultsVisitable, ResultsVisitor, visit_results}; /// Maps between a `Location` and a `PointIndex` (and vice versa). pub struct DenseLocationMap { diff --git a/compiler/rustc_mir_dataflow/src/rustc_peek.rs b/compiler/rustc_mir_dataflow/src/rustc_peek.rs index ac9b853f21b..75732b19cd0 100644 --- a/compiler/rustc_mir_dataflow/src/rustc_peek.rs +++ b/compiler/rustc_mir_dataflow/src/rustc_peek.rs @@ -3,8 +3,8 @@ use rustc_index::bit_set::BitSet; use rustc_middle::mir::{self, Body, Local, Location}; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, sym}; use tracing::{debug, info}; use crate::errors::{ diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 05404366320..aa09fe1dd45 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -39,8 +39,8 @@ use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashMap, FxIndexSet, StdEntry}; use rustc_data_structures::stack::ensure_sufficient_stack; -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_middle::bug; use rustc_middle::mir::tcx::PlaceTy; use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor}; diff --git a/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs b/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs index 8291df9be53..d889bc90c9d 100644 --- a/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs +++ b/compiler/rustc_mir_transform/src/abort_unwinding_calls.rs @@ -1,9 +1,9 @@ use rustc_ast::InlineAsmOptions; use rustc_middle::mir::*; use rustc_middle::span_bug; -use rustc_middle::ty::{self, layout, TyCtxt}; -use rustc_target::spec::abi::Abi; +use rustc_middle::ty::{self, TyCtxt, layout}; use rustc_target::spec::PanicStrategy; +use rustc_target::spec::abi::Abi; /// A pass that runs which is targeted at ensuring that codegen guarantees about /// unwinding are upheld for compilations of panic=abort programs. 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 74df5f7479e..559df222a50 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 @@ -95,13 +95,10 @@ 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 8ad364ed055..53176eec9bc 100644 --- a/compiler/rustc_mir_transform/src/add_retag.rs +++ b/compiler/rustc_mir_transform/src/add_retag.rs @@ -111,13 +111,10 @@ fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { .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 @@ -172,13 +169,10 @@ fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { }; // 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_const_item_mutation.rs b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs index 9c3cbbe1fc9..7968b666dff 100644 --- a/compiler/rustc_mir_transform/src/check_const_item_mutation.rs +++ b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs @@ -3,8 +3,8 @@ use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; use rustc_session::lint::builtin::CONST_ITEM_MUTATION; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; use crate::errors; diff --git a/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs b/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs index 97ce16c0661..5395e1b0e94 100644 --- a/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs +++ b/compiler/rustc_mir_transform/src/cleanup_post_borrowck.rs @@ -18,8 +18,8 @@ use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::mir::{Body, BorrowKind, CastKind, Rvalue, StatementKind, TerminatorKind}; -use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::TyCtxt; +use rustc_middle::ty::adjustment::PointerCoercion; pub(super) struct CleanupPostBorrowck; diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index b3db5669121..7d6ae9843b1 100644 --- a/compiler/rustc_mir_transform/src/copy_prop.rs +++ b/compiler/rustc_mir_transform/src/copy_prop.rs @@ -1,5 +1,5 @@ -use rustc_index::bit_set::BitSet; use rustc_index::IndexSlice; +use rustc_index::bit_set::BitSet; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; diff --git a/compiler/rustc_mir_transform/src/coroutine.rs b/compiler/rustc_mir_transform/src/coroutine.rs index 1fb74f5d82c..8f032728f6b 100644 --- a/compiler/rustc_mir_transform/src/coroutine.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -67,14 +67,14 @@ self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, Ty, TyCtxt, }; use rustc_middle::{bug, span_bug}; +use rustc_mir_dataflow::Analysis; use rustc_mir_dataflow::impls::{ MaybeBorrowedLocals, MaybeLiveLocals, MaybeRequiresStorage, MaybeStorageLive, }; use rustc_mir_dataflow::storage::always_storage_live_locals; -use rustc_mir_dataflow::Analysis; +use rustc_span::Span; use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::symbol::sym; -use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; use rustc_target::spec::PanicStrategy; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; @@ -1054,14 +1054,11 @@ 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(); @@ -1072,7 +1069,7 @@ fn insert_switch<'tcx>( fn elaborate_coroutine_drops<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { use rustc_middle::mir::patch::MirPatch; - use rustc_mir_dataflow::elaborate_drops::{elaborate_drop, Unwind}; + use rustc_mir_dataflow::elaborate_drops::{Unwind, elaborate_drop}; use crate::shim::DropShimElaborator; @@ -1605,16 +1602,13 @@ fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // (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); @@ -1851,18 +1845,12 @@ fn check_suspend_tys<'tcx>(tcx: TyCtxt<'tcx>, layout: &CoroutineLayout<'tcx>, bo continue; }; - check_must_not_suspend_ty( - tcx, - decl.ty, - hir_id, - param_env, - 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, param_env, SuspendCheckData { + source_span: decl.source_info.span, + yield_span: yield_source_info.span, + plural_len: 1, + ..Default::default() + }); } } } @@ -1902,13 +1890,10 @@ 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, - param_env, - SuspendCheckData { descr_pre: &format!("{}boxed ", data.descr_pre), ..data }, - ) || check_must_not_suspend_ty( + check_must_not_suspend_ty(tcx, boxed_ty, hir_id, param_env, SuspendCheckData { + descr_pre: &format!("{}boxed ", data.descr_pre), + ..data + }) || check_must_not_suspend_ty( tcx, allocator_ty, hir_id, @@ -1927,12 +1912,10 @@ 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; } @@ -1946,12 +1929,10 @@ 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; } @@ -1963,13 +1944,10 @@ 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, - param_env, - SuspendCheckData { descr_post, ..data }, - ) { + if check_must_not_suspend_ty(tcx, ty, hir_id, param_env, SuspendCheckData { + descr_post, + ..data + }) { has_emitted = true; } } @@ -1977,29 +1955,20 @@ 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, - param_env, - SuspendCheckData { - descr_pre, - plural_len: len.try_eval_target_usize(tcx, param_env).unwrap_or(0) as usize + 1, - ..data - }, - ) + check_must_not_suspend_ty(tcx, ty, hir_id, param_env, SuspendCheckData { + descr_pre, + plural_len: len.try_eval_target_usize(tcx, param_env).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. ty::Ref(_region, ty, _mutability) => { let descr_pre = &format!("{}reference{} to ", data.descr_pre, plural_suffix); - check_must_not_suspend_ty( - tcx, - ty, - hir_id, - param_env, - SuspendCheckData { descr_pre, ..data }, - ) + check_must_not_suspend_ty(tcx, ty, hir_id, param_env, SuspendCheckData { + descr_pre, + ..data + }) } _ => false, } 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 6476f3c6238..65442877d2d 100644 --- a/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs +++ b/compiler/rustc_mir_transform/src/coroutine/by_move_body.rs @@ -140,10 +140,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/graph.rs b/compiler/rustc_mir_transform/src/coverage/graph.rs index 743aa679058..d839f46cfbd 100644 --- a/compiler/rustc_mir_transform/src/coverage/graph.rs +++ b/compiler/rustc_mir_transform/src/coverage/graph.rs @@ -6,8 +6,8 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::graph::dominators::{self, Dominators}; use rustc_data_structures::graph::{self, DirectedGraph, StartNode}; -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_middle::bug; use rustc_middle::mir::{self, BasicBlock, Terminator, TerminatorKind}; use tracing::debug; diff --git a/compiler/rustc_mir_transform/src/coverage/mappings.rs b/compiler/rustc_mir_transform/src/coverage/mappings.rs index 2ac08ea85d2..ec5ba354805 100644 --- a/compiler/rustc_mir_transform/src/coverage/mappings.rs +++ b/compiler/rustc_mir_transform/src/coverage/mappings.rs @@ -1,8 +1,8 @@ use std::collections::BTreeSet; use rustc_data_structures::graph::DirectedGraph; -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_middle::mir::coverage::{ BlockMarkerId, BranchSpan, ConditionInfo, CoverageInfoHi, CoverageKind, }; @@ -10,10 +10,10 @@ use rustc_middle::ty::TyCtxt; use rustc_span::Span; +use crate::coverage::ExtractedHirInfo; use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph, START_BCB}; use crate::coverage::spans::extract_refined_covspans; use crate::coverage::unexpand::unexpand_into_body_span; -use crate::coverage::ExtractedHirInfo; /// Associates an ordinary executable code span with its corresponding BCB. #[derive(Debug)] diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index f78fc7931f9..104f340c8d6 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -9,7 +9,7 @@ mod unexpand; use rustc_hir as hir; -use rustc_hir::intravisit::{walk_expr, Visitor}; +use rustc_hir::intravisit::{Visitor, walk_expr}; use rustc_middle::hir::map::Map; use rustc_middle::hir::nested_filter; use rustc_middle::mir::coverage::{ @@ -147,8 +147,8 @@ fn create_mappings<'tcx>( let source_file = source_map.lookup_source_file(body_span.lo()); - use rustc_session::config::RemapPathScopeComponents; use rustc_session::RemapFileNameExt; + use rustc_session::config::RemapPathScopeComponents; let file_name = Symbol::intern( &source_file.name.for_scope(tcx.sess, RemapPathScopeComponents::MACRO).to_string_lossy(), ); diff --git a/compiler/rustc_mir_transform/src/coverage/spans.rs b/compiler/rustc_mir_transform/src/coverage/spans.rs index b904b0d2599..da7d20cf19a 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -8,9 +8,9 @@ use crate::coverage::graph::{BasicCoverageBlock, CoverageGraph}; use crate::coverage::spans::from_mir::{ - extract_covspans_from_mir, ExtractedCovspans, Hole, SpanFromMir, + ExtractedCovspans, Hole, SpanFromMir, extract_covspans_from_mir, }; -use crate::coverage::{mappings, ExtractedHirInfo}; +use crate::coverage::{ExtractedHirInfo, mappings}; mod from_mir; diff --git a/compiler/rustc_mir_transform/src/coverage/spans/from_mir.rs b/compiler/rustc_mir_transform/src/coverage/spans/from_mir.rs index 7f5765c9462..875db23ce09 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans/from_mir.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans/from_mir.rs @@ -5,12 +5,12 @@ }; use rustc_span::{ExpnKind, Span}; +use crate::coverage::ExtractedHirInfo; use crate::coverage::graph::{ BasicCoverageBlock, BasicCoverageBlockData, CoverageGraph, START_BCB, }; use crate::coverage::spans::Covspan; use crate::coverage::unexpand::unexpand_into_body_span_with_expn_kind; -use crate::coverage::ExtractedHirInfo; pub(crate) struct ExtractedCovspans { pub(crate) covspans: Vec, diff --git a/compiler/rustc_mir_transform/src/coverage/tests.rs b/compiler/rustc_mir_transform/src/coverage/tests.rs index a4db11bb2c1..233ca9981c5 100644 --- a/compiler/rustc_mir_transform/src/coverage/tests.rs +++ b/compiler/rustc_mir_transform/src/coverage/tests.rs @@ -29,7 +29,7 @@ use rustc_index::{Idx, IndexVec}; use rustc_middle::mir::*; use rustc_middle::{bug, ty}; -use rustc_span::{BytePos, Pos, Span, DUMMY_SP}; +use rustc_span::{BytePos, DUMMY_SP, Pos, Span}; use super::graph::{self, BasicCoverageBlock}; @@ -129,18 +129,15 @@ fn set_branch(&mut self, switchint: BasicBlock, branch_index: usize, to_block: B } 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/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index 997b8c06a96..2026b789315 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -2,7 +2,7 @@ //! //! Currently, this pass only propagates scalar values. -use rustc_const_eval::const_eval::{throw_machine_stop_str, DummyMachine}; +use rustc_const_eval::const_eval::{DummyMachine, throw_machine_stop_str}; use rustc_const_eval::interpret::{ImmTy, Immediate, InterpCx, OpTy, PlaceTy, Projectable}; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def::DefKind; @@ -18,7 +18,7 @@ }; use rustc_mir_dataflow::{Analysis, Results, ResultsVisitor}; use rustc_span::DUMMY_SP; -use rustc_target::abi::{Abi, FieldIdx, Size, VariantIdx, FIRST_VARIANT}; +use rustc_target::abi::{Abi, FIRST_VARIANT, FieldIdx, Size, VariantIdx}; use tracing::{debug, debug_span, instrument}; // These constants are somewhat random guesses and have not been optimized. diff --git a/compiler/rustc_mir_transform/src/dead_store_elimination.rs b/compiler/rustc_mir_transform/src/dead_store_elimination.rs index 65c037559c5..edffe6ce78f 100644 --- a/compiler/rustc_mir_transform/src/dead_store_elimination.rs +++ b/compiler/rustc_mir_transform/src/dead_store_elimination.rs @@ -16,11 +16,11 @@ use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; +use rustc_mir_dataflow::Analysis; use rustc_mir_dataflow::debuginfo::debuginfo_locals; use rustc_mir_dataflow::impls::{ - borrowed_locals, LivenessTransferFunction, MaybeTransitiveLiveLocals, + LivenessTransferFunction, MaybeTransitiveLiveLocals, borrowed_locals, }; -use rustc_mir_dataflow::Analysis; use crate::util::is_within_packed; diff --git a/compiler/rustc_mir_transform/src/deduce_param_attrs.rs b/compiler/rustc_mir_transform/src/deduce_param_attrs.rs index c0cb0e641ac..753bae8e156 100644 --- a/compiler/rustc_mir_transform/src/deduce_param_attrs.rs +++ b/compiler/rustc_mir_transform/src/deduce_param_attrs.rs @@ -8,7 +8,7 @@ use rustc_hir::def_id::LocalDefId; use rustc_index::bit_set::BitSet; use rustc_middle::mir::visit::{NonMutatingUseContext, PlaceContext, Visitor}; -use rustc_middle::mir::{Body, Location, Operand, Place, Terminator, TerminatorKind, RETURN_PLACE}; +use rustc_middle::mir::{Body, Location, Operand, Place, RETURN_PLACE, Terminator, TerminatorKind}; use rustc_middle::ty::{self, DeducedParamAttrs, Ty, TyCtxt}; use rustc_session::config::OptLevel; diff --git a/compiler/rustc_mir_transform/src/dest_prop.rs b/compiler/rustc_mir_transform/src/dest_prop.rs index f123658580d..ad83c0295ba 100644 --- a/compiler/rustc_mir_transform/src/dest_prop.rs +++ b/compiler/rustc_mir_transform/src/dest_prop.rs @@ -137,13 +137,13 @@ use rustc_middle::bug; use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; use rustc_middle::mir::{ - dump_mir, traversal, Body, HasLocalDecls, InlineAsmOperand, Local, LocalKind, Location, - Operand, PassWhere, Place, Rvalue, Statement, StatementKind, TerminatorKind, + Body, HasLocalDecls, InlineAsmOperand, Local, LocalKind, Location, Operand, PassWhere, Place, + Rvalue, Statement, StatementKind, TerminatorKind, dump_mir, traversal, }; use rustc_middle::ty::TyCtxt; -use rustc_mir_dataflow::impls::MaybeLiveLocals; -use rustc_mir_dataflow::points::{save_as_intervals, DenseLocationMap, PointIndex}; use rustc_mir_dataflow::Analysis; +use rustc_mir_dataflow::impls::MaybeLiveLocals; +use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex, save_as_intervals}; use tracing::{debug, trace}; pub(super) struct DestinationPropagation; diff --git a/compiler/rustc_mir_transform/src/dump_mir.rs b/compiler/rustc_mir_transform/src/dump_mir.rs index 1640d34d6c8..d7c47360419 100644 --- a/compiler/rustc_mir_transform/src/dump_mir.rs +++ b/compiler/rustc_mir_transform/src/dump_mir.rs @@ -3,7 +3,7 @@ use std::fs::File; use std::io; -use rustc_middle::mir::{write_mir_pretty, Body}; +use rustc_middle::mir::{Body, write_mir_pretty}; use rustc_middle::ty::TyCtxt; use rustc_session::config::{OutFileName, OutputType}; diff --git a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs index 704ed508b22..aed7f20aaea 100644 --- a/compiler/rustc_mir_transform/src/early_otherwise_branch.rs +++ b/compiler/rustc_mir_transform/src/early_otherwise_branch.rs @@ -133,18 +133,29 @@ fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let mut patch = MirPatch::new(body); - // create temp to store second discriminant in, `_s` in example above - let second_discriminant_temp = - patch.new_temp(opt_data.child_ty, opt_data.child_source.span); + let (second_discriminant_temp, second_operand) = if opt_data.need_hoist_discriminant { + // create temp to store second discriminant in, `_s` in example above + let second_discriminant_temp = + patch.new_temp(opt_data.child_ty, opt_data.child_source.span); - patch.add_statement(parent_end, StatementKind::StorageLive(second_discriminant_temp)); + patch.add_statement( + parent_end, + StatementKind::StorageLive(second_discriminant_temp), + ); - // create assignment of discriminant - patch.add_assign( - parent_end, - Place::from(second_discriminant_temp), - Rvalue::Discriminant(opt_data.child_place), - ); + // create assignment of discriminant + patch.add_assign( + parent_end, + Place::from(second_discriminant_temp), + Rvalue::Discriminant(opt_data.child_place), + ); + ( + Some(second_discriminant_temp), + Operand::Move(Place::from(second_discriminant_temp)), + ) + } else { + (None, Operand::Copy(opt_data.child_place)) + }; // create temp to store inequality comparison between the two discriminants, `_t` in // example above @@ -153,11 +164,9 @@ fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { let comp_temp = patch.new_temp(comp_res_type, opt_data.child_source.span); patch.add_statement(parent_end, StatementKind::StorageLive(comp_temp)); - // create inequality comparison between the two discriminants - let comp_rvalue = Rvalue::BinaryOp( - nequal, - Box::new((parent_op.clone(), Operand::Move(Place::from(second_discriminant_temp)))), - ); + // create inequality comparison + let comp_rvalue = + Rvalue::BinaryOp(nequal, Box::new((parent_op.clone(), second_operand))); patch.add_statement( parent_end, StatementKind::Assign(Box::new((Place::from(comp_temp), comp_rvalue))), @@ -193,8 +202,13 @@ fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { TerminatorKind::if_(Operand::Move(Place::from(comp_temp)), true_case, false_case), ); - // generate StorageDead for the second_discriminant_temp not in use anymore - patch.add_statement(parent_end, StatementKind::StorageDead(second_discriminant_temp)); + if let Some(second_discriminant_temp) = second_discriminant_temp { + // generate StorageDead for the second_discriminant_temp not in use anymore + patch.add_statement( + parent_end, + StatementKind::StorageDead(second_discriminant_temp), + ); + } // Generate a StorageDead for comp_temp in each of the targets, since we moved it into // the switch @@ -222,6 +236,7 @@ struct OptimizationData<'tcx> { child_place: Place<'tcx>, child_ty: Ty<'tcx>, child_source: SourceInfo, + need_hoist_discriminant: bool, } fn evaluate_candidate<'tcx>( @@ -235,44 +250,12 @@ fn evaluate_candidate<'tcx>( return None; }; let parent_ty = parent_discr.ty(body.local_decls(), tcx); - if !bbs[targets.otherwise()].is_empty_unreachable() { - // Someone could write code like this: - // ```rust - // let Q = val; - // if discriminant(P) == otherwise { - // let ptr = &mut Q as *mut _ as *mut u8; - // // It may be difficult for us to effectively determine whether values are valid. - // // Invalid values can come from all sorts of corners. - // unsafe { *ptr = 10; } - // } - // - // match P { - // A => match Q { - // A => { - // // code - // } - // _ => { - // // don't use Q - // } - // } - // _ => { - // // don't use Q - // } - // }; - // ``` - // - // Hoisting the `discriminant(Q)` out of the `A` arm causes us to compute the discriminant - // of an invalid value, which is UB. - // In order to fix this, **we would either need to show that the discriminant computation of - // `place` is computed in all branches**. - // FIXME(#95162) For the moment, we adopt a conservative approach and - // consider only the `otherwise` branch has no statements and an unreachable terminator. - return None; - } let (_, child) = targets.iter().next()?; - let child_terminator = &bbs[child].terminator(); - let TerminatorKind::SwitchInt { targets: child_targets, discr: child_discr } = - &child_terminator.kind + + let Terminator { + kind: TerminatorKind::SwitchInt { targets: child_targets, discr: child_discr }, + source_info, + } = bbs[child].terminator() else { return None; }; @@ -280,25 +263,115 @@ fn evaluate_candidate<'tcx>( if child_ty != parent_ty { return None; } - let Some(StatementKind::Assign(boxed)) = &bbs[child].statements.first().map(|x| &x.kind) else { + + // We only handle: + // ``` + // bb4: { + // _8 = discriminant((_3.1: Enum1)); + // switchInt(move _8) -> [2: bb7, otherwise: bb1]; + // } + // ``` + // and + // ``` + // bb2: { + // switchInt((_3.1: u64)) -> [1: bb5, otherwise: bb1]; + // } + // ``` + if bbs[child].statements.len() > 1 { return None; + } + + // When thie BB has exactly one statement, this statement should be discriminant. + let need_hoist_discriminant = bbs[child].statements.len() == 1; + let child_place = if need_hoist_discriminant { + if !bbs[targets.otherwise()].is_empty_unreachable() { + // Someone could write code like this: + // ```rust + // let Q = val; + // if discriminant(P) == otherwise { + // let ptr = &mut Q as *mut _ as *mut u8; + // // It may be difficult for us to effectively determine whether values are valid. + // // Invalid values can come from all sorts of corners. + // unsafe { *ptr = 10; } + // } + // + // match P { + // A => match Q { + // A => { + // // code + // } + // _ => { + // // don't use Q + // } + // } + // _ => { + // // don't use Q + // } + // }; + // ``` + // + // Hoisting the `discriminant(Q)` out of the `A` arm causes us to compute the discriminant of an + // invalid value, which is UB. + // In order to fix this, **we would either need to show that the discriminant computation of + // `place` is computed in all branches**. + // FIXME(#95162) For the moment, we adopt a conservative approach and + // consider only the `otherwise` branch has no statements and an unreachable terminator. + return None; + } + // Handle: + // ``` + // bb4: { + // _8 = discriminant((_3.1: Enum1)); + // switchInt(move _8) -> [2: bb7, otherwise: bb1]; + // } + // ``` + let [ + Statement { + kind: StatementKind::Assign(box (_, Rvalue::Discriminant(child_place))), + .. + }, + ] = bbs[child].statements.as_slice() + else { + return None; + }; + *child_place + } else { + // Handle: + // ``` + // bb2: { + // switchInt((_3.1: u64)) -> [1: bb5, otherwise: bb1]; + // } + // ``` + let Operand::Copy(child_place) = child_discr else { + return None; + }; + *child_place }; - let (_, Rvalue::Discriminant(child_place)) = &**boxed else { - return None; + let destination = if need_hoist_discriminant || bbs[targets.otherwise()].is_empty_unreachable() + { + child_targets.otherwise() + } else { + targets.otherwise() }; - let destination = child_targets.otherwise(); // Verify that the optimization is legal for each branch for (value, child) in targets.iter() { - if !verify_candidate_branch(&bbs[child], value, *child_place, destination) { + if !verify_candidate_branch( + &bbs[child], + value, + child_place, + destination, + need_hoist_discriminant, + ) { return None; } } Some(OptimizationData { destination, - child_place: *child_place, + child_place, child_ty, - child_source: child_terminator.source_info, + child_source: *source_info, + need_hoist_discriminant, }) } @@ -307,31 +380,48 @@ fn verify_candidate_branch<'tcx>( value: u128, place: Place<'tcx>, destination: BasicBlock, + need_hoist_discriminant: bool, ) -> bool { - // In order for the optimization to be correct, the branch must... - // ...have exactly one statement - if let [statement] = branch.statements.as_slice() - // ...assign the discriminant of `place` in that statement - && let StatementKind::Assign(boxed) = &statement.kind - && let (discr_place, Rvalue::Discriminant(from_place)) = &**boxed - && *from_place == place - // ...make that assignment to a local - && discr_place.projection.is_empty() - // ...terminate on a `SwitchInt` that invalidates that local - && let TerminatorKind::SwitchInt { discr: switch_op, targets, .. } = - &branch.terminator().kind - && *switch_op == Operand::Move(*discr_place) - // ...fall through to `destination` if the switch misses - && destination == targets.otherwise() - // ...have a branch for value `value` - && let mut iter = targets.iter() - && let Some((target_value, _)) = iter.next() - && target_value == value - // ...and have no more branches - && iter.next().is_none() - { - true + // In order for the optimization to be correct, the terminator must be a `SwitchInt`. + let TerminatorKind::SwitchInt { discr: switch_op, targets } = &branch.terminator().kind else { + return false; + }; + if need_hoist_discriminant { + // If we need hoist discriminant, the branch must have exactly one statement. + let [statement] = branch.statements.as_slice() else { + return false; + }; + // The statement must assign the discriminant of `place`. + let StatementKind::Assign(box (discr_place, Rvalue::Discriminant(from_place))) = + statement.kind + else { + return false; + }; + if from_place != place { + return false; + } + // The assignment must invalidate a local that terminate on a `SwitchInt`. + if !discr_place.projection.is_empty() || *switch_op != Operand::Move(discr_place) { + return false; + } } else { - false + // If we don't need hoist discriminant, the branch must not have any statements. + if !branch.statements.is_empty() { + return false; + } + // The place on `SwitchInt` must be the same. + if *switch_op != Operand::Copy(place) { + return false; + } } + // It must fall through to `destination` if the switch misses. + if destination != targets.otherwise() { + return false; + } + // It must have exactly one branch for value `value` and have no more branches. + let mut iter = targets.iter(); + let (Some((target_value, _)), None) = (iter.next(), iter.next()) else { + return false; + }; + target_value == value } diff --git a/compiler/rustc_mir_transform/src/elaborate_drops.rs b/compiler/rustc_mir_transform/src/elaborate_drops.rs index 42d13fa3613..c35aec42408 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drops.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drops.rs @@ -1,17 +1,17 @@ use std::fmt; -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::*; use rustc_middle::ty::{self, TyCtxt}; use rustc_mir_dataflow::elaborate_drops::{ - elaborate_drop, DropElaborator, DropFlagMode, DropFlagState, DropStyle, Unwind, + DropElaborator, DropFlagMode, DropFlagState, DropStyle, Unwind, elaborate_drop, }; use rustc_mir_dataflow::impls::{MaybeInitializedPlaces, MaybeUninitializedPlaces}; use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex}; use rustc_mir_dataflow::{ - on_all_children_bits, on_lookup_result_bits, Analysis, MoveDataParamEnv, ResultsCursor, + Analysis, MoveDataParamEnv, ResultsCursor, on_all_children_bits, on_lookup_result_bits, }; use rustc_span::Span; use rustc_target::abi::{FieldIdx, VariantIdx}; diff --git a/compiler/rustc_mir_transform/src/errors.rs b/compiler/rustc_mir_transform/src/errors.rs index 4550ef06315..84d44c2ab4c 100644 --- a/compiler/rustc_mir_transform/src/errors.rs +++ b/compiler/rustc_mir_transform/src/errors.rs @@ -4,8 +4,8 @@ use rustc_middle::mir::AssertKind; use rustc_middle::ty::TyCtxt; use rustc_session::lint::{self, Lint}; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; use crate::fluent_generated as fluent; diff --git a/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs b/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs index 8490b7e2358..99892a1296b 100644 --- a/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs +++ b/compiler/rustc_mir_transform/src/ffi_unwind_calls.rs @@ -1,11 +1,11 @@ -use rustc_hir::def_id::{LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{LOCAL_CRATE, LocalDefId}; use rustc_middle::mir::*; use rustc_middle::query::{LocalCrate, Providers}; -use rustc_middle::ty::{self, layout, TyCtxt}; +use rustc_middle::ty::{self, TyCtxt, layout}; use rustc_middle::{bug, span_bug}; use rustc_session::lint::builtin::FFI_UNWIND_CALLS; -use rustc_target::spec::abi::Abi; use rustc_target::spec::PanicStrategy; +use rustc_target::spec::abi::Abi; use tracing::debug; use crate::errors; @@ -86,12 +86,10 @@ 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, + tcx.emit_node_span_lint(FFI_UNWIND_CALLS, lint_root, span, errors::FfiUnwindCall { span, - errors::FfiUnwindCall { span, foreign }, - ); + foreign, + }); tainted = true; } diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index eb09a7d3b21..e55aeeac6e0 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -4,9 +4,9 @@ use rustc_middle::mir::*; use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt}; use rustc_session::lint::builtin::FUNCTION_ITEM_REFERENCES; +use rustc_span::Span; use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; -use rustc_span::Span; use rustc_target::spec::abi::Abi; use crate::errors; diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index 0f08d920c5e..4d44669fa3e 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -87,23 +87,23 @@ use either::Either; use rustc_const_eval::const_eval::DummyMachine; use rustc_const_eval::interpret::{ - intern_const_alloc_for_constprop, ImmTy, Immediate, InterpCx, MemPlaceMeta, MemoryKind, OpTy, - Projectable, Scalar, + ImmTy, Immediate, InterpCx, MemPlaceMeta, MemoryKind, OpTy, Projectable, Scalar, + intern_const_alloc_for_constprop, }; use rustc_data_structures::fx::FxIndexSet; use rustc_data_structures::graph::dominators::Dominators; use rustc_hir::def::DefKind; use rustc_index::bit_set::BitSet; -use rustc_index::{newtype_index, IndexVec}; +use rustc_index::{IndexVec, newtype_index}; use rustc_middle::bug; use rustc_middle::mir::interpret::GlobalAlloc; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::layout::{HasParamEnv, LayoutOf}; use rustc_middle::ty::{self, Ty, TyCtxt}; -use rustc_span::def_id::DefId; use rustc_span::DUMMY_SP; -use rustc_target::abi::{self, Abi, FieldIdx, Size, VariantIdx, FIRST_VARIANT}; +use rustc_span::def_id::DefId; +use rustc_target::abi::{self, Abi, FIRST_VARIANT, FieldIdx, Size, VariantIdx}; use smallvec::SmallVec; use tracing::{debug, instrument, trace}; @@ -1333,8 +1333,8 @@ fn simplify_cast( to: Ty<'tcx>, location: Location, ) -> Option { - use rustc_middle::ty::adjustment::PointerCoercion::*; use CastKind::*; + use rustc_middle::ty::adjustment::PointerCoercion::*; let mut from = operand.ty(self.local_decls, self.tcx); let mut value = self.simplify_operand(operand, location)?; diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 2de75e2ef50..c9f24764cc2 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -6,8 +6,8 @@ use rustc_attr::InlineAttr; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; -use rustc_index::bit_set::BitSet; use rustc_index::Idx; +use rustc_index::bit_set::BitSet; use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}; use rustc_middle::mir::visit::*; @@ -885,13 +885,10 @@ fn new_call_temp( }); 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/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index 5c8958924fb..8bcc91b4488 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -5,7 +5,7 @@ use rustc_middle::bug; use rustc_middle::mir::*; use rustc_middle::ty::layout::ValidityRequirement; -use rustc_middle::ty::{self, layout, GenericArgsRef, ParamEnv, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArgsRef, ParamEnv, Ty, TyCtxt, layout}; use rustc_span::sym; use rustc_span::symbol::Symbol; use rustc_target::spec::abi::Abi; diff --git a/compiler/rustc_mir_transform/src/jump_threading.rs b/compiler/rustc_mir_transform/src/jump_threading.rs index 1810569bc8e..9d85b5ba5a7 100644 --- a/compiler/rustc_mir_transform/src/jump_threading.rs +++ b/compiler/rustc_mir_transform/src/jump_threading.rs @@ -39,8 +39,8 @@ use rustc_const_eval::const_eval::DummyMachine; use rustc_const_eval::interpret::{ImmTy, Immediate, InterpCx, OpTy, Projectable}; use rustc_data_structures::fx::FxHashSet; -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_middle::bug; use rustc_middle::mir::interpret::Scalar; use rustc_middle::mir::visit::Visitor; diff --git a/compiler/rustc_mir_transform/src/known_panics_lint.rs b/compiler/rustc_mir_transform/src/known_panics_lint.rs index f123f39bf42..783e7aabe85 100644 --- a/compiler/rustc_mir_transform/src/known_panics_lint.rs +++ b/compiler/rustc_mir_transform/src/known_panics_lint.rs @@ -6,13 +6,13 @@ use rustc_const_eval::const_eval::DummyMachine; use rustc_const_eval::interpret::{ - format_interp_error, ImmTy, InterpCx, InterpResult, Projectable, Scalar, + ImmTy, InterpCx, InterpResult, Projectable, Scalar, format_interp_error, }; use rustc_data_structures::fx::FxHashSet; -use rustc_hir::def::DefKind; use rustc_hir::HirId; -use rustc_index::bit_set::BitSet; +use rustc_hir::def::DefKind; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_middle::bug; use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; @@ -296,12 +296,11 @@ fn report_assert_as_lint( 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, + self.tcx.emit_node_span_lint(lint_kind.lint(), lint_root, span, AssertLint { span, - AssertLint { span, assert_kind, lint_kind }, - ); + assert_kind, + lint_kind, + }); } } diff --git a/compiler/rustc_mir_transform/src/lib.rs b/compiler/rustc_mir_transform/src/lib.rs index 0868f4b3d88..56268c1d201 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -26,14 +26,14 @@ use rustc_index::IndexVec; use rustc_middle::mir::{ AnalysisPhase, Body, CallSource, ClearCrossCrate, ConstOperand, ConstQualifs, LocalDecl, - MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, SourceInfo, - Statement, StatementKind, TerminatorKind, START_BLOCK, + MirPhase, Operand, Place, ProjectionElem, Promoted, RuntimePhase, Rvalue, START_BLOCK, + SourceInfo, Statement, StatementKind, TerminatorKind, }; use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; use rustc_middle::util::Providers; use rustc_middle::{bug, query, span_bug}; use rustc_span::source_map::Spanned; -use rustc_span::{sym, DUMMY_SP}; +use rustc_span::{DUMMY_SP, sym}; use rustc_trait_selection::traits; use tracing::{debug, trace}; diff --git a/compiler/rustc_mir_transform/src/promote_consts.rs b/compiler/rustc_mir_transform/src/promote_consts.rs index 59df99f858d..d963ca5c485 100644 --- a/compiler/rustc_mir_transform/src/promote_consts.rs +++ b/compiler/rustc_mir_transform/src/promote_consts.rs @@ -15,7 +15,7 @@ use std::{cmp, iter, mem}; use either::{Left, Right}; -use rustc_const_eval::check_consts::{qualifs, ConstCx}; +use rustc_const_eval::check_consts::{ConstCx, qualifs}; use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; use rustc_index::{Idx, IndexSlice, IndexVec}; @@ -23,8 +23,8 @@ use rustc_middle::mir::*; use rustc_middle::ty::{self, GenericArgs, List, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, mir, span_bug}; -use rustc_span::source_map::Spanned; use rustc_span::Span; +use rustc_span::source_map::Spanned; use tracing::{debug, instrument}; /// A `MirPass` for promotion. @@ -912,23 +912,19 @@ fn promote_candidate(mut self, candidate: Candidate, next_promoted_id: usize) -> 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/ref_prop.rs b/compiler/rustc_mir_transform/src/ref_prop.rs index 4c3a99b79d4..a62a892716f 100644 --- a/compiler/rustc_mir_transform/src/ref_prop.rs +++ b/compiler/rustc_mir_transform/src/ref_prop.rs @@ -1,15 +1,15 @@ use std::borrow::Cow; use rustc_data_structures::fx::FxHashSet; -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_middle::bug; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::TyCtxt; +use rustc_mir_dataflow::Analysis; use rustc_mir_dataflow::impls::MaybeStorageDead; use rustc_mir_dataflow::storage::always_storage_live_locals; -use rustc_mir_dataflow::Analysis; use tracing::{debug, instrument}; use crate::ssa::{SsaLocals, StorageLiveLocals}; diff --git a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs index d80a4edecdf..e6647edf3f5 100644 --- a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs +++ b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs @@ -3,7 +3,7 @@ use rustc_middle::ty::{self, GenericArgsRef, ParamEnv, Ty, TyCtxt, VariantDef}; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex}; -use rustc_mir_dataflow::{move_path_children_matching, Analysis, MaybeReachable}; +use rustc_mir_dataflow::{Analysis, MaybeReachable, move_path_children_matching}; use rustc_target::abi::FieldIdx; /// Removes `Drop` terminators whose target is known to be uninitialized at diff --git a/compiler/rustc_mir_transform/src/required_consts.rs b/compiler/rustc_mir_transform/src/required_consts.rs index 99d1cd6f63e..b418ede42f0 100644 --- a/compiler/rustc_mir_transform/src/required_consts.rs +++ b/compiler/rustc_mir_transform/src/required_consts.rs @@ -1,5 +1,5 @@ use rustc_middle::mir::visit::Visitor; -use rustc_middle::mir::{traversal, Body, ConstOperand, Location}; +use rustc_middle::mir::{Body, ConstOperand, Location, traversal}; pub(super) struct RequiredConstsVisitor<'tcx> { required_consts: Vec>, diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 47d04d8a00b..e872878a751 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -14,8 +14,8 @@ use rustc_middle::{bug, span_bug}; use rustc_mir_dataflow::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle}; use rustc_span::source_map::Spanned; -use rustc_span::{Span, DUMMY_SP}; -use rustc_target::abi::{FieldIdx, VariantIdx, FIRST_VARIANT}; +use rustc_span::{DUMMY_SP, Span}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx, VariantIdx}; use rustc_target::spec::abi::Abi; use tracing::{debug, instrument}; 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 c88953a1d1a..c206252c15a 100644 --- a/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs +++ b/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs @@ -8,8 +8,8 @@ use rustc_index::{Idx, IndexVec}; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, CallSource, CastKind, Const, ConstOperand, ConstValue, Local, - LocalDecl, MirSource, Operand, Place, PlaceElem, Rvalue, SourceInfo, Statement, StatementKind, - Terminator, TerminatorKind, UnwindAction, UnwindTerminateReason, RETURN_PLACE, + LocalDecl, MirSource, Operand, Place, PlaceElem, RETURN_PLACE, Rvalue, SourceInfo, Statement, + StatementKind, Terminator, TerminatorKind, UnwindAction, UnwindTerminateReason, }; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::util::{AsyncDropGlueMorphology, Discr}; @@ -452,19 +452,17 @@ fn combine_async_surface(&mut self) -> Ty<'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> { @@ -484,11 +482,11 @@ fn combine_chain(&mut self, first: Ty<'tcx>, second: Ty<'tcx>) -> Ty<'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 e8d8335b136..26496b7f3fe 100644 --- a/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs +++ b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs @@ -113,13 +113,10 @@ fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { // 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/single_use_consts.rs b/compiler/rustc_mir_transform/src/single_use_consts.rs index 26059268c37..9884b6dd1c3 100644 --- a/compiler/rustc_mir_transform/src/single_use_consts.rs +++ b/compiler/rustc_mir_transform/src/single_use_consts.rs @@ -1,5 +1,5 @@ -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_middle::bug; use rustc_middle::mir::visit::{MutVisitor, PlaceContext, Visitor}; use rustc_middle::mir::*; diff --git a/compiler/rustc_mir_transform/src/sroa.rs b/compiler/rustc_mir_transform/src/sroa.rs index e6dd2cfd862..2de0059bc7f 100644 --- a/compiler/rustc_mir_transform/src/sroa.rs +++ b/compiler/rustc_mir_transform/src/sroa.rs @@ -1,14 +1,14 @@ use rustc_data_structures::flat_map_in_place::FlatMapInPlace; use rustc_hir::LangItem; -use rustc_index::bit_set::{BitSet, GrowableBitSet}; use rustc_index::IndexVec; +use rustc_index::bit_set::{BitSet, GrowableBitSet}; use rustc_middle::bug; use rustc_middle::mir::patch::MirPatch; use rustc_middle::mir::visit::*; use rustc_middle::mir::*; use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_mir_dataflow::value_analysis::{excluded_locals, iter_fields}; -use rustc_target::abi::{FieldIdx, FIRST_VARIANT}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx}; use tracing::{debug, instrument}; pub(super) struct ScalarReplacementOfAggregates; diff --git a/compiler/rustc_mir_transform/src/ssa.rs b/compiler/rustc_mir_transform/src/ssa.rs index ba64216f9e1..84df666e34a 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -159,11 +159,10 @@ pub(super) fn for_each_assignment_mut<'tcx>( ) { 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_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index e5837b1b475..914dddc1a56 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -2,8 +2,8 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::LangItem; -use rustc_index::bit_set::BitSet; use rustc_index::IndexVec; +use rustc_index::bit_set::BitSet; use rustc_infer::traits::Reveal; use rustc_middle::mir::coverage::CoverageKind; use rustc_middle::mir::visit::{NonUseContext, PlaceContext, Visitor}; @@ -14,7 +14,7 @@ Variance, }; use rustc_middle::{bug, span_bug}; -use rustc_target::abi::{Size, FIRST_VARIANT}; +use rustc_target::abi::{FIRST_VARIANT, Size}; use rustc_target::spec::abi::Abi; use crate::util::{is_within_packed, relate_types}; diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index c3f22896200..0cdd237dc00 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -210,7 +210,7 @@ use std::path::PathBuf; use move_check::MoveCheckState; -use rustc_data_structures::sync::{par_for_each_in, LRef, MTLock}; +use rustc_data_structures::sync::{LRef, MTLock, par_for_each_in}; use rustc_data_structures::unord::{UnordMap, UnordSet}; use rustc_hir as hir; use rustc_hir::def::DefKind; @@ -220,7 +220,7 @@ use rustc_middle::mir::interpret::{AllocId, ErrorHandled, GlobalAlloc, Scalar}; use rustc_middle::mir::mono::{InstantiationMode, MonoItem}; use rustc_middle::mir::visit::Visitor as MirVisitor; -use rustc_middle::mir::{self, traversal, Location, MentionedItem}; +use rustc_middle::mir::{self, Location, MentionedItem, traversal}; use rustc_middle::query::TyCtxtAt; use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCoercion}; use rustc_middle::ty::layout::ValidityRequirement; @@ -231,11 +231,11 @@ }; use rustc_middle::util::Providers; use rustc_middle::{bug, span_bug}; -use rustc_session::config::EntryFnType; use rustc_session::Limit; -use rustc_span::source_map::{dummy_spanned, respan, Spanned}; -use rustc_span::symbol::{sym, Ident}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_session::config::EntryFnType; +use rustc_span::source_map::{Spanned, dummy_spanned, respan}; +use rustc_span::symbol::{Ident, sym}; +use rustc_span::{DUMMY_SP, Span}; use rustc_target::abi::Size; use tracing::{debug, instrument, trace}; diff --git a/compiler/rustc_monomorphize/src/collector/move_check.rs b/compiler/rustc_monomorphize/src/collector/move_check.rs index 851f86e86b8..b86ef1e7373 100644 --- a/compiler/rustc_monomorphize/src/collector/move_check.rs +++ b/compiler/rustc_monomorphize/src/collector/move_check.rs @@ -132,12 +132,11 @@ fn lint_large_assignment( // 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, + self.tcx.emit_node_span_lint(LARGE_ASSIGNMENTS, lint_root, span, LargeAssignmentsLint { span, - LargeAssignmentsLint { span, size: too_large_size.bytes(), limit: limit as u64 }, - ); + size: too_large_size.bytes(), + limit: limit as u64, + }); self.move_check.move_size_spans.push(span); } } diff --git a/compiler/rustc_monomorphize/src/partitioning.rs b/compiler/rustc_monomorphize/src/partitioning.rs index 2d9dbdbaec2..1c1e6164f2e 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -101,10 +101,10 @@ use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; use rustc_data_structures::sync; use rustc_data_structures::unord::{UnordMap, UnordSet}; +use rustc_hir::LangItem; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, DefIdSet, LOCAL_CRATE}; use rustc_hir::definitions::DefPathDataName; -use rustc_hir::LangItem; use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags; use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel}; @@ -116,8 +116,8 @@ use rustc_middle::ty::visit::TypeVisitableExt; use rustc_middle::ty::{self, InstanceKind, TyCtxt}; use rustc_middle::util::Providers; -use rustc_session::config::{DumpMonoStatsFormat, SwitchWithOptPath}; use rustc_session::CodegenUnits; +use rustc_session::config::{DumpMonoStatsFormat, SwitchWithOptPath}; use rustc_span::symbol::Symbol; use tracing::debug; @@ -255,8 +255,12 @@ fn place_mono_items<'tcx, I>(cx: &PartitioningCx<'_, 'tcx>, mono_items: I) -> Pl } 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_monomorphize/src/polymorphize.rs b/compiler/rustc_monomorphize/src/polymorphize.rs index c65ad9fa67e..e049fe99664 100644 --- a/compiler/rustc_monomorphize/src/polymorphize.rs +++ b/compiler/rustc_monomorphize/src/polymorphize.rs @@ -5,9 +5,9 @@ //! generic parameters are unused (and eventually, in what ways generic parameters are used - only //! for their size, offset of a field, etc.). +use rustc_hir::ConstContext; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; -use rustc_hir::ConstContext; use rustc_middle::mir::visit::{TyContext, Visitor}; use rustc_middle::mir::{self, Local, LocalDecl, Location}; use rustc_middle::query::Providers; diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index 6c9a6011144..520afbeb645 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -7,7 +7,7 @@ use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; use rustc_type_ir::visit::TypeVisitableExt as _; -use rustc_type_ir::{self as ty, elaborate, Interner, Upcast as _}; +use rustc_type_ir::{self as ty, Interner, Upcast as _, elaborate}; use tracing::{debug, instrument}; use crate::delegate::SolverDelegate; 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 a57338acaab..5c1a7852dc0 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 @@ -7,7 +7,7 @@ use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; -use rustc_type_ir::{self as ty, elaborate, Interner, Upcast as _}; +use rustc_type_ir::{self as ty, Interner, Upcast as _, elaborate}; use rustc_type_ir_macros::{TypeFoldable_Generic, TypeVisitable_Generic}; use tracing::instrument; @@ -507,11 +507,10 @@ 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/eval_ctxt/canonical.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/canonical.rs index 4d743c05190..252a9ed1a2e 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 @@ -22,9 +22,9 @@ use crate::resolve::EagerResolver; use crate::solve::eval_ctxt::NestedGoals; use crate::solve::{ - inspect, response_no_constraints_raw, CanonicalInput, CanonicalResponse, Certainty, EvalCtxt, - ExternalConstraintsData, Goal, MaybeCause, NestedNormalizationGoals, NoSolution, - PredefinedOpaquesData, QueryInput, QueryResult, Response, + CanonicalInput, CanonicalResponse, Certainty, EvalCtxt, ExternalConstraintsData, Goal, + MaybeCause, NestedNormalizationGoals, NoSolution, PredefinedOpaquesData, QueryInput, + QueryResult, Response, inspect, response_no_constraints_raw, }; trait ResponseT { 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 15b123ebdf9..12ad0724b5c 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 @@ -17,9 +17,9 @@ use crate::solve::inspect::{self, ProofTreeBuilder}; use crate::solve::search_graph::SearchGraph; use crate::solve::{ - CanonicalInput, CanonicalResponse, Certainty, Goal, GoalEvaluationKind, GoalSource, - NestedNormalizationGoals, NoSolution, PredefinedOpaquesData, QueryResult, SolverMode, - FIXPOINT_STEP_LIMIT, + CanonicalInput, CanonicalResponse, Certainty, FIXPOINT_STEP_LIMIT, Goal, GoalEvaluationKind, + GoalSource, NestedNormalizationGoals, NoSolution, PredefinedOpaquesData, QueryResult, + SolverMode, }; pub(super) mod canonical; @@ -497,10 +497,10 @@ fn evaluate_added_goals_step(&mut self) -> Result, NoSolution> // 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/eval_ctxt/probe.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/probe.rs index e459d5cbe58..be69a6e84ea 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/probe.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/probe.rs @@ -6,7 +6,7 @@ use crate::delegate::SolverDelegate; use crate::solve::assembly::Candidate; use crate::solve::{ - inspect, BuiltinImplSource, CandidateSource, EvalCtxt, NoSolution, QueryResult, + BuiltinImplSource, CandidateSource, EvalCtxt, NoSolution, QueryResult, inspect, }; pub(in crate::solve) struct ProbeCtxt<'me, 'a, D, I, F, T> diff --git a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs index 742d45de7d3..85474bf37b4 100644 --- a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs +++ b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs @@ -13,8 +13,8 @@ use crate::delegate::SolverDelegate; use crate::solve::eval_ctxt::canonical; use crate::solve::{ - inspect, CanonicalInput, Certainty, GenerateProofTree, Goal, GoalEvaluationKind, GoalSource, - QueryInput, QueryResult, + CanonicalInput, Certainty, GenerateProofTree, Goal, GoalEvaluationKind, GoalSource, QueryInput, + QueryResult, inspect, }; /// The core data structure when building proof trees. 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 17b6ec7e2bb..fc9c634942b 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 @@ -340,11 +340,10 @@ fn consider_builtin_fn_trait_candidates( 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); @@ -396,26 +395,21 @@ fn consider_builtin_async_fn_trait_candidates( .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( @@ -423,14 +417,10 @@ fn consider_builtin_async_fn_trait_candidates( 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 { @@ -556,11 +546,10 @@ fn consider_builtin_pointee_candidate( // 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) @@ -731,11 +720,10 @@ fn consider_builtin_coroutine_candidate( 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/search_graph.rs b/compiler/rustc_next_trait_solver/src/solve/search_graph.rs index 81c89fad8e8..e47cc03f5ad 100644 --- a/compiler/rustc_next_trait_solver/src/solve/search_graph.rs +++ b/compiler/rustc_next_trait_solver/src/solve/search_graph.rs @@ -1,13 +1,13 @@ use std::convert::Infallible; use std::marker::PhantomData; +use rustc_type_ir::Interner; use rustc_type_ir::inherent::*; use rustc_type_ir::search_graph::{self, PathKind}; use rustc_type_ir::solve::{CanonicalInput, Certainty, QueryResult}; -use rustc_type_ir::Interner; use super::inspect::ProofTreeBuilder; -use super::{has_no_inference_or_external_constraints, FIXPOINT_STEP_LIMIT}; +use super::{FIXPOINT_STEP_LIMIT, has_no_inference_or_external_constraints}; use crate::delegate::SolverDelegate; /// This type is never constructed. We only use it to implement `search_graph::Delegate` 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 73d9b5e8a4e..781ca127e15 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -6,7 +6,7 @@ use rustc_type_ir::inherent::*; use rustc_type_ir::lang_items::TraitSolverLangItem; use rustc_type_ir::visit::TypeVisitableExt as _; -use rustc_type_ir::{self as ty, elaborate, Interner, TraitPredicate, Upcast as _}; +use rustc_type_ir::{self as ty, Interner, TraitPredicate, Upcast as _, elaborate}; use tracing::{instrument, trace}; use crate::delegate::SolverDelegate; @@ -359,21 +359,18 @@ fn consider_builtin_async_fn_trait_candidates( )?; 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); // A built-in `AsyncFn` impl only holds if the output is sized. @@ -1027,11 +1024,9 @@ fn consider_builtin_struct_unsize( 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) @@ -1069,11 +1064,9 @@ fn consider_builtin_tuple_unsize( 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 e9fe2e6c1dd..20bcefd4fe1 100644 --- a/compiler/rustc_parse/src/errors.rs +++ b/compiler/rustc_parse/src/errors.rs @@ -1116,25 +1116,19 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for ExpectedIdentifier { fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> { let token_descr = TokenDescription::from_token(&self.token); - 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 - } - 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 + } + None => fluent::parse_expected_identifier_found_str, + }); diag.span(self.span); diag.arg("token", self.token); @@ -1176,23 +1170,17 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for ExpectedSemi { fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, G> { let token_descr = TokenDescription::from_token(&self.token); - 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 - } - 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, + None => fluent::parse_expected_semi_found_str, + }); diag.span(self.span); diag.arg("token", self.token); diff --git a/compiler/rustc_parse/src/lexer/diagnostics.rs b/compiler/rustc_parse/src/lexer/diagnostics.rs index 4d5d1ce099e..41108c91f2e 100644 --- a/compiler/rustc_parse/src/lexer/diagnostics.rs +++ b/compiler/rustc_parse/src/lexer/diagnostics.rs @@ -1,7 +1,7 @@ use rustc_ast::token::Delimiter; use rustc_errors::Diag; -use rustc_span::source_map::SourceMap; use rustc_span::Span; +use rustc_span::source_map::SourceMap; use super::UnmatchedDelim; diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 898c4779b08..3e46fc93fa4 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -8,10 +8,10 @@ use rustc_errors::{Applicability, Diag, DiagCtxtHandle, StashKey}; use rustc_lexer::unescape::{self, EscapeError, Mode}; use rustc_lexer::{Base, Cursor, DocStyle, LiteralKind, RawStrError}; +use rustc_session::lint::BuiltinLintDiag; use rustc_session::lint::builtin::{ RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, TEXT_DIRECTION_CODEPOINT_IN_COMMENT, }; -use rustc_session::lint::BuiltinLintDiag; use rustc_session::parse::ParseSess; use rustc_span::symbol::Symbol; use rustc_span::{BytePos, Pos, Span}; @@ -866,7 +866,7 @@ fn cook_mixed( } pub fn nfc_normalize(string: &str) -> Symbol { - use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; + use unicode_normalization::{IsNormalized, UnicodeNormalization, is_nfc_quick}; match is_nfc_quick(string.chars()) { IsNormalized::Yes => Symbol::intern(string), _ => { diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index c83d8bf4021..d35c9c7bae7 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -5,7 +5,7 @@ use rustc_span::symbol::kw; use super::diagnostics::{ - report_suspicious_mismatch_block, same_indentation_level, TokenTreeDiagInfo, + TokenTreeDiagInfo, report_suspicious_mismatch_block, same_indentation_level, }; use super::{StringReader, UnmatchedDelim}; use crate::Parser; diff --git a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs index efa53f0962b..2e066f0179c 100644 --- a/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs +++ b/compiler/rustc_parse/src/lexer/unescape_error_reporting.rs @@ -40,8 +40,8 @@ pub(crate) fn emit_unescape_error( dcx.emit_err(UnescapeError::InvalidUnicodeEscape { span: err_span, surrogate: false }) } EscapeError::MoreThanOneChar => { - use unicode_normalization::char::is_combining_mark; use unicode_normalization::UnicodeNormalization; + use unicode_normalization::char::is_combining_mark; let mut sugg = None; let mut note = None; diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index 788bb732ef7..f7a8b8780ed 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -18,7 +18,7 @@ use rustc_ast as ast; use rustc_ast::tokenstream::TokenStream; -use rustc_ast::{token, AttrItem, Attribute, MetaItem}; +use rustc_ast::{AttrItem, Attribute, MetaItem, token}; use rustc_ast_pretty::pprust; use rustc_data_structures::sync::Lrc; use rustc_errors::{Diag, FatalError, PResult}; @@ -29,7 +29,7 @@ #[macro_use] pub mod parser; -use parser::{make_unclosed_delims_error, Parser}; +use parser::{Parser, make_unclosed_delims_error}; pub mod lexer; pub mod validate_attr; diff --git a/compiler/rustc_parse/src/parser/attr_wrapper.rs b/compiler/rustc_parse/src/parser/attr_wrapper.rs index 6a241be0a15..8bd615e6d79 100644 --- a/compiler/rustc_parse/src/parser/attr_wrapper.rs +++ b/compiler/rustc_parse/src/parser/attr_wrapper.rs @@ -10,7 +10,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::PResult; use rustc_session::parse::ParseSess; -use rustc_span::{sym, Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span, sym}; use super::{ Capturing, FlatToken, ForceCollect, NodeRange, NodeReplacement, Parser, ParserRange, @@ -108,7 +108,7 @@ struct LazyAttrTokenStreamImpl { start_token: (Token, Spacing), cursor_snapshot: TokenCursor, num_calls: u32, - break_last_token: bool, + break_last_token: u32, node_replacements: Box<[NodeReplacement]>, } @@ -339,17 +339,20 @@ pub(super) fn collect_tokens( let parser_replacements_end = self.capture_state.parser_replacements.len(); assert!( - !(self.break_last_token && matches!(capture_trailing, Trailing::Yes)), - "Cannot set break_last_token and have trailing token" + !(self.break_last_token > 0 && matches!(capture_trailing, Trailing::Yes)), + "Cannot have break_last_token > 0 and have trailing token" ); + assert!(self.break_last_token <= 2, "cannot break token more than twice"); let end_pos = self.num_bump_calls + capture_trailing as u32 - // If we 'broke' the last token (e.g. breaking a '>>' token to two '>' tokens), then - // extend the range of captured tokens to include it, since the parser was not actually - // bumped past it. When the `LazyAttrTokenStream` gets converted into an - // `AttrTokenStream`, we will create the proper token. - + self.break_last_token as u32; + // If we "broke" the last token (e.g. breaking a `>>` token once into `>` + `>`, or + // breaking a `>>=` token twice into `>` + `>` + `=`), then extend the range of + // captured tokens to include it, because the parser was not actually bumped past it. + // (Even if we broke twice, it was still just one token originally, hence the `1`.) + // When the `LazyAttrTokenStream` gets converted into an `AttrTokenStream`, we will + // rebreak that final token once or twice. + + if self.break_last_token == 0 { 0 } else { 1 }; let num_calls = end_pos - collect_pos.start_pos; @@ -425,7 +428,7 @@ pub(super) fn collect_tokens( // for the `#[cfg]` and/or `#[cfg_attr]` attrs. This allows us to run // eager cfg-expansion on the captured token stream. if definite_capture_mode { - assert!(!self.break_last_token, "Should not have unglued last token with cfg attr"); + assert!(self.break_last_token == 0, "Should not have unglued last token with cfg attr"); // What is the status here when parsing the example code at the top of this method? // @@ -471,7 +474,7 @@ pub(super) fn collect_tokens( /// close delims. fn make_attr_token_stream( iter: impl Iterator, - break_last_token: bool, + break_last_token: u32, ) -> AttrTokenStream { #[derive(Debug)] struct FrameData { @@ -485,10 +488,10 @@ struct FrameData { 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()); @@ -513,18 +516,17 @@ struct FrameData { } } - if break_last_token { + if break_last_token > 0 { let last_token = stack_top.inner.pop().unwrap(); if let AttrTokenTree::Token(last_token, spacing) = last_token { - let unglued_first = last_token.kind.break_two_token_op().unwrap().0; + let (unglued, _) = last_token.kind.break_two_token_op(break_last_token).unwrap(); - // An 'unglued' token is always two ASCII characters + // Tokens are always ASCII chars, so we can use byte arithmetic here. let mut first_span = last_token.span.shrink_to_lo(); - first_span = first_span.with_hi(first_span.lo() + rustc_span::BytePos(1)); + first_span = + first_span.with_hi(first_span.lo() + rustc_span::BytePos(break_last_token)); - stack_top - .inner - .push(AttrTokenTree::Token(Token::new(unglued_first, first_span), spacing)); + stack_top.inner.push(AttrTokenTree::Token(Token::new(unglued, first_span), spacing)); } else { panic!("Unexpected last token {last_token:?}") } diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index fd488cf1d31..f32307f6ed4 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -15,15 +15,15 @@ use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashSet; use rustc_errors::{ - pluralize, Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, PErr, PResult, - Subdiagnostic, Suggestions, + Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, FatalError, PErr, PResult, Subdiagnostic, + Suggestions, pluralize, }; use rustc_session::errors::ExprParenthesesNeeded; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::source_map::Spanned; -use rustc_span::symbol::{kw, sym, AllKeywords, Ident}; -use rustc_span::{BytePos, Span, SpanSnippetError, Symbol, DUMMY_SP}; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{AllKeywords, Ident, kw, sym}; +use rustc_span::{BytePos, DUMMY_SP, Span, SpanSnippetError, Symbol}; +use thin_vec::{ThinVec, thin_vec}; use tracing::{debug, trace}; use super::pat::Expected; @@ -721,15 +721,12 @@ fn is_ident_eq_keyword(found: &TokenKind, expected: &TokenType) -> bool { 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, ); @@ -1936,14 +1933,13 @@ pub(super) fn unexpected_try_recover(&mut self, t: &TokenKind) -> PResult<'a, Re (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(); @@ -2864,27 +2860,25 @@ pub(crate) fn maybe_recover_colon_colon_in_pat_typo( 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 f19cba4c1bf..0ac6133e828 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -10,25 +10,25 @@ use rustc_ast::token::{self, Delimiter, Token, TokenKind}; use rustc_ast::util::case::Case; use rustc_ast::util::classify; -use rustc_ast::util::parser::{prec_let_scrutinee_needs_par, AssocOp, Fixity}; -use rustc_ast::visit::{walk_expr, Visitor}; +use rustc_ast::util::parser::{AssocOp, Fixity, prec_let_scrutinee_needs_par}; +use rustc_ast::visit::{Visitor, walk_expr}; use rustc_ast::{ self as ast, AnonConst, Arm, AttrStyle, AttrVec, BinOp, BinOpKind, BlockCheckMode, CaptureBy, - ClosureBinder, Expr, ExprField, ExprKind, FnDecl, FnRetTy, Label, MacCall, MetaItemLit, - Movability, Param, RangeLimits, StmtKind, Ty, TyKind, UnOp, DUMMY_NODE_ID, + ClosureBinder, DUMMY_NODE_ID, Expr, ExprField, ExprKind, FnDecl, FnRetTy, Label, MacCall, + MetaItemLit, Movability, Param, RangeLimits, StmtKind, Ty, TyKind, UnOp, }; use rustc_ast_pretty::pprust; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{Applicability, Diag, PResult, StashKey, Subdiagnostic}; use rustc_lexer::unescape::unescape_char; use rustc_macros::Subdiagnostic; -use rustc_session::errors::{report_lit_error, ExprParenthesesNeeded}; -use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP; +use rustc_session::errors::{ExprParenthesesNeeded, report_lit_error}; use rustc_session::lint::BuiltinLintDiag; +use rustc_session::lint::builtin::BREAK_WITH_LABEL_AND_LOOP; use rustc_span::source_map::{self, Spanned}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use rustc_span::{BytePos, ErrorGuaranteed, Pos, Span}; -use thin_vec::{thin_vec, ThinVec}; +use thin_vec::{ThinVec, thin_vec}; use tracing::instrument; use super::diagnostics::SnapshotParser; @@ -811,20 +811,17 @@ fn parse_assoc_op_cast( // 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<'_>| { @@ -2844,10 +2841,13 @@ fn parse_expr_for(&mut self, opt_label: Option