diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index ec76a1a42ef09..8612a40923a8d 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 2082ec9ef455f..33ea0f53cf132 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/Cargo.lock b/Cargo.lock index e973d7f9a2ae0..47ad7ab3e9814 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2177,9 +2177,9 @@ dependencies = [ [[package]] name = "memchr" -version = "2.5.0" +version = "2.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" [[package]] name = "memmap2" diff --git a/compiler/rustc_abi/src/layout.rs b/compiler/rustc_abi/src/layout.rs index 01593d34c9788..620a051eeb7dd 100644 --- a/compiler/rustc_abi/src/layout.rs +++ b/compiler/rustc_abi/src/layout.rs @@ -999,8 +999,8 @@ impl LayoutCalculator { 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 904c5933a185a..fa7c98a7fa0cc 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/Cargo.toml b/compiler/rustc_ast/Cargo.toml index d33f9666b484c..34c612dac692b 100644 --- a/compiler/rustc_ast/Cargo.toml +++ b/compiler/rustc_ast/Cargo.toml @@ -4,10 +4,9 @@ version = "0.0.0" edition = "2021" [dependencies] -# FIXME: bumping memchr to 2.7.1 causes linker errors in MSVC thin-lto # tidy-alphabetical-start bitflags = "2.4.1" -memchr = "=2.5.0" +memchr = "2.7.4" rustc_ast_ir = { path = "../rustc_ast_ir" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_index = { path = "../rustc_index" } diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index d49265de202ac..37f429cce44d7 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 @@ impl ParenthesizedArgs { } } -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)] diff --git a/compiler/rustc_ast/src/attr/mod.rs b/compiler/rustc_ast/src/attr/mod.rs index 94a00ab1a047e..124d0acfa4912 100644 --- a/compiler/rustc_ast/src/attr/mod.rs +++ b/compiler/rustc_ast/src/attr/mod.rs @@ -4,15 +4,15 @@ use std::iter; 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 53276e0847a74..45c4caca6e9ee 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 1723501d0fec0..bee7dfb61da87 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 e72d32d9b752d..d5900d83e4d1a 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 1bef51aa73f7b..104f84f26e0af 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -13,10 +13,10 @@ use std::panic; 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 a0082a41713be..1d6abbef06c95 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; +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; -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_span::symbol::{kw, sym}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use crate::ast; use crate::ptr::P; @@ -385,35 +385,41 @@ impl 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 fc1dd2caf681a..d5c2bc1c7f63c 100644 --- a/compiler/rustc_ast/src/tokenstream.rs +++ b/compiler/rustc_ast/src/tokenstream.rs @@ -20,7 +20,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; 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 3bd2a80d361ee..498df5a71441b 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 bae7ad93f90fa..9f9c3d8c39239 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 11867c39e02bc..88cdb2ec36397 100644 --- a/compiler/rustc_ast_lowering/src/asm.rs +++ b/compiler/rustc_ast_lowering/src/asm.rs @@ -8,9 +8,10 @@ use rustc_hir as hir; 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 @@ use super::errors::{ 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> { diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index 97483e85f77dd..3b85f1737bdd9 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -46,8 +46,8 @@ use rustc_errors::ErrorGuaranteed; 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 d828c9856b954..52372bbf991c9 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -4,14 +4,14 @@ use rustc_ast::ptr::P as AstP; 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 @@ use super::{ 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>] { @@ -725,18 +725,15 @@ impl<'hir> LoweringContext<'_, 'hir> { 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 8c742d2aaf436..653116e1fe00d 100644 --- a/compiler/rustc_ast_lowering/src/format.rs +++ b/compiler/rustc_ast_lowering/src/format.rs @@ -6,8 +6,8 @@ use rustc_ast::*; 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 f90a0612db692..e77c0fb3a3ed3 100644 --- a/compiler/rustc_ast_lowering/src/index.rs +++ b/compiler/rustc_ast_lowering/src/index.rs @@ -6,7 +6,7 @@ use rustc_hir::*; 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 73c604bf28a40..7bb3b2fa29095 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -3,17 +3,17 @@ use rustc_ast::visit::AssocCtxt; 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 @@ impl<'hir> LoweringContext<'_, 'hir> { ); this.arena.alloc(this.ty(span, hir::TyKind::Err(guar))) } - Some(ty) => this.lower_ty( - ty, - ImplTraitContext::OpaqueTy { - origin: hir::OpaqueTyOrigin::TyAlias { - parent: this.local_def_id(id), - in_assoc_ty: false, - }, - 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 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::ImplItemKind::Type(ty) } Some(ty) => { - let ty = this.lower_ty( - ty, - ImplTraitContext::OpaqueTy { - origin: hir::OpaqueTyOrigin::TyAlias { - parent: this.local_def_id(i.id), - in_assoc_ty: true, - }, - 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 @@ impl<'hir> LoweringContext<'_, 'hir> { pub(super) fn lower_const_body(&mut self, span: Span, expr: Option<&Expr>) -> hir::BodyId { self.lower_body(|this| { - ( - &[], - match expr { - Some(expr) => this.lower_expr_mut(expr), - None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")), - }, - ) + (&[], match expr { + Some(expr) => this.lower_expr_mut(expr), + None => this.expr_err(span, this.dcx().span_delayed_bug(span, "no block")), + }) }) } @@ -1515,10 +1506,10 @@ impl<'hir> LoweringContext<'_, 'hir> { 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 @@ impl<'hir> LoweringContext<'_, 'hir> { 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 3f48fe67dbba9..c6cb7aa7dd5c2 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::stable_hasher::{HashStable, StableHasher}; 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_macros::extension; 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}; diff --git a/compiler/rustc_ast_lowering/src/lifetime_collector.rs b/compiler/rustc_ast_lowering/src/lifetime_collector.rs index 76c957afa5461..1e82ba5db8a2a 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_data_structures::fx::FxIndexSet; 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 584d94ebe2df1..760f84564f1a2 100644 --- a/compiler/rustc_ast_lowering/src/pat.rs +++ b/compiler/rustc_ast_lowering/src/pat.rs @@ -3,9 +3,9 @@ use rustc_ast::*; 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 03c8097e4c351..e60488fdc8c74 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 93881f5ed4261..229d04f8de2fd 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -21,21 +21,21 @@ use std::ops::{Deref, DerefMut}; 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 cfc534acd982e..614a99a6e1960 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 c61640de6f799..e22e99f6e4d65 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 7559b181f7d41..a1c07bb07e42a 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 cfcc28ba76fdd..726ceebe3c524 100644 --- a/compiler/rustc_ast_pretty/src/pprust/mod.rs +++ b/compiler/rustc_ast_pretty/src/pprust/mod.rs @@ -7,7 +7,7 @@ use std::borrow::Cow; 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 3b1449d9a9113..7e07ccf28a0cb 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::tokenstream::{Spacing, TokenStream, TokenTree}; 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 b13c89c435da7..893bfaf8f712e 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::classify; 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 c9baca72485ef..50fd12a4e8b68 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 85a0b3b202292..8217b6df5b470 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 3fefc523f8883..01e5dff34b7a6 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 309049b98f0e2..762ebc47ca9d0 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -4,21 +4,21 @@ use std::num::NonZero; 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}; @@ -153,7 +153,7 @@ pub enum StabilityLevel { } /// Rust release in which a feature is stabilized. -#[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, Hash)] +#[derive(Encodable, Decodable, PartialEq, Copy, Clone, Debug, Eq, PartialOrd, Ord, Hash)] #[derive(HashStable_Generic)] pub enum StableSince { Version(RustcVersion), diff --git a/compiler/rustc_attr/src/lib.rs b/compiler/rustc_attr/src/lib.rs index 0dad637238982..bb207c5c9526c 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 234a0ef28a269..959a5a4bba752 100644 --- a/compiler/rustc_attr/src/session_diagnostics.rs +++ b/compiler/rustc_attr/src/session_diagnostics.rs @@ -6,7 +6,7 @@ use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, EmissionGuar 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 fbda44550a19c..a8ade54732f85 100644 --- a/compiler/rustc_borrowck/src/borrow_set.rs +++ b/compiler/rustc_borrowck/src/borrow_set.rs @@ -4,15 +4,15 @@ use std::ops::Index; 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 3a7e407f3e7a6..30e94b0bec708 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 8f560635cb339..c994c4dc1e484 100644 --- a/compiler/rustc_borrowck/src/consumers.rs +++ b/compiler/rustc_borrowck/src/consumers.rs @@ -8,12 +8,12 @@ use rustc_middle::mir::{Body, Promoted}; 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 5e1043ec81798..4af5a10f5812d 100644 --- a/compiler/rustc_borrowck/src/dataflow.rs +++ b/compiler/rustc_borrowck/src/dataflow.rs @@ -12,7 +12,7 @@ use rustc_mir_dataflow::impls::{EverInitializedPlaces, MaybeUninitializedPlaces} 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 ee28e556cbc34..40a6d506ffa63 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 @@ use rustc_middle::ty::{ 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 @@ trait TypeOpInfo<'tcx> { return; }; - 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 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 + }; debug!(?placeholder_region); diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index c7a5d516ad72d..60ea0d1edbf4e 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -11,10 +11,10 @@ use hir::{ClosureKind, Path}; 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::mir::{ }; 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::explain_borrow::{BorrowExplanation, LaterUseKind}; 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 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { span, desired_action.as_noun(), partially_str, - self.describe_place_with_options( - moved_place, - DescribePlaceOpt { including_downcast: true, including_tuple_field: true }, - ), + self.describe_place_with_options(moved_place, DescribePlaceOpt { + including_downcast: true, + including_tuple_field: true, + }), ); let reinit_spans = maybe_reinitialized_locations @@ -266,10 +266,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } } - 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 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { } let spans: Vec<_> = spans_set.into_iter().collect(); - let (name, desc) = match self.describe_place_with_options( - moved_place, - DescribePlaceOpt { including_downcast: true, including_tuple_field: true }, - ) { + let (name, desc) = match self.describe_place_with_options(moved_place, DescribePlaceOpt { + including_downcast: true, + including_tuple_field: true, + }) { Some(name) => (format!("`{name}`"), format!("`{name}` ")), None => ("the variable".to_string(), String::new()), }; - let path = match self.describe_place_with_options( - used_place, - DescribePlaceOpt { including_downcast: true, including_tuple_field: true }, - ) { + let path = match self.describe_place_with_options(used_place, DescribePlaceOpt { + including_downcast: true, + including_tuple_field: true, + }) { Some(name) => format!("`{name}`"), None => "value".to_string(), }; diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index d9b5fd8b5c182..31a5d451ff6b6 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::mir::{ }; 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}; @@ -333,7 +333,11 @@ impl<'tcx> BorrowExplanation<'tcx> { } } - if let ConstraintCategory::Cast { unsize_to: Some(unsize_ty) } = category { + if let ConstraintCategory::Cast { + is_implicit_coercion: true, + unsize_to: Some(unsize_ty), + } = category + { self.add_object_lifetime_default_note(tcx, err, unsize_ty); } self.add_lifetime_bound_suggestion_to_diagnostic(err, &category, span, region_name); @@ -740,7 +744,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { // If we see an unsized cast, then if it is our data we should check // whether it is being cast to a trait object. Rvalue::Cast( - CastKind::PointerCoercion(PointerCoercion::Unsize), + CastKind::PointerCoercion(PointerCoercion::Unsize, _), operand, ty, ) => { diff --git a/compiler/rustc_borrowck/src/diagnostics/mod.rs b/compiler/rustc_borrowck/src/diagnostics/mod.rs index e52ddfa3eb543..801c7af2de701 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mod.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mod.rs @@ -15,22 +15,22 @@ use rustc_middle::mir::{ }; 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 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { /// End-user visible description of `place` if one can be found. /// If the place is a temporary for instance, `None` will be returned. pub(super) fn describe_place(&self, place_ref: PlaceRef<'tcx>) -> Option { - self.describe_place_with_options( - place_ref, - DescribePlaceOpt { including_downcast: false, including_tuple_field: true }, - ) + self.describe_place_with_options(place_ref, DescribePlaceOpt { + including_downcast: false, + including_tuple_field: true, + }) } /// End-user visible description of `place` if one can be found. If the place is a temporary diff --git a/compiler/rustc_borrowck/src/diagnostics/move_errors.rs b/compiler/rustc_borrowck/src/diagnostics/move_errors.rs index 5a9eba34d07f1..98417e8c7a3f4 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_span::{BytePos, ExpnKind, MacroKind, Span}; 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 2bbafb0163ee0..20ecc665b1eed 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -14,8 +14,8 @@ use rustc_middle::mir::{ 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 tracing::debug; 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 57c3a0843a694..39175b406a4aa 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 @@ use crate::session_diagnostics::{ 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 { @@ -47,7 +47,8 @@ impl<'tcx> ConstraintDescription for ConstraintCategory<'tcx> { ConstraintCategory::Yield => "yielding this value ", ConstraintCategory::UseAsConst => "using this value as a constant ", ConstraintCategory::UseAsStatic => "using this value as a static ", - ConstraintCategory::Cast { .. } => "cast ", + ConstraintCategory::Cast { is_implicit_coercion: false, .. } => "cast ", + ConstraintCategory::Cast { is_implicit_coercion: true, .. } => "coercion ", ConstraintCategory::CallArgument(_) => "argument ", ConstraintCategory::TypeAnnotation => "type annotation ", ConstraintCategory::ClosureBounds => "closure body ", @@ -1108,15 +1109,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> { let closure_ty = Ty::new_closure( tcx, closure_def_id.to_def_id(), - ty::ClosureArgs::new( - tcx, - ty::ClosureArgsParts { - parent_args: args.parent_args(), - closure_kind_ty: args.kind_ty(), - tupled_upvars_ty: args.tupled_upvars_ty(), - closure_sig_as_fn_ptr_ty, - }, - ) + ty::ClosureArgs::new(tcx, ty::ClosureArgsParts { + parent_args: args.parent_args(), + closure_kind_ty: args.kind_ty(), + tupled_upvars_ty: args.tupled_upvars_ty(), + closure_sig_as_fn_ptr_ty, + }) .args, ); diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 58fcda2571cc0..2f22e1532c196 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_hir::def::{DefKind, Res}; 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 2a4fa1e00191c..bda7024126732 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 94b5044857689..713452796c602 100644 --- a/compiler/rustc_borrowck/src/facts.rs +++ b/compiler/rustc_borrowck/src/facts.rs @@ -10,8 +10,8 @@ use rustc_middle::mir::Local; 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 58e730307492e..733fabe557e6b 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -37,13 +37,13 @@ use rustc_middle::mir::*; 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 borrow_set::{BorrowData, BorrowSet}; 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 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> { match elem { ProjectionElem::Deref => match place_ty.ty.kind() { ty::Ref(..) | ty::RawPtr(..) => { - self.move_errors.push(MoveError::new( - place, - location, - BorrowedContent { - target_place: place_ref.project_deeper(&[elem], tcx), - }, - )); + self.move_errors.push(MoveError::new(place, location, BorrowedContent { + target_place: place_ref.project_deeper(&[elem], tcx), + })); return; } ty::Adt(adt, _) => { diff --git a/compiler/rustc_borrowck/src/nll.rs b/compiler/rustc_borrowck/src/nll.rs index 8575eb9e9a52d..d85af52b01e36 100644 --- a/compiler/rustc_borrowck/src/nll.rs +++ b/compiler/rustc_borrowck/src/nll.rs @@ -9,17 +9,17 @@ use polonius_engine::{Algorithm, Output}; 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::location::LocationTable; 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 f387d5cfedcb9..1ba41cd524455 100644 --- a/compiler/rustc_borrowck/src/path_utils.rs +++ b/compiler/rustc_borrowck/src/path_utils.rs @@ -5,7 +5,7 @@ use rustc_target::abi::FieldIdx; 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 d6bb006cd7e00..c62ea870acfe9 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_mir_dataflow::points::DenseLocationMap; 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::reverse_sccs::ReverseSccGraph; 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 f97f3dfe29f6a..3cf21d4a36b83 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 @@ impl<'tcx> RegionInferenceContext<'tcx> { // FIXME(oli-obk): collect multiple spans for better diagnostics down the road. prev.span = prev.span.substitute_dummy(concrete_type.span); } else { - result.insert( - opaque_type_key.def_id, - OpaqueHiddenType { ty, span: concrete_type.span }, - ); + result.insert(opaque_type_key.def_id, OpaqueHiddenType { + ty, + span: concrete_type.span, + }); } // Check that all opaque types have the same region parameters if they have the same diff --git a/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs b/compiler/rustc_borrowck/src/region_infer/reverse_sccs.rs index 3cc5fa4404e35..cfd5a92787ed2 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; 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 30dc062ae7cea..b95fe5b50282e 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::fmt::Debug; 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 b6c6960d4ca00..627444a4ce5b8 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 4b15ce8873d37..0c6f8cd7b5bfe 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_infer::infer::canonical::Canonical; 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 0f1d79a2c3530..fc1600ea4a611 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::region_constraints::{GenericKind, VerifyBound}; 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 c711190cb97ab..6977fed59ed9d 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_hir::def::DefKind; 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 rustc_trait_selection::traits::query::type_op::{self, TypeOp}; 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 56f8464628c7b..141f251244bf9 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 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let output_ty = Ty::new_coroutine( self.tcx(), self.tcx().coroutine_for_closure(mir_def_id), - ty::CoroutineArgs::new( - self.tcx(), - ty::CoroutineArgsParts { - parent_args: args.parent_args(), - kind_ty: Ty::from_coroutine_closure_kind(self.tcx(), args.kind()), - return_ty: user_provided_sig.output(), - tupled_upvars_ty, - // For async closures, none of these can be annotated, so just fill - // them with fresh ty vars. - resume_ty: next_ty_var(), - yield_ty: next_ty_var(), - witness: next_ty_var(), - }, - ) + ty::CoroutineArgs::new(self.tcx(), ty::CoroutineArgsParts { + parent_args: args.parent_args(), + kind_ty: Ty::from_coroutine_closure_kind(self.tcx(), args.kind()), + return_ty: user_provided_sig.output(), + tupled_upvars_ty, + // For async closures, none of these can be annotated, so just fill + // them with fresh ty vars. + resume_ty: next_ty_var(), + yield_ty: next_ty_var(), + witness: next_ty_var(), + }) .args, ); diff --git a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs index a73467824de5e..d4900d21f8f5a 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::mir::{Body, Local, Location, SourceInfo}; 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 1ac2757345390..8cbe3ac67016b 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_infer::infer::outlives::for_liveness; 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 3e5a6ad85fa56..16e51e82f85e0 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -31,20 +31,20 @@ use rustc_middle::ty::{ 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::diagnostics::UniverseInfo; 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 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } &Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, ty) => { - let trait_ref = ty::TraitRef::new( - tcx, - tcx.require_lang_item(LangItem::Sized, Some(span)), - [ty], - ); + let trait_ref = + ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Sized, Some(span)), [ + ty, + ]); self.prove_trait_ref( trait_ref, @@ -1961,11 +1960,10 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { Rvalue::ShallowInitBox(operand, ty) => { self.check_operand(operand, location); - let trait_ref = ty::TraitRef::new( - tcx, - tcx.require_lang_item(LangItem::Sized, Some(span)), - [*ty], - ); + let trait_ref = + ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Sized, Some(span)), [ + *ty, + ]); self.prove_trait_ref( trait_ref, @@ -1977,8 +1975,9 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { Rvalue::Cast(cast_kind, op, ty) => { self.check_operand(op, location); - match cast_kind { - CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer) => { + match *cast_kind { + CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, coercion_source) => { + let is_implicit_coercion = coercion_source == CoercionSource::Implicit; let src_sig = op.ty(body, tcx).fn_sig(tcx); // HACK: This shouldn't be necessary... We can remove this when we actually @@ -2009,7 +2008,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { self.prove_predicate( ty::ClauseKind::WellFormed(src_ty.into()), location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ); let src_ty = self.normalize(src_ty, location); @@ -2017,7 +2016,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { src_ty, *ty, location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ) { span_mirbug!( self, @@ -2038,7 +2037,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { self.prove_predicate( ty::ClauseKind::WellFormed(src_ty.into()), location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ); // The type that we see in the fcx is like @@ -2051,7 +2050,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { src_ty, *ty, location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ) { span_mirbug!( self, @@ -2064,19 +2063,23 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } } - CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(safety)) => { + CastKind::PointerCoercion( + PointerCoercion::ClosureFnPointer(safety), + coercion_source, + ) => { let sig = match op.ty(body, tcx).kind() { ty::Closure(_, args) => args.as_closure().sig(), _ => bug!(), }; let ty_fn_ptr_from = - Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, *safety)); + Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, safety)); + let is_implicit_coercion = coercion_source == CoercionSource::Implicit; if let Err(terr) = self.sub_types( ty_fn_ptr_from, *ty, location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ) { span_mirbug!( self, @@ -2089,7 +2092,10 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } } - CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer) => { + CastKind::PointerCoercion( + PointerCoercion::UnsafeFnPointer, + coercion_source, + ) => { let fn_sig = op.ty(body, tcx).fn_sig(tcx); // The type that we see in the fcx is like @@ -2101,11 +2107,12 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig); + let is_implicit_coercion = coercion_source == CoercionSource::Implicit; if let Err(terr) = self.sub_types( ty_fn_ptr_from, *ty, location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ) { span_mirbug!( self, @@ -2118,7 +2125,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } } - CastKind::PointerCoercion(PointerCoercion::Unsize) => { + CastKind::PointerCoercion(PointerCoercion::Unsize, coercion_source) => { let &ty = ty; let trait_ref = ty::TraitRef::new( tcx, @@ -2126,22 +2133,21 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { [op.ty(body, tcx), ty], ); + let is_implicit_coercion = coercion_source == CoercionSource::Implicit; + let unsize_to = tcx.fold_regions(ty, |r, _| { + if let ty::ReVar(_) = r.kind() { tcx.lifetimes.re_erased } else { r } + }); self.prove_trait_ref( trait_ref, location.to_locations(), ConstraintCategory::Cast { - unsize_to: Some(tcx.fold_regions(ty, |r, _| { - if let ty::ReVar(_) = r.kind() { - tcx.lifetimes.re_erased - } else { - r - } - })), + is_implicit_coercion, + unsize_to: Some(unsize_to), }, ); } - CastKind::DynStar => { + CastKind::PointerCoercion(PointerCoercion::DynStar, coercion_source) => { // get the constraints from the target type (`dyn* Clone`) // // apply them to prove that the source type `Foo` implements `Clone` etc @@ -2152,12 +2158,13 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let self_ty = op.ty(body, tcx); + let is_implicit_coercion = coercion_source == CoercionSource::Implicit; self.prove_predicates( existential_predicates .iter() .map(|predicate| predicate.with_self_ty(tcx, self_ty)), location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ); let outlives_predicate = tcx.mk_predicate(Binder::dummy( @@ -2168,11 +2175,14 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { self.prove_predicate( outlives_predicate, location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ); } - CastKind::PointerCoercion(PointerCoercion::MutToConstPointer) => { + CastKind::PointerCoercion( + PointerCoercion::MutToConstPointer, + coercion_source, + ) => { let ty::RawPtr(ty_from, hir::Mutability::Mut) = op.ty(body, tcx).kind() else { span_mirbug!(self, rvalue, "unexpected base type for cast {:?}", ty,); @@ -2182,11 +2192,12 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { span_mirbug!(self, rvalue, "unexpected target type for cast {:?}", ty,); return; }; + let is_implicit_coercion = coercion_source == CoercionSource::Implicit; if let Err(terr) = self.sub_types( *ty_from, *ty_to, location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ) { span_mirbug!( self, @@ -2199,7 +2210,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } } - CastKind::PointerCoercion(PointerCoercion::ArrayToPointer) => { + CastKind::PointerCoercion(PointerCoercion::ArrayToPointer, coercion_source) => { let ty_from = op.ty(body, tcx); let opt_ty_elem_mut = match ty_from.kind() { @@ -2244,11 +2255,12 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { return; } + let is_implicit_coercion = coercion_source == CoercionSource::Implicit; if let Err(terr) = self.sub_types( *ty_elem, *ty_to, location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { is_implicit_coercion, unsize_to: None }, ) { span_mirbug!( self, @@ -2429,7 +2441,10 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { src_obj, dst_obj, location.to_locations(), - ConstraintCategory::Cast { unsize_to: None }, + ConstraintCategory::Cast { + is_implicit_coercion: false, + unsize_to: None, + }, ) .unwrap(); } diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index 71892a67ffcc7..bf079e813f16b 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 @@ use rustc_infer::infer::relate::{ 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 c3edbcb50cc3d..fa44ffcd17dd0 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -20,9 +20,9 @@ use std::iter; 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::symbol::{kw, sym}; 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 @@ impl<'cx, 'tcx> UniversalRegionsBuilder<'cx, 'tcx> { let ty = tcx .typeck(self.mir_def) .node_type(tcx.local_def_id_to_hir_id(self.mir_def)); - let args = InlineConstArgs::new( - tcx, - InlineConstArgsParts { parent_args: identity_args, ty }, - ) + let args = InlineConstArgs::new(tcx, InlineConstArgsParts { + parent_args: identity_args, + ty, + }) .args; let args = self.infcx.replace_free_regions_with_nll_infer_vars(FR, args); DefiningTy::InlineConst(self.mir_def.to_def_id(), args) diff --git a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs index 1df2812e0c887..0caad997b9df1 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 @@ use rustc_ast::{ 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 0e1ec3b3cad1b..94e40da8c9297 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 99f433c0851ad..714493509859a 100644 --- a/compiler/rustc_builtin_macros/src/assert.rs +++ b/compiler/rustc_builtin_macros/src/assert.rs @@ -3,13 +3,13 @@ mod context; 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 2cd5b9d68a012..70fa4d00c0f39 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::ptr::P; 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 3d3bd3aea059c..23578781a833f 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_ast as ast; 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 4b05c144d37d7..b686a8cf935ca 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 as ast; 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_expand::configure; 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 66fa74da60d9f..6afd8c4b43b9a 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 196bf906dc028..456f2b9ab31de 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 13729a9d250fe..b459cc3007d37 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 e8704bc2f639d..4be2d209ae785 100644 --- a/compiler/rustc_builtin_macros/src/derive.rs +++ b/compiler/rustc_builtin_macros/src/derive.rs @@ -6,7 +6,7 @@ use rustc_expand::base::{ 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 22beca4ea9a06..dde696fca610b 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 a5e1217479641..bd6f4eb8d9945 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 705c41175e70f..433cbfaa6cb08 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 f6299589e0f3e..ae1e5f4a2198c 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 a51f98f5396ce..99a9832505327 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 57d9c07615044..06a598cf3b0ef 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 89300a36d1b56..686424770fc58 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 afc55ddd2302e..652e6f7740f9f 100644 --- a/compiler/rustc_builtin_macros/src/deriving/default.rs +++ b/compiler/rustc_builtin_macros/src/deriving/default.rs @@ -2,12 +2,12 @@ use core::ops::ControlFlow; 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 9c26d05f811d1..5c7583f2a77d8 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 289e92a69b2c0..82baaca9a4641 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::cell::RefCell; 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_ast::{ }; 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 @@ impl<'a> MethodDef<'a> { let discr_let_stmts: ThinVec<_> = iter::zip(&discr_idents, &selflike_args) .map(|(&ident, selflike_arg)| { - let variant_value = deriving::call_intrinsic( - cx, - span, - sym::discriminant_value, - thin_vec![selflike_arg.clone()], - ); + let variant_value = + deriving::call_intrinsic(cx, span, sym::discriminant_value, thin_vec![ + selflike_arg.clone() + ]); cx.stmt_let(span, false, ident, variant_value) }) .collect(); diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs b/compiler/rustc_builtin_macros/src/deriving/generic/ty.rs index 42855e255a806..b118cbfbd913b 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 4fa6686b7b34b..2d1f5b70f7746 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 32936ac183df9..d5ee5e430d5d0 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 as ast; 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 bc41d33a609e3..12749e87dcbcc 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_ast::{ 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 cc385bade4703..c4164a7db9a47 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::token::Delimiter; 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 1a4fc65f0a8a6..25583cda5a20d 100644 --- a/compiler/rustc_builtin_macros/src/env.rs +++ b/compiler/rustc_builtin_macros/src/env.rs @@ -10,8 +10,8 @@ use rustc_ast::token::{self, LitKind}; 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 f99530cad18f9..9501e93bad534 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -2,9 +2,10 @@ use parse::Position::ArgumentNamed; 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 866ec72f11646..71320e6d5ad37 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) mod printf { s.push('{'); if let Some(arg) = self.parameter { - match write!( - s, - "{}", - match arg.checked_sub(1) { - Some(a) => a, - None => return Err(None), - } - ) { + match write!(s, "{}", match arg.checked_sub(1) { + Some(a) => a, + None => return Err(None), + }) { Err(_) => return Err(None), _ => {} } diff --git a/compiler/rustc_builtin_macros/src/format_foreign/printf/tests.rs b/compiler/rustc_builtin_macros/src/format_foreign/printf/tests.rs index df773910dbc8f..8fe06df48e5ec 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 @@ fn test_parse() { fn test_iter() { let s = "The %d'th word %% is: `%.*s` %!\n"; let subs: Vec<_> = iter_subs(s, 0).map(|sub| sub.translate().ok()).collect(); - assert_eq!( - subs.iter().map(Option::as_deref).collect::>(), - vec![Some("{}"), None, Some("{:.*}"), None] - ); + assert_eq!(subs.iter().map(Option::as_deref).collect::>(), vec![ + Some("{}"), + None, + Some("{:.*}"), + None + ]); } /// Checks that the translations are what we expect. diff --git a/compiler/rustc_builtin_macros/src/format_foreign/shell/tests.rs b/compiler/rustc_builtin_macros/src/format_foreign/shell/tests.rs index 93a7afcd6e8b6..dd2ee2b6ca9a9 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 66df393b501a2..b4b18409a18eb 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 @@ use rustc_ast::{ 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 869d203f68eba..90b5f097b32b3 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 6b2b2b90457c5..d6603af101afc 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 std::mem; 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 9554d97829e21..946fbe918e6a6 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::tokenstream::TokenStream; 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 9bcd793c45041..a3fc53344ab14 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::base::{ExtCtxt, ResolverExpand}; 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 40dc75339efd7..664e935ee14a3 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -5,13 +5,13 @@ use std::assert_matches::assert_matches; 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 400557ca260b2..953484533087c 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 as ast; 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 bd9ebc355e158..e624d1da66bd5 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 0bcd5aef28bab..d7b03a43ecb0d 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 5a464bfac3644..1ec99eb3d17a5 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 896a5c34c3eff..2ee94146c1a4e 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 02d4d98dc4212..1c2ca95b075ca 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 a0df502dadc47..6594ffb5d66bd 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 e3f1162445b33..9292778806a2e 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_REPO: GitRepo = GitRepo::github( 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 6c64faaa2563e..ebeb67722507a 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 129713e574ad0..02da89f737cf2 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::rustc_info::get_file_name; 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 e41f6c5e709e2..82558999aface 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::process::Command; 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 @@ impl SysrootTarget { } } -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 9ddeda583afd1..b68ac7c09267e 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 8572815fc55e4..35e7e81c5285d 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 @@ impl RelPath { 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 be0bed0f4e636..30bd7ae26a186 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::hash::{Hash, Hasher}; 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 @@ impl GitRepo { 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 @@ impl GitRepo { } } -#[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 38c3786a94a42..fd94e80f6312e 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::path::PathBuf; 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 @@ pub(crate) static RAND_REPO: GitRepo = GitRepo::github( "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 @@ pub(crate) static REGEX_REPO: GitRepo = GitRepo::github( "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 EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ 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 EXTENDED_SYSROOT_SUITE: &[TestCase] = &[ 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 @@ impl<'a> TestRunner<'a> { 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 @@ impl<'a> TestRunner<'a> { } 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 f652599447bcf..5c333fe2db596 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 3c4b45e02cc25..22a9487a202d6 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 @@ impl Compiler { } } } + + 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 @@ impl CargoProject { } } -#[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 19405a53d1c65..4dbd9dac94a89 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 00e437d7e546a..69ce17d3d752a 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 f27d4ef57e0c0..ebaa9c69c810a 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 0000000000000..b1fd6224632be --- /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 8c404956bcc20..5117b04fd3447 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 d579c9588f08a..efd721d9df885 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 440177018f428..d7204add7a788 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 96c467e091cff..651770be3775d 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 684a5d0729355..2f13b0b9cb834 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 8838b15d29d40..892ec3e95855e 100644 --- a/compiler/rustc_codegen_cranelift/src/abi/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/abi/mod.rs @@ -13,9 +13,9 @@ use cranelift_module::ModuleError; 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 @@ pub(crate) fn codegen_terminator_call<'tcx>( 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 0652267002910..38c322b5e0450 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 cranelift_codegen::ir::{ArgumentExtension, ArgumentPurpose}; 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 e0f399e616e5d..a294c789b220d 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 b4a3825e9965f..5e33b9d606fa5 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 8839829e2f5cd..1ce0aacab4998 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}; @@ -652,7 +652,7 @@ fn codegen_stmt<'tcx>( lval.write_cvalue(fx, res); } Rvalue::Cast( - CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer), + CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _), ref operand, to_ty, ) => { @@ -677,7 +677,7 @@ fn codegen_stmt<'tcx>( } } Rvalue::Cast( - CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer), + CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _), ref operand, to_ty, ) => { @@ -688,6 +688,7 @@ fn codegen_stmt<'tcx>( Rvalue::Cast( CastKind::PointerCoercion( PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, + _, ), .., ) => { @@ -741,7 +742,7 @@ fn codegen_stmt<'tcx>( } } Rvalue::Cast( - CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_)), + CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _), ref operand, _to_ty, ) => { @@ -763,14 +764,18 @@ fn codegen_stmt<'tcx>( } } Rvalue::Cast( - CastKind::PointerCoercion(PointerCoercion::Unsize), + CastKind::PointerCoercion(PointerCoercion::Unsize, _), ref operand, _to_ty, ) => { let operand = codegen_operand(fx, operand); crate::unsize::coerce_unsized_into(fx, operand, lval); } - Rvalue::Cast(CastKind::DynStar, ref operand, _) => { + Rvalue::Cast( + CastKind::PointerCoercion(PointerCoercion::DynStar, _), + ref operand, + _, + ) => { let operand = codegen_operand(fx, operand); crate::unsize::coerce_dyn_star(fx, operand, lval); } diff --git a/compiler/rustc_codegen_cranelift/src/common.rs b/compiler/rustc_codegen_cranelift/src/common.rs index 22ca2070715d1..e78ba5a341531 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 0ba163f50aec5..ab78584332a05 100644 --- a/compiler/rustc_codegen_cranelift/src/constant.rs +++ b/compiler/rustc_codegen_cranelift/src/constant.rs @@ -5,7 +5,7 @@ use std::cmp::Ordering; 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::*; @@ -161,13 +161,13 @@ pub(crate) fn codegen_const_value<'tcx>( fx.module.declare_func_in_func(func_id, &mut fx.bcx.func); fx.bcx.ins().func_addr(fx.pointer_type, local_func_id) } - GlobalAlloc::VTable(ty, trait_ref) => { + GlobalAlloc::VTable(ty, dyn_ty) => { let data_id = data_id_for_vtable( fx.tcx, &mut fx.constants_cx, fx.module, ty, - trait_ref, + dyn_ty.principal(), ); let local_data_id = fx.module.declare_data_in_func(data_id, &mut fx.bcx.func); @@ -456,8 +456,8 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut dyn Module, cx: &mut Constant GlobalAlloc::Memory(target_alloc) => { data_id_for_alloc_id(cx, module, alloc_id, target_alloc.inner().mutability) } - GlobalAlloc::VTable(ty, trait_ref) => { - data_id_for_vtable(tcx, cx, module, ty, trait_ref) + GlobalAlloc::VTable(ty, dyn_ty) => { + data_id_for_vtable(tcx, cx, module, ty, dyn_ty.principal()) } GlobalAlloc::Static(def_id) => { if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) @@ -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 36af7d4450d04..ccdc347af660f 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::write::{Address, AttributeValue, EndianVec, Result, Sections, Writer} 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 78b3d5a58f4a2..c3d9d635084d6 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 1c6e471cc870f..048a388731fb0 100644 --- a/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs +++ b/compiler/rustc_codegen_cranelift/src/debuginfo/object.rs @@ -73,19 +73,16 @@ impl WriteDebugInfo for ObjectProduct { } }; self.object - .add_relocation( - from.0, - Relocation { - offset: u64::from(reloc.offset), - symbol, - flags: RelocationFlags::Generic { - kind: reloc.kind, - encoding: RelocationEncoding::Generic, - size: reloc.size * 8, - }, - 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 8a55a23128db8..a710701e72c4b 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_data_structures::fx::FxHashMap; 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 ac7dd0bd46329..9399230f292e0 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 b6fee1bf24a78..419efa9060081 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::link::ensure_removed; 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 12e860f676d05..0d62a13b4724e 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 16edec47e1029..41f1b30d10b59 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 f0fb18608e072..39f6763d9f2cb 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 cb003037c265f..c02d31844e032 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 29deac6073035..19e5adc253854 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -19,11 +19,11 @@ mod simd; 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 b96abb14b2e9e..cbe411d78d5fd 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 f737af25b62ee..f6b7981395a5f 100644 --- a/compiler/rustc_codegen_cranelift/src/lib.rs +++ b/compiler/rustc_codegen_cranelift/src/lib.rs @@ -38,15 +38,15 @@ use std::sync::Arc; 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 value_and_place; 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 ba20a750d2b35..df92bc58bf53d 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 196418023d920..13877b3b1e9ae 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::fmt; 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 2fb0c2164c309..a61e1e334eca1 100644 --- a/compiler/rustc_codegen_cranelift/src/trap.rs +++ b/compiler/rustc_codegen_cranelift/src/trap.rs @@ -5,15 +5,11 @@ use crate::prelude::*; fn codegen_print(fx: &mut FunctionCx<'_, '_, '_>, msg: &str) { let puts = fx .module - .declare_function( - "puts", - Linkage::Import, - &Signature { - call_conv: fx.target_config.default_call_conv, - params: vec![AbiParam::new(fx.pointer_type)], - returns: vec![AbiParam::new(types::I32)], - }, - ) + .declare_function("puts", Linkage::Import, &Signature { + call_conv: fx.target_config.default_call_conv, + params: vec![AbiParam::new(fx.pointer_type)], + returns: vec![AbiParam::new(types::I32)], + }) .unwrap(); let puts = fx.module.declare_func_in_func(puts, &mut fx.bcx.func); if fx.clif_comments.enabled() { diff --git a/compiler/rustc_codegen_cranelift/test.sh b/compiler/rustc_codegen_cranelift/test.sh index 6357eebf02696..6c07c512ef294 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 b9152d2cc6de0..a70d457341b93 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 15ba1612167e4..a7980dec83b6c 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::ffi::OsStr; 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 83fa8059b1a05..50e27736aac2d 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 e338d1b4992e8..401c23948e5d3 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 ed78d4ef19fa3..14fc23593f0e6 100644 --- a/compiler/rustc_codegen_gcc/src/abi.rs +++ b/compiler/rustc_codegen_gcc/src/abi.rs @@ -4,8 +4,8 @@ use gccjit::{ToLValue, ToRValue, Type}; 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 deeb55e9d128e..e9498857fb9a3 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 c2adab7137f62..ed92f9c52412c 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::lto::{LtoModuleCodegen, SerializedModule, ThinModul 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::bug; 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 c0443faf24a3c..9836e654f37f6 100644 --- a/compiler/rustc_codegen_gcc/src/base.rs +++ b/compiler/rustc_codegen_gcc/src/base.rs @@ -19,7 +19,7 @@ use rustc_target::spec::PanicStrategy; 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 9282d8699ebb1..b687330438239 100644 --- a/compiler/rustc_codegen_gcc/src/builder.rs +++ b/compiler/rustc_codegen_gcc/src/builder.rs @@ -7,7 +7,8 @@ use gccjit::{ 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 @@ use rustc_codegen_ssa::traits::{ 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 @@ use rustc_middle::ty::layout::{ 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 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { // NOTE: not sure why, but we have the wrong type here. let int_type = compare_exchange.get_param(2).to_rvalue().get_type(); let src = self.context.new_bitcast(self.location, src, int_type); - self.context.new_call( - self.location, - compare_exchange, - &[dst, expected, src, weak, order, failure_order], - ) + self.context.new_call(self.location, compare_exchange, &[ + dst, + expected, + src, + weak, + order, + failure_order, + ]) } pub fn assign(&self, lvalue: LValue<'gcc>, value: RValue<'gcc>) { @@ -500,6 +503,7 @@ impl<'a, 'gcc, 'tcx> Deref for Builder<'a, 'gcc, 'tcx> { impl<'gcc, 'tcx> BackendTypes for Builder<'_, 'gcc, 'tcx> { type Value = as BackendTypes>::Value; + type Metadata = as BackendTypes>::Metadata; type Function = as BackendTypes>::Function; type BasicBlock = as BackendTypes>::BasicBlock; type Type = as BackendTypes>::Type; @@ -1079,11 +1083,9 @@ impl<'a, 'gcc, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'gcc, 'tcx> { let align = dest.val.align.restrict_for_offset(dest.layout.field(self.cx(), 0).size); cg_elem.val.store(self, PlaceRef::new_sized_aligned(current_val, cg_elem.layout, align)); - let next = self.inbounds_gep( - self.backend_type(cg_elem.layout), - current.to_rvalue(), - &[self.const_usize(1)], - ); + let next = self.inbounds_gep(self.backend_type(cg_elem.layout), current.to_rvalue(), &[ + self.const_usize(1), + ]); self.llbb().add_assignment(self.location, current, next); self.br(header_bb); diff --git a/compiler/rustc_codegen_gcc/src/common.rs b/compiler/rustc_codegen_gcc/src/common.rs index b7ed34858b5c4..726b126e727dd 100644 --- a/compiler/rustc_codegen_gcc/src/common.rs +++ b/compiler/rustc_codegen_gcc/src/common.rs @@ -2,8 +2,8 @@ use gccjit::{LValue, RValue, ToRValue, Type}; 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}; @@ -224,10 +224,10 @@ impl<'gcc, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { value } GlobalAlloc::Function { instance, .. } => self.get_fn_addr(instance), - GlobalAlloc::VTable(ty, trait_ref) => { + GlobalAlloc::VTable(ty, dyn_ty) => { let alloc = self .tcx - .global_alloc(self.tcx.vtable_allocation((ty, trait_ref))) + .global_alloc(self.tcx.vtable_allocation((ty, dyn_ty.principal()))) .unwrap_memory(); let init = const_alloc_to_gcc(self, alloc); self.static_addr_of(init, alloc.inner().align, None) diff --git a/compiler/rustc_codegen_gcc/src/consts.rs b/compiler/rustc_codegen_gcc/src/consts.rs index 68b9df946d0b8..5ad5117d7fd4f 100644 --- a/compiler/rustc_codegen_gcc/src/consts.rs +++ b/compiler/rustc_codegen_gcc/src/consts.rs @@ -7,7 +7,7 @@ use rustc_codegen_ssa::traits::{ 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 8e1a5b6128509..caccf8296a294 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -6,7 +6,7 @@ use gccjit::{ 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::layout::{ 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}; @@ -414,6 +414,7 @@ impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> { impl<'gcc, 'tcx> BackendTypes for CodegenCx<'gcc, 'tcx> { type Value = RValue<'gcc>; + type Metadata = RValue<'gcc>; type Function = RValue<'gcc>; type BasicBlock = Block<'gcc>; diff --git a/compiler/rustc_codegen_gcc/src/debuginfo.rs b/compiler/rustc_codegen_gcc/src/debuginfo.rs index 1d859656b3efc..271d65a823537 100644 --- a/compiler/rustc_codegen_gcc/src/debuginfo.rs +++ b/compiler/rustc_codegen_gcc/src/debuginfo.rs @@ -10,8 +10,8 @@ use rustc_middle::mir::{self, Body, SourceScope}; 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 5308ccdb61469..01dd1a8856aab 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_data_structures::fx::FxHashMap; 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 29f4db6738b2e..abb473a830c8d 100644 --- a/compiler/rustc_codegen_gcc/src/int.rs +++ b/compiler/rustc_codegen_gcc/src/int.rs @@ -6,8 +6,8 @@ use gccjit::{BinaryOp, ComparisonOp, FunctionType, Location, RValue, ToRValue, T 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 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { 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 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { ); 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 554e57250e6d8..48f96df61e97e 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 4fd033255feca..753c3a3dfa630 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -7,6 +7,7 @@ use std::iter; #[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 @@ use rustc_codegen_ssa::traits::{ }; #[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 28f6a0821fb81..d78b3f2eb8e81 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_hir as hir; 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 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let arg_tys = sig.inputs(); if name == sym::simd_select_bitmask { - require_simd!( - arg_tys[1], - InvalidMonomorphization::SimdArgument { span, name, ty: arg_tys[1] } - ); + require_simd!(arg_tys[1], InvalidMonomorphization::SimdArgument { + span, + name, + ty: arg_tys[1] + }); let (len, _) = arg_tys[1].simd_size_and_type(bx.tcx()); let expected_int_bits = (len.max(8) - 1).next_power_of_two(); @@ -135,17 +136,14 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx()); - require!( - 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 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( let lo_nibble = bx.context.new_rvalue_from_vector(None, long_byte_vector_type, &lo_nibble_elements); - let mask = bx.context.new_rvalue_from_vector( - None, - long_byte_vector_type, - &vec![bx.context.new_rvalue_from_int(bx.u8_type, 0x0f); byte_vector_type_size as _], - ); - - let 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 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 _ + ]); // Step 2: Byte-swap the input. let swapped = simd_bswap(bx, args[0].immediate()); @@ -364,14 +368,21 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_ty) = ret_ty.simd_size_and_type(bx.tcx()); - require!( - out_len == n, - InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len } - ); - require!( - in_elem == out_ty, - InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty } - ); + require!(out_len == n, InvalidMonomorphization::ReturnLength { + span, + name, + in_len: n, + ret_ty, + out_len + }); + require!(in_elem == out_ty, InvalidMonomorphization::ReturnElement { + span, + name, + in_elem, + in_ty, + ret_ty, + out_ty + }); let vector = args[2].immediate(); @@ -380,16 +391,13 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( #[cfg(feature = "master")] if name == sym::simd_insert { - require!( - in_elem == arg_tys[2], - InvalidMonomorphization::InsertedType { - span, - name, - in_elem, - in_ty, - out_ty: arg_tys[2] - } - ); + require!(in_elem == arg_tys[2], InvalidMonomorphization::InsertedType { + span, + name, + in_elem, + in_ty, + out_ty: arg_tys[2] + }); let vector = args[0].immediate(); let index = args[1].immediate(); let value = args[2].immediate(); @@ -403,10 +411,13 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( #[cfg(feature = "master")] if name == sym::simd_extract { - require!( - ret_ty == in_elem, - InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } - ); + require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { + span, + name, + in_elem, + in_ty, + ret_ty + }); let vector = args[0].immediate(); return Ok(bx.context.new_vector_access(None, vector, args[1].immediate()).to_rvalue()); } @@ -414,15 +425,18 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( if name == sym::simd_select { let m_elem_ty = in_elem; let m_len = in_len; - require_simd!( - arg_tys[1], - InvalidMonomorphization::SimdArgument { span, name, ty: arg_tys[1] } - ); + require_simd!(arg_tys[1], InvalidMonomorphization::SimdArgument { + span, + name, + ty: arg_tys[1] + }); let (v_len, _) = arg_tys[1].simd_size_and_type(bx.tcx()); - require!( - m_len == v_len, - InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len } - ); + require!(m_len == v_len, InvalidMonomorphization::MismatchedLengths { + span, + name, + m_len, + v_len + }); match *m_elem_ty.kind() { ty::Int(_) => {} _ => return_error!(InvalidMonomorphization::MaskType { span, name, ty: m_elem_ty }), @@ -434,27 +448,25 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!( - in_len == out_len, - InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - } - ); + require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + }); match *in_elem.kind() { ty::RawPtr(p_ty, _) => { let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(ty::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 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( 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 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!( - in_len == out_len, - InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - } - ); + require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + }); match *in_elem.kind() { ty::RawPtr(_, _) => {} @@ -530,17 +540,14 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!( - in_len == out_len, - InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - } - ); + require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + }); match *in_elem.kind() { ty::Uint(ty::UintTy::Usize) => {} @@ -569,17 +576,14 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( if name == sym::simd_cast || name == sym::simd_as { require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); let (out_len, out_elem) = ret_ty.simd_size_and_type(bx.tcx()); - require!( - in_len == out_len, - InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - } - ); + require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + }); // casting cares about nominal type, not just structural type if in_elem == out_elem { return Ok(args[0].immediate()); @@ -605,17 +609,14 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( match (in_style, out_style) { (Style::Unsupported, Style::Unsupported) => { - require!( - false, - InvalidMonomorphization::UnsupportedCast { - span, - name, - in_ty, - in_elem, - ret_ty, - out_elem - } - ); + require!(false, InvalidMonomorphization::UnsupportedCast { + span, + name, + in_ty, + in_elem, + ret_ty, + out_elem + }); } _ => return Ok(bx.context.convert_vector(None, args[0].immediate(), llret_ty)), } @@ -880,47 +881,45 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( // All types must be simd vector types require_simd!(in_ty, InvalidMonomorphization::SimdFirst { span, name, ty: in_ty }); - require_simd!( - arg_tys[1], - InvalidMonomorphization::SimdSecond { span, name, ty: arg_tys[1] } - ); - require_simd!( - arg_tys[2], - InvalidMonomorphization::SimdThird { span, name, ty: arg_tys[2] } - ); + require_simd!(arg_tys[1], InvalidMonomorphization::SimdSecond { + span, + name, + ty: arg_tys[1] + }); + require_simd!(arg_tys[2], InvalidMonomorphization::SimdThird { + span, + name, + ty: arg_tys[2] + }); require_simd!(ret_ty, InvalidMonomorphization::SimdReturn { span, name, ty: ret_ty }); // Of the same length: let (out_len, _) = arg_tys[1].simd_size_and_type(bx.tcx()); let (out_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx()); - require!( - in_len == out_len, - InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len - } - ); - require!( - in_len == out_len2, - InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: out_len2 - } - ); + require!(in_len == out_len, InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len + }); + require!(in_len == out_len2, InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: out_len2 + }); // The return type must match the first argument type - require!( - ret_ty == in_ty, - InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty } - ); + require!(ret_ty == in_ty, InvalidMonomorphization::ExpectedReturnType { + span, + name, + in_ty, + ret_ty + }); // This counts how many pointers fn ptr_count(t: Ty<'_>) -> usize { @@ -947,18 +946,15 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( (ptr_count(element_ty1), non_ptr(element_ty1)) } _ => { - require!( - false, - InvalidMonomorphization::ExpectedElementType { - span, - name, - expected_element: element_ty1, - second_arg: arg_tys[1], - in_elem, - in_ty, - mutability: ExpectedPointerMutability::Not, - } - ); + require!(false, InvalidMonomorphization::ExpectedElementType { + span, + name, + expected_element: element_ty1, + second_arg: arg_tys[1], + in_elem, + in_ty, + mutability: ExpectedPointerMutability::Not, + }); unreachable!(); } }; @@ -971,15 +967,12 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( match *element_ty2.kind() { ty::Int(_) => (), _ => { - require!( - false, - InvalidMonomorphization::ThirdArgElementType { - span, - name, - expected_element: element_ty2, - third_arg: arg_tys[2] - } - ); + require!(false, InvalidMonomorphization::ThirdArgElementType { + span, + name, + expected_element: element_ty2, + third_arg: arg_tys[2] + }); } } @@ -1003,40 +996,36 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( // All types must be simd vector types require_simd!(in_ty, InvalidMonomorphization::SimdFirst { span, name, ty: in_ty }); - require_simd!( - arg_tys[1], - InvalidMonomorphization::SimdSecond { span, name, ty: arg_tys[1] } - ); - require_simd!( - arg_tys[2], - InvalidMonomorphization::SimdThird { span, name, ty: arg_tys[2] } - ); + require_simd!(arg_tys[1], InvalidMonomorphization::SimdSecond { + span, + name, + ty: arg_tys[1] + }); + require_simd!(arg_tys[2], InvalidMonomorphization::SimdThird { + span, + name, + ty: arg_tys[2] + }); // Of the same length: let (element_len1, _) = arg_tys[1].simd_size_and_type(bx.tcx()); let (element_len2, _) = arg_tys[2].simd_size_and_type(bx.tcx()); - require!( - in_len == element_len1, - InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len: element_len1 - } - ); - require!( - in_len == element_len2, - InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: element_len2 - } - ); + require!(in_len == element_len1, InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len: element_len1 + }); + require!(in_len == element_len2, InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: element_len2 + }); // This counts how many pointers fn ptr_count(t: Ty<'_>) -> usize { @@ -1064,18 +1053,15 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( (ptr_count(element_ty1), non_ptr(element_ty1)) } _ => { - require!( - false, - InvalidMonomorphization::ExpectedElementType { - span, - name, - expected_element: element_ty1, - second_arg: arg_tys[1], - in_elem, - in_ty, - mutability: ExpectedPointerMutability::Mut, - } - ); + require!(false, InvalidMonomorphization::ExpectedElementType { + span, + name, + expected_element: element_ty1, + second_arg: arg_tys[1], + in_elem, + in_ty, + mutability: ExpectedPointerMutability::Mut, + }); unreachable!(); } }; @@ -1087,15 +1073,12 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( match *element_ty2.kind() { ty::Int(_) => (), _ => { - require!( - false, - InvalidMonomorphization::ThirdArgElementType { - span, - name, - expected_element: element_ty2, - third_arg: arg_tys[2] - } - ); + require!(false, InvalidMonomorphization::ThirdArgElementType { + span, + name, + expected_element: element_ty2, + third_arg: arg_tys[2] + }); } } @@ -1262,10 +1245,13 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( ($name:ident : $vec_op:expr, $float_reduce:ident, $ordered:expr, $op:ident, $identity:expr) => { if name == sym::$name { - require!( - ret_ty == in_elem, - InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } - ); + require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { + span, + name, + in_elem, + in_ty, + ret_ty + }); return match *in_elem.kind() { ty::Int(_) | ty::Uint(_) => { let r = bx.vector_reduce_op(args[0].immediate(), $vec_op); @@ -1331,10 +1317,13 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( macro_rules! minmax_red { ($name:ident: $int_red:ident, $float_red:ident) => { if name == sym::$name { - require!( - ret_ty == in_elem, - InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } - ); + require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { + span, + name, + in_elem, + in_ty, + ret_ty + }); return match *in_elem.kind() { ty::Int(_) | ty::Uint(_) => Ok(bx.$int_red(args[0].immediate())), ty::Float(_) => Ok(bx.$float_red(args[0].immediate())), @@ -1358,10 +1347,13 @@ pub fn generic_simd_intrinsic<'a, 'gcc, 'tcx>( ($name:ident : $op:expr, $boolean:expr) => { if name == sym::$name { let input = if !$boolean { - require!( - ret_ty == in_elem, - InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } - ); + require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { + span, + name, + in_elem, + in_ty, + ret_ty + }); args[0].immediate() } else { match *in_elem.kind() { diff --git a/compiler/rustc_codegen_gcc/src/lib.rs b/compiler/rustc_codegen_gcc/src/lib.rs index 4de671ac4a062..edf524ff0b4af 100644 --- a/compiler/rustc_codegen_gcc/src/lib.rs +++ b/compiler/rustc_codegen_gcc/src/lib.rs @@ -107,10 +107,10 @@ use rustc_metadata::EncodedMetadata; 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 0fa8c9d3f1952..3d75393bf06fd 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 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { // LLVM also rejects full range. && !scalar.is_always_valid(cx) { - attributes::apply_to_llfn( - llfn, - idx, - &[llvm::CreateRangeAttr(cx.llcx, scalar.size(cx), scalar.valid_range(cx))], - ); + attributes::apply_to_llfn(llfn, idx, &[llvm::CreateRangeAttr( + cx.llcx, + scalar.size(cx), + scalar.valid_range(cx), + )]); } }; @@ -469,14 +469,10 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { ); attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[sret]); if cx.sess().opts.optimize != config::OptLevel::No { - attributes::apply_to_llfn( - llfn, - llvm::AttributePlace::Argument(i), - &[ - llvm::AttributeKind::Writable.create_attr(cx.llcx), - llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx), - ], - ); + attributes::apply_to_llfn(llfn, llvm::AttributePlace::Argument(i), &[ + llvm::AttributeKind::Writable.create_attr(cx.llcx), + llvm::AttributeKind::DeadOnUnwind.create_attr(cx.llcx), + ]); } } PassMode::Cast { cast, pad_i32: _ } => { @@ -592,11 +588,9 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { bx.cx.llcx, bx.cx.type_array(bx.cx.type_i8(), arg.layout.size.bytes()), ); - attributes::apply_to_callsite( - callsite, - llvm::AttributePlace::Argument(i), - &[byval], - ); + attributes::apply_to_callsite(callsite, llvm::AttributePlace::Argument(i), &[ + byval, + ]); } PassMode::Direct(attrs) | PassMode::Indirect { attrs, meta_attrs: None, on_stack: false } => { @@ -628,11 +622,9 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { // This will probably get ignored on all targets but those supporting the TrustZone-M // extension (thumbv8m targets). let cmse_nonsecure_call = llvm::CreateAttrString(bx.cx.llcx, "cmse_nonsecure_call"); - attributes::apply_to_callsite( - callsite, - llvm::AttributePlace::Function, - &[cmse_nonsecure_call], - ); + attributes::apply_to_callsite(callsite, llvm::AttributePlace::Function, &[ + cmse_nonsecure_call, + ]); } // Some intrinsics require that an elementtype attribute (with the pointee type of a diff --git a/compiler/rustc_codegen_llvm/src/allocator.rs b/compiler/rustc_codegen_llvm/src/allocator.rs index b4f3784a31abd..2adac278c62f9 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 430ba7352433b..7621f111fe257 100644 --- a/compiler/rustc_codegen_llvm/src/asm.rs +++ b/compiler/rustc_codegen_llvm/src/asm.rs @@ -5,10 +5,10 @@ use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; 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; @@ -504,10 +504,15 @@ pub(crate) fn inline_asm_call<'ll>( // due to the asm template string coming from a macro. LLVM will // default to the first srcloc for lines that don't have an // associated srcloc. - srcloc.push(bx.const_i32(0)); + srcloc.push(llvm::LLVMValueAsMetadata(bx.const_i32(0))); } - srcloc.extend(line_spans.iter().map(|span| bx.const_i32(span.lo().to_u32() as i32))); - let md = llvm::LLVMMDNodeInContext(bx.llcx, srcloc.as_ptr(), srcloc.len() as u32); + srcloc.extend( + line_spans + .iter() + .map(|span| llvm::LLVMValueAsMetadata(bx.const_i32(span.lo().to_u32() as i32))), + ); + let md = llvm::LLVMMDNodeInContext2(bx.llcx, srcloc.as_ptr(), srcloc.len()); + let md = llvm::LLVMMetadataAsValue(&bx.llcx, md); llvm::LLVMSetMetadata(call, kind, md); Some(call) diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index 4f2c83634a8a8..1b4f6682af02d 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 66479ad7f34d3..5e510177818b4 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::lto::{LtoModuleCodegen, SerializedModule, ThinModul 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 rustc_session::config::{self, CrateType, Lto}; 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 @@ impl ThinLTOKeysMap { 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 76529e0c83bcd..44c30d22a9e9c 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 79794775b7b66..73ae0072c424f 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 d2c4ea8171b87..afdd2b581b86e 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_data_structures::small_c_str::SmallCStr; 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::errors::{ 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 6ffe90997f502..4e0c62c8bf8c9 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -3,11 +3,11 @@ use std::ops::Deref; 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; @@ -56,6 +56,7 @@ const UNNAMED: *const c_char = c"".as_ptr(); impl<'ll, 'tcx> BackendTypes for Builder<'_, 'll, 'tcx> { type Value = as BackendTypes>::Value; + type Metadata = as BackendTypes>::Metadata; type Function = as BackendTypes>::Function; type BasicBlock = as BackendTypes>::BasicBlock; type Type = as BackendTypes>::Type; @@ -623,26 +624,19 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { unsafe { let llty = self.cx.val_ty(load); - let v = [ - self.cx.const_uint_big(llty, range.start), - self.cx.const_uint_big(llty, range.end.wrapping_add(1)), + let md = [ + llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.start)), + llvm::LLVMValueAsMetadata(self.cx.const_uint_big(llty, range.end.wrapping_add(1))), ]; - - llvm::LLVMSetMetadata( - load, - llvm::MD_range as c_uint, - llvm::LLVMMDNodeInContext(self.cx.llcx, v.as_ptr(), v.len() as c_uint), - ); + let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len()); + self.set_metadata(load, llvm::MD_range, md); } } fn nonnull_metadata(&mut self, load: &'ll Value) { unsafe { - llvm::LLVMSetMetadata( - load, - llvm::MD_nonnull as c_uint, - llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0), - ); + let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0); + self.set_metadata(load, llvm::MD_nonnull, md); } } @@ -690,9 +684,9 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { // *always* point to a metadata value of the integer 1. // // [1]: https://llvm.org/docs/LangRef.html#store-instruction - let one = self.cx.const_i32(1); - let node = llvm::LLVMMDNodeInContext(self.cx.llcx, &one, 1); - llvm::LLVMSetMetadata(store, llvm::MD_nontemporal as c_uint, node); + let one = llvm::LLVMValueAsMetadata(self.cx.const_i32(1)); + let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, &one, 1); + self.set_metadata(store, llvm::MD_nontemporal, md); } } store @@ -1157,11 +1151,8 @@ impl<'a, 'll, 'tcx> BuilderMethods<'a, 'tcx> for Builder<'a, 'll, 'tcx> { fn set_invariant_load(&mut self, load: &'ll Value) { unsafe { - llvm::LLVMSetMetadata( - load, - llvm::MD_invariant_load as c_uint, - llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0), - ); + let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0); + self.set_metadata(load, llvm::MD_invariant_load, md); } } @@ -1290,33 +1281,23 @@ impl<'a, 'll, 'tcx> Builder<'a, 'll, 'tcx> { fn align_metadata(&mut self, load: &'ll Value, align: Align) { unsafe { - let v = [self.cx.const_u64(align.bytes())]; - - llvm::LLVMSetMetadata( - load, - llvm::MD_align as c_uint, - llvm::LLVMMDNodeInContext(self.cx.llcx, v.as_ptr(), v.len() as c_uint), - ); + let md = [llvm::LLVMValueAsMetadata(self.cx.const_u64(align.bytes()))]; + let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, md.as_ptr(), md.len()); + self.set_metadata(load, llvm::MD_align, md); } } fn noundef_metadata(&mut self, load: &'ll Value) { unsafe { - llvm::LLVMSetMetadata( - load, - llvm::MD_noundef as c_uint, - llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0), - ); + let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0); + self.set_metadata(load, llvm::MD_noundef, md); } } pub(crate) fn set_unpredictable(&mut self, inst: &'ll Value) { unsafe { - llvm::LLVMSetMetadata( - inst, - llvm::MD_unpredictable as c_uint, - llvm::LLVMMDNodeInContext(self.cx.llcx, ptr::null(), 0), - ); + let md = llvm::LLVMMDNodeInContext2(self.cx.llcx, ptr::null(), 0); + self.set_metadata(inst, llvm::MD_unpredictable, md); } } diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index 508c2d1a820e2..31d59905446f3 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -14,7 +14,7 @@ use tracing::debug; use crate::consts::const_alloc_to_llvm; pub(crate) use crate::context::CodegenCx; -use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, OperandBundleDef, True}; +use crate::llvm::{self, BasicBlock, Bool, ConstantInt, False, Metadata, OperandBundleDef, True}; use crate::type_::Type; use crate::value::Value; @@ -79,6 +79,7 @@ impl<'ll> Funclet<'ll> { impl<'ll> BackendTypes for CodegenCx<'ll, '_> { type Value = &'ll Value; + type Metadata = &'ll Metadata; // FIXME(eddyb) replace this with a `Function` "subclass" of `Value`. type Function = &'ll Value; @@ -290,10 +291,10 @@ impl<'ll, 'tcx> ConstCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { self.get_fn_addr(instance.polymorphize(self.tcx)), self.data_layout().instruction_address_space, ), - GlobalAlloc::VTable(ty, trait_ref) => { + GlobalAlloc::VTable(ty, dyn_ty) => { let alloc = self .tcx - .global_alloc(self.tcx.vtable_allocation((ty, trait_ref))) + .global_alloc(self.tcx.vtable_allocation((ty, dyn_ty.principal()))) .unwrap_memory(); let init = const_alloc_to_llvm(self, alloc, /*static*/ false); let value = self.static_addr_of(init, alloc.inner().align, None); diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 33d3b5d44745e..33a85adeb8781 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::DefKind; 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 1d5580fdd0719..2b8912d1db2ab 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -1,13 +1,12 @@ use std::borrow::Borrow; use std::cell::{Cell, RefCell}; -use std::ffi::CStr; +use std::ffi::{CStr, c_uint}; use std::str; -use libc::c_uint; 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 +17,12 @@ use rustc_middle::ty::layout::{ }; 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; @@ -31,6 +30,7 @@ use smallvec::SmallVec; use crate::back::write::to_llvm_code_model; use crate::callee::get_fn; use crate::debuginfo::metadata::apply_vcall_visibility_metadata; +use crate::llvm::{Metadata, MetadataType}; use crate::type_::Type; use crate::value::Value; use crate::{attributes, coverageinfo, debuginfo, llvm, llvm_util}; @@ -404,17 +404,17 @@ pub(crate) unsafe fn create_module<'ll>( let rustc_producer = format!("rustc version {}", option_env!("CFG_VERSION").expect("CFG_VERSION")); let name_metadata = unsafe { - llvm::LLVMMDStringInContext( + llvm::LLVMMDStringInContext2( llcx, rustc_producer.as_ptr().cast(), - rustc_producer.as_bytes().len() as c_uint, + rustc_producer.as_bytes().len(), ) }; unsafe { llvm::LLVMAddNamedMetadataOperand( llmod, c"llvm.ident".as_ptr(), - llvm::LLVMMDNodeInContext(llcx, &name_metadata, 1), + &llvm::LLVMMetadataAsValue(llcx, llvm::LLVMMDNodeInContext2(llcx, &name_metadata, 1)), ); } @@ -1119,6 +1119,14 @@ impl CodegenCx<'_, '_> { name.push_str(&(idx as u64).to_base(ALPHANUMERIC_ONLY)); name } + + /// A wrapper for [`llvm::LLVMSetMetadata`], but it takes `Metadata` as a parameter instead of `Value`. + pub(crate) fn set_metadata<'a>(&self, val: &'a Value, kind_id: MetadataType, md: &'a Metadata) { + unsafe { + let node = llvm::LLVMMetadataAsValue(&self.llcx, md); + llvm::LLVMSetMetadata(val, kind_id as c_uint, node); + } + } } impl HasDataLayout for CodegenCx<'_, '_> { diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/mapgen.rs index a9f65ee8a93bb..267a22449167d 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_hir::def_id::{DefId, LocalDefId}; 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 @@ impl GlobalFileTable { // 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 c9d2a1c9b8838..3a80d216f47ee 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_data_structures::fx::{FxHashMap, FxIndexMap}; 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 c3087d8ec3040..ac6c2fb1b83a6 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 57e396415ccef..964b83c0fa07a 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::path::{Path, PathBuf}; 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_middle::ty::{ }; 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 smallvec::smallvec; 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() @@ -1547,20 +1547,16 @@ pub(crate) fn apply_vcall_visibility_metadata<'ll, 'tcx>( let trait_ref_typeid = typeid_for_trait_ref(cx.tcx, trait_ref); unsafe { - let typeid = llvm::LLVMMDStringInContext( + let typeid = llvm::LLVMMDStringInContext2( cx.llcx, trait_ref_typeid.as_ptr() as *const c_char, - trait_ref_typeid.as_bytes().len() as c_uint, + trait_ref_typeid.as_bytes().len(), ); - let v = [cx.const_usize(0), typeid]; + let v = [llvm::LLVMValueAsMetadata(cx.const_usize(0)), typeid]; llvm::LLVMRustGlobalAddMetadata( vtable, llvm::MD_type as c_uint, - llvm::LLVMValueAsMetadata(llvm::LLVMMDNodeInContext( - cx.llcx, - v.as_ptr(), - v.len() as c_uint, - )), + llvm::LLVMMDNodeInContext2(cx.llcx, v.as_ptr(), v.len()), ); let vcall_visibility = llvm::LLVMValueAsMetadata(cx.const_u64(vcall_visibility as u64)); let vcall_visibility_metadata = llvm::LLVMMDNodeInContext2(cx.llcx, &vcall_visibility, 1); 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 8a132f89aa3ff..966788cf32f54 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::common::CodegenCx; 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 edaf73b74a2a0..fe1634146ff83 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_span::Symbol; 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 0b3140cc91f08..5e7dbdd921abf 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 smallvec::smallvec; 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 6d21f4204e361..714e3c0b1458c 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::bug; 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 920c9e06be4dd..1a8153a54e837 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_index::IndexVec; 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 rustc_target::abi::Size; 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 @@ impl<'ll, 'tcx> DebugInfoCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { } } - let scope = namespace::item_namespace( - cx, - DefId { - krate: instance.def_id().krate, - index: cx - .tcx - .def_key(instance.def_id()) - .parent - .expect("get_containing_scope: missing parent?"), - }, - ); + let scope = namespace::item_namespace(cx, DefId { + krate: instance.def_id().krate, + index: cx + .tcx + .def_key(instance.def_id()) + .parent + .expect("get_containing_scope: missing parent?"), + }); (scope, false) } } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs b/compiler/rustc_codegen_llvm/src/debuginfo/namespace.rs index 9674b1eb84864..3578755aae059 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_codegen_ssa::debuginfo::type_names; 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 321553a3df0bd..acb15449ce323 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::layout::{HasParamEnv, LayoutOf}; 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 307fb9c35b714..c66c80da9fcca 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -12,7 +12,7 @@ use rustc_middle::mir::BinOp; 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; @@ -20,7 +20,7 @@ use tracing::debug; use crate::abi::{Abi, FnAbi, FnAbiLlvmExt, LlvmType, PassMode}; use crate::builder::Builder; use crate::context::CodegenCx; -use crate::llvm; +use crate::llvm::{self, Metadata}; use crate::type_::Type; use crate::type_of::LayoutLlvmExt; use crate::va_arg::emit_va_arg; @@ -330,15 +330,12 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { sym::prefetch_write_instruction => (1, 0), _ => bug!(), }; - self.call_intrinsic( - "llvm.prefetch", - &[ - args[0].immediate(), - self.const_i32(rw), - args[1].immediate(), - self.const_i32(cache_type), - ], - ) + self.call_intrinsic("llvm.prefetch", &[ + args[0].immediate(), + self.const_i32(rw), + args[1].immediate(), + self.const_i32(cache_type), + ]) } sym::ctlz | sym::ctlz_nonzero @@ -356,10 +353,10 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { 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 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { self.intcast(ret, llret_ty, false) } sym::ctpop => { - let ret = self.call_intrinsic( - &format!("llvm.ctpop.i{width}"), - &[args[0].immediate()], - ); + let ret = self.call_intrinsic(&format!("llvm.ctpop.i{width}"), &[args + [0] + .immediate()]); self.intcast(ret, llret_ty, false) } sym::bswap => { if width == 8 { args[0].immediate() // byte swap a u8/i8 is just a no-op } else { - self.call_intrinsic( - &format!("llvm.bswap.i{width}"), - &[args[0].immediate()], - ) + self.call_intrinsic(&format!("llvm.bswap.i{width}"), &[ + args[0].immediate() + ]) } } - sym::bitreverse => self.call_intrinsic( - &format!("llvm.bitreverse.i{width}"), - &[args[0].immediate()], - ), + sym::bitreverse => self + .call_intrinsic(&format!("llvm.bitreverse.i{width}"), &[ + args[0].immediate() + ]), sym::rotate_left | sym::rotate_right => { let is_left = name == sym::rotate_left; let val = args[0].immediate(); @@ -471,10 +466,11 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { sym::compare_bytes => { // Here we assume that the `memcmp` provided by the target is a NOP for size 0. - let cmp = self.call_intrinsic( - "memcmp", - &[args[0].immediate(), args[1].immediate(), args[2].immediate()], - ); + let cmp = self.call_intrinsic("memcmp", &[ + args[0].immediate(), + args[1].immediate(), + args[2].immediate(), + ]); // Some targets have `memcmp` returning `i16`, but the intrinsic is always `i32`. self.sext(cmp, self.type_ix(32)) } @@ -617,9 +613,10 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { } } - fn type_test(&mut self, pointer: Self::Value, typeid: Self::Value) -> Self::Value { + fn type_test(&mut self, pointer: Self::Value, typeid: Self::Metadata) -> Self::Value { // Test the called operand using llvm.type.test intrinsic. The LowerTypeTests link-time // optimization pass replaces calls to this intrinsic with code to test type membership. + let typeid = unsafe { llvm::LLVMMetadataAsValue(&self.llcx, typeid) }; self.call_intrinsic("llvm.type.test", &[pointer, typeid]) } @@ -627,8 +624,9 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { &mut self, llvtable: &'ll Value, vtable_byte_offset: u64, - typeid: &'ll Value, + typeid: &'ll Metadata, ) -> Self::Value { + let typeid = unsafe { llvm::LLVMMetadataAsValue(&self.llcx, typeid) }; let vtable_byte_offset = self.const_i32(vtable_byte_offset as i32); let type_checked_load = self.call_intrinsic("llvm.type.checked.load", &[llvtable, vtable_byte_offset, typeid]); @@ -1216,17 +1214,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if let Some(cmp_op) = comparison { let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn); - require!( - in_len == out_len, - InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - } - ); + require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + }); require!( bx.type_kind(bx.element_type(llret_ty)) == TypeKind::Integer, InvalidMonomorphization::ReturnIntegerType { span, name, ret_ty, out_ty } @@ -1252,14 +1247,21 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let n = idx.len() as u64; let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn); - require!( - out_len == n, - InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len } - ); - require!( - in_elem == out_ty, - InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty } - ); + require!(out_len == n, InvalidMonomorphization::ReturnLength { + span, + name, + in_len: n, + ret_ty, + out_len + }); + require!(in_elem == out_ty, InvalidMonomorphization::ReturnElement { + span, + name, + in_elem, + in_ty, + ret_ty, + out_ty + }); let total_len = in_len * 2; @@ -1304,14 +1306,21 @@ fn generic_simd_intrinsic<'ll, 'tcx>( }; let (out_len, out_ty) = require_simd!(ret_ty, SimdReturn); - require!( - out_len == n, - InvalidMonomorphization::ReturnLength { span, name, in_len: n, ret_ty, out_len } - ); - require!( - in_elem == out_ty, - InvalidMonomorphization::ReturnElement { span, name, in_elem, in_ty, ret_ty, out_ty } - ); + require!(out_len == n, InvalidMonomorphization::ReturnLength { + span, + name, + in_len: n, + ret_ty, + out_len + }); + require!(in_elem == out_ty, InvalidMonomorphization::ReturnElement { + span, + name, + in_elem, + in_ty, + ret_ty, + out_ty + }); let total_len = u128::from(in_len) * 2; @@ -1336,16 +1345,13 @@ fn generic_simd_intrinsic<'ll, 'tcx>( } if name == sym::simd_insert { - require!( - in_elem == arg_tys[2], - InvalidMonomorphization::InsertedType { - span, - name, - in_elem, - in_ty, - out_ty: arg_tys[2] - } - ); + require!(in_elem == arg_tys[2], InvalidMonomorphization::InsertedType { + span, + name, + in_elem, + in_ty, + out_ty: arg_tys[2] + }); let idx = bx .const_to_opt_u128(args[1].immediate(), false) .expect("typeck should have ensure that this is a const"); @@ -1364,10 +1370,13 @@ fn generic_simd_intrinsic<'ll, 'tcx>( )); } if name == sym::simd_extract { - require!( - ret_ty == in_elem, - InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } - ); + require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { + span, + name, + in_elem, + in_ty, + ret_ty + }); let idx = bx .const_to_opt_u128(args[1].immediate(), false) .expect("typeck should have ensure that this is a const"); @@ -1386,10 +1395,12 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let m_elem_ty = in_elem; let m_len = in_len; let (v_len, _) = require_simd!(arg_tys[1], SimdArgument); - require!( - m_len == v_len, - InvalidMonomorphization::MismatchedLengths { span, name, m_len, v_len } - ); + 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 +1627,30 @@ fn generic_simd_intrinsic<'ll, 'tcx>( require_simd!(ret_ty, SimdReturn); // Of the same length: - require!( - in_len == out_len, - InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len - } - ); - require!( - in_len == out_len2, - InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: out_len2 - } - ); + require!(in_len == out_len, InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len + }); + require!(in_len == out_len2, InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: out_len2 + }); // The return type must match the first argument type - require!( - ret_ty == in_ty, - InvalidMonomorphization::ExpectedReturnType { span, name, in_ty, ret_ty } - ); + require!(ret_ty == in_ty, InvalidMonomorphization::ExpectedReturnType { + span, + name, + in_ty, + ret_ty + }); require!( matches!( @@ -1734,23 +1741,22 @@ fn generic_simd_intrinsic<'ll, 'tcx>( require_simd!(ret_ty, SimdReturn); // Of the same length: - require!( - values_len == mask_len, - InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len: mask_len, - in_ty: mask_ty, - arg_ty: values_ty, - out_len: values_len - } - ); + require!(values_len == mask_len, InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len: mask_len, + in_ty: mask_ty, + arg_ty: values_ty, + out_len: values_len + }); // The return type must match the last argument type - require!( - ret_ty == values_ty, - InvalidMonomorphization::ExpectedReturnType { span, name, in_ty: values_ty, ret_ty } - ); + require!(ret_ty == values_ty, InvalidMonomorphization::ExpectedReturnType { + span, + name, + in_ty: values_ty, + ret_ty + }); require!( matches!( @@ -1832,17 +1838,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let (values_len, values_elem) = require_simd!(values_ty, SimdThird); // Of the same length: - require!( - values_len == mask_len, - InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len: mask_len, - in_ty: mask_ty, - arg_ty: values_ty, - out_len: values_len - } - ); + require!(values_len == mask_len, InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len: mask_len, + in_ty: mask_ty, + arg_ty: values_ty, + out_len: values_len + }); // The second argument must be a mutable pointer type matching the element type require!( @@ -1921,28 +1924,22 @@ fn generic_simd_intrinsic<'ll, 'tcx>( let (element_len2, element_ty2) = require_simd!(arg_tys[2], SimdThird); // Of the same length: - require!( - in_len == element_len1, - InvalidMonomorphization::SecondArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[1], - out_len: element_len1 - } - ); - require!( - in_len == element_len2, - InvalidMonomorphization::ThirdArgumentLength { - span, - name, - in_len, - in_ty, - arg_ty: arg_tys[2], - out_len: element_len2 - } - ); + require!(in_len == element_len1, InvalidMonomorphization::SecondArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[1], + out_len: element_len1 + }); + require!(in_len == element_len2, InvalidMonomorphization::ThirdArgumentLength { + span, + name, + in_len, + in_ty, + arg_ty: arg_tys[2], + out_len: element_len2 + }); require!( matches!( @@ -2016,10 +2013,13 @@ fn generic_simd_intrinsic<'ll, 'tcx>( ($name:ident : $integer_reduce:ident, $float_reduce:ident, $ordered:expr, $op:ident, $identity:expr) => { if name == sym::$name { - require!( - ret_ty == in_elem, - InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } - ); + require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { + span, + name, + in_elem, + in_ty, + ret_ty + }); return match in_elem.kind() { ty::Int(_) | ty::Uint(_) => { let r = bx.$integer_reduce(args[0].immediate()); @@ -2088,10 +2088,13 @@ fn generic_simd_intrinsic<'ll, 'tcx>( macro_rules! minmax_red { ($name:ident: $int_red:ident, $float_red:ident) => { if name == sym::$name { - require!( - ret_ty == in_elem, - InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } - ); + require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { + span, + name, + in_elem, + in_ty, + ret_ty + }); return match in_elem.kind() { ty::Int(_i) => Ok(bx.$int_red(args[0].immediate(), true)), ty::Uint(_u) => Ok(bx.$int_red(args[0].immediate(), false)), @@ -2116,10 +2119,13 @@ fn generic_simd_intrinsic<'ll, 'tcx>( ($name:ident : $red:ident, $boolean:expr) => { if name == sym::$name { let input = if !$boolean { - require!( - ret_ty == in_elem, - InvalidMonomorphization::ReturnType { span, name, in_elem, in_ty, ret_ty } - ); + require!(ret_ty == in_elem, InvalidMonomorphization::ReturnType { + span, + name, + in_elem, + in_ty, + ret_ty + }); args[0].immediate() } else { match in_elem.kind() { @@ -2165,27 +2171,25 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if name == sym::simd_cast_ptr { let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn); - require!( - in_len == out_len, - InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - } - ); + require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + }); match in_elem.kind() { ty::RawPtr(p_ty, _) => { let metadata = p_ty.ptr_metadata_ty(bx.tcx, |ty| { bx.tcx.normalize_erasing_regions(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 +2200,11 @@ fn generic_simd_intrinsic<'ll, 'tcx>( 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 +2216,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if name == sym::simd_expose_provenance { let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn); - require!( - in_len == out_len, - InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - } - ); + require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + }); match in_elem.kind() { ty::RawPtr(_, _) => {} @@ -2239,17 +2241,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if name == sym::simd_with_exposed_provenance { let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn); - require!( - in_len == out_len, - InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - } - ); + require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + }); match in_elem.kind() { ty::Uint(ty::UintTy::Usize) => {} @@ -2267,17 +2266,14 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if name == sym::simd_cast || name == sym::simd_as { let (out_len, out_elem) = require_simd!(ret_ty, SimdReturn); - require!( - in_len == out_len, - InvalidMonomorphization::ReturnLengthInputType { - span, - name, - in_len, - in_ty, - ret_ty, - out_len - } - ); + require!(in_len == out_len, InvalidMonomorphization::ReturnLengthInputType { + span, + name, + in_len, + in_ty, + ret_ty, + out_len + }); // casting cares about nominal type, not just structural type if in_elem == out_elem { return Ok(args[0].immediate()); diff --git a/compiler/rustc_codegen_llvm/src/lib.rs b/compiler/rustc_codegen_llvm/src/lib.rs index 7f26bbd7f8757..d69112612ba6b 100644 --- a/compiler/rustc_codegen_llvm/src/lib.rs +++ b/compiler/rustc_codegen_llvm/src/lib.rs @@ -41,8 +41,8 @@ use rustc_metadata::EncodedMetadata; 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 a588f11b6233e..9aabfd794bad7 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -5,13 +5,13 @@ use std::marker::PhantomData; 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; @@ -885,17 +885,7 @@ unsafe extern "C" { pub fn LLVMGetPoison(Ty: &Type) -> &Value; // Operations on metadata - // FIXME: deprecated, replace with LLVMMDStringInContext2 - pub fn LLVMMDStringInContext(C: &Context, Str: *const c_char, SLen: c_uint) -> &Value; - pub fn LLVMMDStringInContext2(C: &Context, Str: *const c_char, SLen: size_t) -> &Metadata; - - // FIXME: deprecated, replace with LLVMMDNodeInContext2 - pub fn LLVMMDNodeInContext<'a>( - C: &'a Context, - Vals: *const &'a Value, - Count: c_uint, - ) -> &'a Value; pub fn LLVMMDNodeInContext2<'a>( C: &'a Context, Vals: *const &'a Metadata, diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index fd8db4ad1d5f2..71fd7afb148c4 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::small_c_str::SmallCStr; 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/type_.rs b/compiler/rustc_codegen_llvm/src/type_.rs index 2c2b9030b7c95..f1efc7a3dacb8 100644 --- a/compiler/rustc_codegen_llvm/src/type_.rs +++ b/compiler/rustc_codegen_llvm/src/type_.rs @@ -13,7 +13,7 @@ use rustc_target::abi::{AddressSpace, Align, Integer, Size}; use crate::abi::{FnAbiLlvmExt, LlvmType}; use crate::context::CodegenCx; pub(crate) use crate::llvm::Type; -use crate::llvm::{Bool, False, True}; +use crate::llvm::{Bool, False, Metadata, True}; use crate::type_of::LayoutLlvmExt; use crate::value::Value; use crate::{common, llvm}; @@ -283,43 +283,31 @@ impl<'ll, 'tcx> LayoutTypeCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { impl<'ll, 'tcx> TypeMembershipCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { fn add_type_metadata(&self, function: &'ll Value, typeid: String) { let typeid_metadata = self.typeid_metadata(typeid).unwrap(); - let v = [self.const_usize(0), typeid_metadata]; unsafe { + let v = [llvm::LLVMValueAsMetadata(self.const_usize(0)), typeid_metadata]; llvm::LLVMRustGlobalAddMetadata( function, llvm::MD_type as c_uint, - llvm::LLVMValueAsMetadata(llvm::LLVMMDNodeInContext( - self.llcx, - v.as_ptr(), - v.len() as c_uint, - )), + llvm::LLVMMDNodeInContext2(self.llcx, v.as_ptr(), v.len()), ) } } fn set_type_metadata(&self, function: &'ll Value, typeid: String) { let typeid_metadata = self.typeid_metadata(typeid).unwrap(); - let v = [self.const_usize(0), typeid_metadata]; unsafe { + let v = [llvm::LLVMValueAsMetadata(self.const_usize(0)), typeid_metadata]; llvm::LLVMGlobalSetMetadata( function, llvm::MD_type as c_uint, - llvm::LLVMValueAsMetadata(llvm::LLVMMDNodeInContext( - self.llcx, - v.as_ptr(), - v.len() as c_uint, - )), + llvm::LLVMMDNodeInContext2(self.llcx, v.as_ptr(), v.len()), ) } } - fn typeid_metadata(&self, typeid: String) -> Option<&'ll Value> { + fn typeid_metadata(&self, typeid: String) -> Option<&'ll Metadata> { Some(unsafe { - llvm::LLVMMDStringInContext( - self.llcx, - typeid.as_ptr() as *const c_char, - typeid.len() as c_uint, - ) + llvm::LLVMMDStringInContext2(self.llcx, typeid.as_ptr() as *const c_char, typeid.len()) }) } diff --git a/compiler/rustc_codegen_llvm/src/va_arg.rs b/compiler/rustc_codegen_llvm/src/va_arg.rs index 781cee81180b2..f12b94d5887ea 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 a665f5c93060d..2f48c1fbf0d7d 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::io::{self, Write}; 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 @@ impl<'a> ArchiveBuilder for ArArchiveBuilder<'a> { let member_path = archive_path.parent().unwrap().join(Path::new(&file_name)); self.entries.push((file_name.into_bytes(), ArchiveEntry::File(member_path))); } else { - self.entries.push(( - file_name.into_bytes(), - ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() }, - )); + self.entries.push((file_name.into_bytes(), ArchiveEntry::FromArchive { + archive_index, + file_range: entry.file_range(), + })); } } } diff --git a/compiler/rustc_codegen_ssa/src/back/link.rs b/compiler/rustc_codegen_ssa/src/back/link.rs index 8b855bd0dd568..892dfb91201e3 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_data_structures::temp_dir::MaybeTempDir; 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::search_paths::PathKind; 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 tracing::{debug, info, warn}; 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 06fc164893fda..84817e1984458 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::dependency_format::Linkage; 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 1e1e039882be0..ab8b06a05fc74 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_data_structures::memmap::Mmap; 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 ff87f7f1ea45f..06433484ea3cd 100644 --- a/compiler/rustc_codegen_ssa/src/back/metadata.rs +++ b/compiler/rustc_codegen_ssa/src/back/metadata.rs @@ -7,19 +7,20 @@ use std::path::Path; 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 0de0b8a52b192..39034842d1086 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 257e2dfac006a..77c35a1fe79e9 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 std::collections::hash_map::Entry::*; 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 c170cd41ec49d..4d81ff933dded 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::any::Any; 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_hir::def_id::{CrateNum, LOCAL_CRATE}; 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 super::symbol_export::symbol_name_for_instance_in_crate; 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 3d1007a46737b..8e4385bee1aa3 100644 --- a/compiler/rustc_codegen_ssa/src/base.rs +++ b/compiler/rustc_codegen_ssa/src/base.rs @@ -3,7 +3,7 @@ use std::collections::BTreeSet; 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::codegen_fn_attrs::CodegenFnAttrs; 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::assert_module_sources::CguReuse; 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 9bd8a84f5a3f0..e99c3a462711c 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_middle::ty::{self as ty, TyCtxt}; 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 58877379e2686..08b326e3ac3c6 100644 --- a/compiler/rustc_codegen_ssa/src/errors.rs +++ b/compiler/rustc_codegen_ssa/src/errors.rs @@ -10,8 +10,8 @@ use rustc_errors::{ 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 26d4d0acac5c0..ec0520fbb09d3 100644 --- a/compiler/rustc_codegen_ssa/src/lib.rs +++ b/compiler/rustc_codegen_ssa/src/lib.rs @@ -37,10 +37,10 @@ use rustc_middle::middle::exported_symbols::SymbolExportKind; 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 25712095e76e1..43b8230c679e1 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_data_structures::graph::dominators::Dominators; 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 f23ae7abafdb3..125d3b908c733 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::ty::{self, Instance, Ty}; 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::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphizat 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 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { if let Some(slot) = self.personality_slot { slot } else { - let layout = cx.layout_of(Ty::new_tup( - cx.tcx(), - &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32], - )); + let layout = cx.layout_of(Ty::new_tup(cx.tcx(), &[ + Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), + cx.tcx().types.i32, + ])); let slot = PlaceRef::alloca(bx, layout); self.personality_slot = Some(slot); slot diff --git a/compiler/rustc_codegen_ssa/src/mir/coverageinfo.rs b/compiler/rustc_codegen_ssa/src/mir/coverageinfo.rs index 52e749f4fb75f..33a050ef2804f 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 5b36a11aa2546..9874809ea2bbe 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::layout::{LayoutOf, TyAndLayout}; 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 4acbc04c505e8..71541e6ab41a1 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 68fb5cb220692..202baddec723e 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 ee32b4f23c9dc..17f66c12a0332 100644 --- a/compiler/rustc_codegen_ssa/src/mir/operand.rs +++ b/compiler/rustc_codegen_ssa/src/mir/operand.rs @@ -4,17 +4,17 @@ use std::fmt; 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 eba150c6eac6e..0b764ae7747d8 100644 --- a/compiler/rustc_codegen_ssa/src/mir/place.rs +++ b/compiler/rustc_codegen_ssa/src/mir/place.rs @@ -415,11 +415,10 @@ impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> { 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 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { LocalRef::Operand(..) => { if place_ref.is_indirect_first_projection() { base = 1; - let cg_base = self.codegen_consume( - bx, - mir::PlaceRef { projection: &place_ref.projection[..0], ..place_ref }, - ); + let cg_base = self.codegen_consume(bx, mir::PlaceRef { + projection: &place_ref.projection[..0], + ..place_ref + }); cg_base.deref(bx.cx()) } else { bug!("using operand local {:?} as place", place_ref); diff --git a/compiler/rustc_codegen_ssa/src/mir/rvalue.rs b/compiler/rustc_codegen_ssa/src/mir/rvalue.rs index 6bf75293fce45..f9c0f3ce94146 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::layout::{HasTyCtxt, LayoutOf, TyAndLayout}; 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::place::PlaceRef; 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))] @@ -34,7 +34,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { } mir::Rvalue::Cast( - mir::CastKind::PointerCoercion(PointerCoercion::Unsize), + mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _), ref source, _, ) => { @@ -465,7 +465,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { let lladdr = bx.ptrtoint(llptr, llcast_ty); OperandValue::Immediate(lladdr) } - mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer) => { + mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _) => { match *operand.layout.ty.kind() { ty::FnDef(def_id, args) => { let instance = ty::Instance::resolve_for_fn_ptr( @@ -481,7 +481,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { _ => bug!("{} cannot be reified to a fn ptr", operand.layout.ty), } } - mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_)) => { + mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => { match *operand.layout.ty.kind() { ty::Closure(def_id, args) => { let instance = Instance::resolve_closure( @@ -496,11 +496,11 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { _ => bug!("{} cannot be cast to a fn ptr", operand.layout.ty), } } - mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer) => { + mir::CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => { // This is a no-op at the LLVM level. operand.val } - mir::CastKind::PointerCoercion(PointerCoercion::Unsize) => { + mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) => { assert!(bx.cx().is_backend_scalar_pair(cast)); let (lldata, llextra) = operand.val.pointer_parts(); let (lldata, llextra) = @@ -508,7 +508,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { OperandValue::Pair(lldata, llextra) } mir::CastKind::PointerCoercion( - PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, + PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, _ ) => { bug!("{kind:?} is for borrowck, and should never appear in codegen"); } @@ -526,7 +526,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { bug!("unexpected non-pair operand"); } } - mir::CastKind::DynStar => { + mir::CastKind::PointerCoercion(PointerCoercion::DynStar, _) => { let (lldata, llextra) = operand.val.pointer_parts(); let (lldata, llextra) = base::cast_to_dyn_star(bx, lldata, operand.layout, cast.ty, llextra); diff --git a/compiler/rustc_codegen_ssa/src/mono_item.rs b/compiler/rustc_codegen_ssa/src/mono_item.rs index 64fcefdc860cd..038c5857face1 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 0349d5817b451..dfe8fd616e4a2 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::fx::FxIndexSet; 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 e45af1cd15307..676fb181d67cc 100644 --- a/compiler/rustc_codegen_ssa/src/traits/backend.rs +++ b/compiler/rustc_codegen_ssa/src/traits/backend.rs @@ -5,22 +5,23 @@ use rustc_ast::expand::allocator::AllocatorKind; 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}; pub trait BackendTypes { type Value: CodegenObject; + type Metadata: CodegenObject; type Function: CodegenObject; type BasicBlock: Copy; diff --git a/compiler/rustc_codegen_ssa/src/traits/builder.rs b/compiler/rustc_codegen_ssa/src/traits/builder.rs index 5af0457bebdd3..c0c1085e949e2 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::intrinsic::IntrinsicCallBuilderMethods; 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 { @@ -51,6 +51,7 @@ pub trait BuilderMethods<'a, 'tcx>: type CodegenCx: CodegenMethods< 'tcx, Value = Self::Value, + Metadata = Self::Metadata, Function = Self::Function, BasicBlock = Self::BasicBlock, Type = Self::Type, diff --git a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs index 7526c221b0536..c26d4532d0f14 100644 --- a/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs +++ b/compiler/rustc_codegen_ssa/src/traits/debuginfo.rs @@ -3,8 +3,8 @@ use std::ops::Range; 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/intrinsic.rs b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs index e721cfb71342f..5b9274b48248c 100644 --- a/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs +++ b/compiler/rustc_codegen_ssa/src/traits/intrinsic.rs @@ -24,14 +24,14 @@ pub trait IntrinsicCallBuilderMethods<'tcx>: BackendTypes { fn assume(&mut self, val: Self::Value); fn expect(&mut self, cond: Self::Value, expected: bool) -> Self::Value; /// Trait method used to test whether a given pointer is associated with a type identifier. - fn type_test(&mut self, pointer: Self::Value, typeid: Self::Value) -> Self::Value; + fn type_test(&mut self, pointer: Self::Value, typeid: Self::Metadata) -> Self::Value; /// Trait method used to load a function while testing if it is associated with a type /// identifier. fn type_checked_load( &mut self, llvtable: Self::Value, vtable_byte_offset: u64, - typeid: Self::Value, + typeid: Self::Metadata, ) -> Self::Value; /// Trait method used to inject `va_start` on the "spoofed" `VaListImpl` in /// Rust defined C-variadic functions. diff --git a/compiler/rustc_codegen_ssa/src/traits/mod.rs b/compiler/rustc_codegen_ssa/src/traits/mod.rs index 2196bc996d9a6..800470286bc94 100644 --- a/compiler/rustc_codegen_ssa/src/traits/mod.rs +++ b/compiler/rustc_codegen_ssa/src/traits/mod.rs @@ -27,8 +27,8 @@ mod write; 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 f6f309287fe2e..f862434c8ef78 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_middle::ty::{self, Ty}; 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; @@ -152,7 +152,7 @@ pub trait LayoutTypeCodegenMethods<'tcx>: BackendTypes { pub trait TypeMembershipCodegenMethods<'tcx>: BackendTypes { fn add_type_metadata(&self, _function: Self::Function, _typeid: String) {} fn set_type_metadata(&self, _function: Self::Function, _typeid: String) {} - fn typeid_metadata(&self, _typeid: String) -> Option { + fn typeid_metadata(&self, _typeid: String) -> Option { None } fn add_kcfi_type_metadata(&self, _function: Self::Function, _typeid: u32) {} diff --git a/compiler/rustc_const_eval/messages.ftl b/compiler/rustc_const_eval/messages.ftl index 2dc9d57e3b5c7..73a9a1569f64e 100644 --- a/compiler/rustc_const_eval/messages.ftl +++ b/compiler/rustc_const_eval/messages.ftl @@ -198,7 +198,7 @@ const_eval_invalid_vtable_pointer = using {$pointer} as vtable pointer but it does not point to a vtable const_eval_invalid_vtable_trait = - using vtable for trait `{$vtable_trait}` but trait `{$expected_trait}` was expected + using vtable for `{$vtable_dyn_type}` but `{$expected_dyn_type}` was expected const_eval_lazy_lock = consider wrapping this expression in `std::sync::LazyLock::new(|| ...)` @@ -459,7 +459,7 @@ const_eval_validation_invalid_fn_ptr = {$front_matter}: encountered {$value}, bu const_eval_validation_invalid_ref_meta = {$front_matter}: encountered invalid reference metadata: total size is bigger than largest supported object const_eval_validation_invalid_ref_slice_meta = {$front_matter}: encountered invalid reference metadata: slice is bigger than largest supported object const_eval_validation_invalid_vtable_ptr = {$front_matter}: encountered {$value}, but expected a vtable pointer -const_eval_validation_invalid_vtable_trait = {$front_matter}: wrong trait in wide pointer vtable: expected `{$ref_trait}`, but encountered `{$vtable_trait}` +const_eval_validation_invalid_vtable_trait = {$front_matter}: wrong trait in wide pointer vtable: expected `{$expected_dyn_type}`, but encountered `{$vtable_dyn_type}` const_eval_validation_mutable_ref_to_immutable = {$front_matter}: encountered mutable reference or box pointing to read-only memory const_eval_validation_never_val = {$front_matter}: encountered a value of the never type `!` const_eval_validation_null_box = {$front_matter}: encountered a null box diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 6d09ed5b4bfc2..e1b605979972d 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::mir::*; 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}; @@ -440,6 +440,7 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { | PointerCoercion::UnsafeFnPointer | PointerCoercion::ClosureFnPointer(_) | PointerCoercion::ReifyFnPointer, + _, ), _, _, @@ -447,8 +448,12 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // These are all okay; they only change the type, not the data. } - Rvalue::Cast(CastKind::PointerCoercion(PointerCoercion::Unsize), _, _) => { - // Unsizing is implemented for CTFE. + Rvalue::Cast( + CastKind::PointerCoercion(PointerCoercion::Unsize | PointerCoercion::DynStar, _), + _, + _, + ) => { + // Unsizing and `dyn*` coercions are implemented for CTFE. } Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => { @@ -458,10 +463,6 @@ impl<'tcx> Visitor<'tcx> for Checker<'_, 'tcx> { // Since no pointer can ever get exposed (rejected above), this is easy to support. } - Rvalue::Cast(CastKind::DynStar, _, _) => { - // `dyn*` coercion is implemented for CTFE. - } - Rvalue::Cast(_, _, _) => {} Rvalue::NullaryOp( diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index a52fc6a077b4c..df8313d0e7038 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 f0998300dc843..f98234ce7f3c1 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 c566dc7fa844d..7358a6c6d2256 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 @@ impl Qualif for NeedsNonConstDrop { 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 681184f7fbcde..eb5024c36f4b6 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_middle::mir::{ 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 aa7449e8ad269..ed1c912e6cb03 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_middle::{bug, span_bug, ty}; 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 25b32785b7d3e..fd05664e2f227 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 rustc_span::{Span, Symbol}; 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 337eab7a1c2cc..a241edbd77ad9 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::layout::LayoutOf; 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 6a691abae026d..6d74998b7d88e 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 std::ops::ControlFlow; 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 super::error::*; 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 @@ impl<'tcx> CompileTimeInterpCx<'tcx> { 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 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { // 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 8add23ed22fb3..48aeee2e6f05e 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_middle::{bug, mir}; 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 fn_queries; 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 8351a6af25b81..a11d491bdd2c9 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 tracing::{debug, instrument, trace}; 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 b66b5c0a00a2f..c60bacb85067f 100644 --- a/compiler/rustc_const_eval/src/errors.rs +++ b/compiler/rustc_const_eval/src/errors.rs @@ -15,8 +15,8 @@ use rustc_middle::mir::interpret::{ }; 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 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { } ShiftOverflow { intrinsic, shift_amount } => { diag.arg("intrinsic", intrinsic); - diag.arg( - "shift_amount", - match shift_amount { - Either::Left(v) => v.to_string(), - Either::Right(v) => v.to_string(), - }, - ); + diag.arg("shift_amount", match shift_amount { + Either::Left(v) => v.to_string(), + Either::Right(v) => v.to_string(), + }); } BoundsCheckFailed { len, index } => { diag.arg("len", len); @@ -523,12 +522,9 @@ impl<'a> ReportErrorExt for UndefinedBehaviorInfo<'a> { UnterminatedCString(ptr) | InvalidFunctionPointer(ptr) | InvalidVTablePointer(ptr) => { diag.arg("pointer", ptr); } - InvalidVTableTrait { expected_trait, vtable_trait } => { - diag.arg("expected_trait", expected_trait.to_string()); - diag.arg( - "vtable_trait", - vtable_trait.map(|t| t.to_string()).unwrap_or_else(|| format!("")), - ); + InvalidVTableTrait { expected_dyn_type, vtable_dyn_type } => { + diag.arg("expected_dyn_type", expected_dyn_type.to_string()); + diag.arg("vtable_dyn_type", vtable_dyn_type.to_string()); } PointerUseAfterFree(alloc_id, msg) => { diag.arg("alloc_id", alloc_id) @@ -778,12 +774,9 @@ impl<'tcx> ReportErrorExt for ValidationErrorInfo<'tcx> { DanglingPtrNoProvenance { pointer, .. } => { err.arg("pointer", pointer); } - InvalidMetaWrongTrait { expected_trait: ref_trait, vtable_trait } => { - err.arg("ref_trait", ref_trait.to_string()); - err.arg( - "vtable_trait", - vtable_trait.map(|t| t.to_string()).unwrap_or_else(|| format!("")), - ); + InvalidMetaWrongTrait { vtable_dyn_type, expected_dyn_type } => { + err.arg("vtable_dyn_type", vtable_dyn_type.to_string()); + err.arg("expected_dyn_type", expected_dyn_type.to_string()); } NullPtr { .. } | ConstRefToMutable diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 0f2b22f035bc8..f5a0a2c0ee360 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -14,9 +14,9 @@ use rustc_target::spec::abi::Abi; 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 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } // Fall back to exact equality. - // FIXME: We are missing the rules for "repr(C) wrapping compatible types". Ok(caller == callee) } @@ -234,6 +233,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { // 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 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { "caller ABI: {:#?}, args: {:#?}", caller_fn_abi, args.iter() - .map(|arg| ( - arg.layout().ty, - match arg { - FnArg::Copy(op) => format!("copy({op:?})"), - FnArg::InPlace(mplace) => format!("in-place({mplace:?})"), - } - )) + .map(|arg| (arg.layout().ty, match arg { + FnArg::Copy(op) => format!("copy({op:?})"), + FnArg::InPlace(mplace) => format!("in-place({mplace:?})"), + })) .collect::>() ); trace!( @@ -853,13 +850,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { ); // Check `unwinding`. - assert_eq!( - unwinding, - match self.frame().loc { - Left(loc) => self.body().basic_blocks[loc.block].is_cleanup, - Right(_) => true, - } - ); + assert_eq!(unwinding, match self.frame().loc { + Left(loc) => self.body().basic_blocks[loc.block].is_cleanup, + Right(_) => true, + }); if unwinding && self.frame_idx() == 0 { throw_ub_custom!(fluent::const_eval_unwind_past_top); } diff --git a/compiler/rustc_const_eval/src/interpret/cast.rs b/compiler/rustc_const_eval/src/interpret/cast.rs index e8c9f145eea55..85e7d91c2ad50 100644 --- a/compiler/rustc_const_eval/src/interpret/cast.rs +++ b/compiler/rustc_const_eval/src/interpret/cast.rs @@ -2,8 +2,8 @@ use std::assert_matches::assert_matches; 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 tracing::trace; 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; @@ -32,7 +32,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { if cast_ty == dest.layout.ty { dest.layout } else { self.layout_of(cast_ty)? }; // FIXME: In which cases should we trigger UB when the source is uninit? match cast_kind { - CastKind::PointerCoercion(PointerCoercion::Unsize) => { + CastKind::PointerCoercion(PointerCoercion::Unsize, _) => { self.unsize_into(src, cast_layout, dest)?; } @@ -68,11 +68,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { CastKind::PointerCoercion( PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, + _, ) => { bug!("{cast_kind:?} casts are for borrowck only, not runtime MIR"); } - CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer) => { + CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _) => { // All reifications must be monomorphic, bail out otherwise. ensure_monomorphic_enough(*self.tcx, src.layout.ty)?; @@ -94,7 +95,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } - CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer) => { + CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => { let src = self.read_immediate(src)?; match cast_ty.kind() { ty::FnPtr(..) => { @@ -105,7 +106,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } - CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_)) => { + CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _) => { // All reifications must be monomorphic, bail out otherwise. ensure_monomorphic_enough(*self.tcx, src.layout.ty)?; @@ -125,10 +126,10 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } - CastKind::DynStar => { + CastKind::PointerCoercion(PointerCoercion::DynStar, _) => { if let ty::Dynamic(data, _, ty::DynStar) = cast_ty.kind() { // Initial cast from sized to dyn trait - let vtable = self.get_vtable_ptr(src.layout.ty, data.principal())?; + let vtable = self.get_vtable_ptr(src.layout.ty, data)?; let vtable = Scalar::from_maybe_pointer(vtable, self); let data = self.read_immediate(src)?.to_scalar(); let _assert_pointer_like = data.to_pointer(self)?; @@ -446,12 +447,12 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } // Get the destination trait vtable and return that. - let new_vptr = self.get_vtable_ptr(ty, data_b.principal())?; + let new_vptr = self.get_vtable_ptr(ty, data_b)?; self.write_immediate(Immediate::new_dyn_trait(old_data, new_vptr, self), dest) } (_, &ty::Dynamic(data, _, ty::Dyn)) => { // Initial cast from sized to dyn trait - let vtable = self.get_vtable_ptr(src_pointee_ty, data.principal())?; + let vtable = self.get_vtable_ptr(src_pointee_ty, data)?; let ptr = self.read_pointer(src)?; let val = Immediate::new_dyn_trait(ptr, vtable, &*self.tcx); self.write_immediate(val, dest) diff --git a/compiler/rustc_const_eval/src/interpret/discriminant.rs b/compiler/rustc_const_eval/src/interpret/discriminant.rs index de93ed85704b5..3bab2b3261e1e 100644 --- a/compiler/rustc_const_eval/src/interpret/discriminant.rs +++ b/compiler/rustc_const_eval/src/interpret/discriminant.rs @@ -7,7 +7,7 @@ use rustc_target::abi::{self, TagEncoding, VariantIdx, Variants}; 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 16d40fcceb6bb..f4c4a6fb0bf5b 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 rustc_trait_selection::traits::ObligationCtxt; 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 5df989b4c1d1e..81659df7c533b 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::def_id::LocalDefId; 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 b3f4fd5e2a107..e1fd8bea1f30c 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::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic}; 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 67c9993405979..a809f74e8eb90 100644 --- a/compiler/rustc_const_eval/src/interpret/machine.rs +++ b/compiler/rustc_const_eval/src/interpret/machine.rs @@ -9,18 +9,18 @@ use std::hash::Hash; 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 b1d1dab7c162b..c3b506d848cdb 100644 --- a/compiler/rustc_const_eval/src/interpret/memory.rs +++ b/compiler/rustc_const_eval/src/interpret/memory.rs @@ -21,10 +21,10 @@ use rustc_target::abi::{Align, HasDataLayout, Size}; 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; @@ -943,12 +943,13 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { if offset.bytes() != 0 { throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset))) } - let Some(GlobalAlloc::VTable(ty, vtable_trait)) = self.tcx.try_get_global_alloc(alloc_id) + let Some(GlobalAlloc::VTable(ty, vtable_dyn_type)) = + self.tcx.try_get_global_alloc(alloc_id) else { throw_ub!(InvalidVTablePointer(Pointer::new(alloc_id, offset))) }; - if let Some(expected_trait) = expected_trait { - self.check_vtable_for_type(vtable_trait, expected_trait)?; + if let Some(expected_dyn_type) = expected_trait { + self.check_vtable_for_type(vtable_dyn_type, expected_dyn_type)?; } Ok(ty) } @@ -1113,11 +1114,8 @@ impl<'a, 'tcx, M: Machine<'tcx>> std::fmt::Debug for DumpAllocs<'a, 'tcx, M> { Some(GlobalAlloc::Function { instance, .. }) => { write!(fmt, " (fn: {instance})")?; } - Some(GlobalAlloc::VTable(ty, Some(trait_ref))) => { - write!(fmt, " (vtable: impl {trait_ref} for {ty})")?; - } - Some(GlobalAlloc::VTable(ty, None)) => { - write!(fmt, " (vtable: impl for {ty})")?; + Some(GlobalAlloc::VTable(ty, dyn_ty)) => { + write!(fmt, " (vtable: impl {dyn_ty} for {ty})")?; } Some(GlobalAlloc::Static(did)) => { write!(fmt, " (static: {})", self.ecx.tcx.def_path_str(did))?; diff --git a/compiler/rustc_const_eval/src/interpret/mod.rs b/compiler/rustc_const_eval/src/interpret/mod.rs index 561d681f804a1..5e84626f77e7a 100644 --- a/compiler/rustc_const_eval/src/interpret/mod.rs +++ b/compiler/rustc_const_eval/src/interpret/mod.rs @@ -19,18 +19,18 @@ mod util; 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 ead3ef6861a2f..31ee3e6519afc 100644 --- a/compiler/rustc_const_eval/src/interpret/operand.rs +++ b/compiler/rustc_const_eval/src/interpret/operand.rs @@ -14,9 +14,9 @@ use rustc_target::abi::{self, Abi, HasDataLayout, Size}; 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 7d32fcbb664ab..863b330a74cd5 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_span::symbol::sym; 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 e398c4c074215..32f90254a9470 100644 --- a/compiler/rustc_const_eval/src/interpret/place.rs +++ b/compiler/rustc_const_eval/src/interpret/place.rs @@ -6,16 +6,16 @@ use std::assert_matches::assert_matches; 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 58ce44e4014e0..621afdb1050a2 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 db418c82f663f..15868f1b02d92 100644 --- a/compiler/rustc_const_eval/src/interpret/stack.rs +++ b/compiler/rustc_const_eval/src/interpret/stack.rs @@ -15,9 +15,9 @@ use rustc_span::Span; 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 70cfba1922c6e..8e2367e0d214c 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::ty::{self, Instance, Ty}; 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 cd4faf06655fe..8eead6018ac4a 100644 --- a/compiler/rustc_const_eval/src/interpret/traits.rs +++ b/compiler/rustc_const_eval/src/interpret/traits.rs @@ -1,36 +1,35 @@ use rustc_middle::mir::interpret::{InterpResult, Pointer}; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::{self, Ty, TyCtxt, VtblEntry}; +use rustc_middle::ty::{self, ExistentialPredicateStableCmpExt, Ty, TyCtxt, VtblEntry}; use rustc_target::abi::{Align, Size}; 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 /// objects. /// - /// The `trait_ref` encodes the erased self type. Hence, if we are making an object `Foo` - /// from a value of type `Foo`, then `trait_ref` would map `T: Trait`. `None` here means that - /// this is an auto trait without any methods, so we only need the basic vtable (drop, size, - /// align). + /// The `dyn_ty` encodes the erased self type. Hence, if we are making an object + /// `Foo + Send>` from a value of type `Foo`, then `dyn_ty` + /// would be `Trait + Send`. If this list doesn't have a principal trait ref, + /// we only need the basic vtable prefix (drop, size, align). pub fn get_vtable_ptr( &self, ty: Ty<'tcx>, - poly_trait_ref: Option>, + dyn_ty: &'tcx ty::List>, ) -> InterpResult<'tcx, Pointer>> { - trace!("get_vtable(trait_ref={:?})", poly_trait_ref); + trace!("get_vtable(ty={ty:?}, dyn_ty={dyn_ty:?})"); - let (ty, poly_trait_ref) = self.tcx.erase_regions((ty, poly_trait_ref)); + let (ty, dyn_ty) = self.tcx.erase_regions((ty, dyn_ty)); // All vtables must be monomorphic, bail out otherwise. ensure_monomorphic_enough(*self.tcx, ty)?; - ensure_monomorphic_enough(*self.tcx, poly_trait_ref)?; + ensure_monomorphic_enough(*self.tcx, dyn_ty)?; let salt = M::get_global_alloc_salt(self, None); - let vtable_symbolic_allocation = - self.tcx.reserve_and_set_vtable_alloc(ty, poly_trait_ref, salt); + let vtable_symbolic_allocation = self.tcx.reserve_and_set_vtable_alloc(ty, dyn_ty, salt); let vtable_ptr = self.global_root_pointer(Pointer::from(vtable_symbolic_allocation))?; Ok(vtable_ptr.into()) } @@ -64,17 +63,45 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { /// expected trait type. pub(super) fn check_vtable_for_type( &self, - vtable_trait: Option>, - expected_trait: &'tcx ty::List>, + vtable_dyn_type: &'tcx ty::List>, + expected_dyn_type: &'tcx ty::List>, ) -> InterpResult<'tcx> { - let eq = match (expected_trait.principal(), vtable_trait) { - (Some(a), Some(b)) => self.eq_in_param_env(a, b), - (None, None) => true, - _ => false, - }; - if !eq { - throw_ub!(InvalidVTableTrait { expected_trait, vtable_trait }); + // We check validity by comparing the lists of predicates for equality. We *could* instead + // check that the dynamic type to which the vtable belongs satisfies all the expected + // predicates, but that would likely be a lot slower and seems unnecessarily permissive. + + // FIXME: we are skipping auto traits for now, but might revisit this in the future. + let mut sorted_vtable: Vec<_> = vtable_dyn_type.without_auto_traits().collect(); + let mut sorted_expected: Vec<_> = expected_dyn_type.without_auto_traits().collect(); + // `skip_binder` here is okay because `stable_cmp` doesn't look at binders + sorted_vtable.sort_by(|a, b| a.skip_binder().stable_cmp(*self.tcx, &b.skip_binder())); + sorted_vtable.dedup(); + sorted_expected.sort_by(|a, b| a.skip_binder().stable_cmp(*self.tcx, &b.skip_binder())); + sorted_expected.dedup(); + + if sorted_vtable.len() != sorted_expected.len() { + throw_ub!(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }); + } + + for (a_pred, b_pred) in std::iter::zip(sorted_vtable, sorted_expected) { + let is_eq = match (a_pred.skip_binder(), b_pred.skip_binder()) { + ( + ty::ExistentialPredicate::Trait(a_data), + ty::ExistentialPredicate::Trait(b_data), + ) => self.eq_in_param_env(a_pred.rebind(a_data), b_pred.rebind(b_data)), + + ( + ty::ExistentialPredicate::Projection(a_data), + ty::ExistentialPredicate::Projection(b_data), + ) => self.eq_in_param_env(a_pred.rebind(a_data), b_pred.rebind(b_data)), + + _ => false, + }; + if !is_eq { + throw_ub!(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }); + } } + Ok(()) } diff --git a/compiler/rustc_const_eval/src/interpret/util.rs b/compiler/rustc_const_eval/src/interpret/util.rs index 490355f416cf4..2d53badf0f967 100644 --- a/compiler/rustc_const_eval/src/interpret/util.rs +++ b/compiler/rustc_const_eval/src/interpret/util.rs @@ -9,7 +9,7 @@ use rustc_middle::ty::{ }; 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 b20df7ac9c1d1..203cceccd9d1f 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_hir as hir; 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 tracing::trace; 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 @@ -452,8 +452,8 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { self.path, Ub(DanglingIntPointer{ .. } | InvalidVTablePointer(..)) => InvalidVTablePtr { value: format!("{vtable}") }, - Ub(InvalidVTableTrait { expected_trait, vtable_trait }) => { - InvalidMetaWrongTrait { expected_trait, vtable_trait: *vtable_trait } + Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }) => { + InvalidMetaWrongTrait { vtable_dyn_type, expected_dyn_type } }, ); } @@ -803,10 +803,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { if start == 1 && end == max_value { // Only null is the niche. So make sure the ptr is NOT null. if self.ecx.scalar_may_be_null(scalar)? { - throw_validation_failure!( - self.path, - NullablePtrOutOfRange { range: valid_range, max_value } - ) + throw_validation_failure!(self.path, NullablePtrOutOfRange { + range: valid_range, + max_value + }) } else { return Ok(()); } @@ -816,10 +816,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { } else { // Conservatively, we reject, because the pointer *could* have a bad // value. - throw_validation_failure!( - self.path, - PtrOutOfRange { range: valid_range, max_value } - ) + throw_validation_failure!(self.path, PtrOutOfRange { + range: valid_range, + max_value + }) } } }; @@ -827,10 +827,11 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { 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 + }) } } @@ -1280,8 +1281,8 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValueVisitor<'tcx, M> for ValidityVisitor<'rt, self.path, // It's not great to catch errors here, since we can't give a very good path, // but it's better than ICEing. - Ub(InvalidVTableTrait { expected_trait, vtable_trait }) => { - InvalidMetaWrongTrait { expected_trait, vtable_trait: *vtable_trait } + Ub(InvalidVTableTrait { vtable_dyn_type, expected_dyn_type }) => { + InvalidMetaWrongTrait { vtable_dyn_type, expected_dyn_type: *expected_dyn_type } }, ); } diff --git a/compiler/rustc_const_eval/src/interpret/visitor.rs b/compiler/rustc_const_eval/src/interpret/visitor.rs index d8af67bd0e705..d004a3f08929f 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_middle::ty::{self, Ty}; 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 73dda81bd298b..cbe8a043fba00 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 @@ pub mod util; 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 eb185bee5c07b..7f4c36835e449 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_middle::{bug, mir}; 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 efc56dc93373b..16c66824c5ba1 100644 --- a/compiler/rustc_data_structures/src/fingerprint.rs +++ b/compiler/rustc_data_structures/src/fingerprint.rs @@ -3,7 +3,7 @@ use std::hash::{Hash, Hasher}; 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 0d76df27a0a39..9739e501272c4 100644 --- a/compiler/rustc_data_structures/src/flock/windows.rs +++ b/compiler/rustc_data_structures/src/flock/windows.rs @@ -6,8 +6,8 @@ use std::path::Path; 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 6c078ca7c6ee4..ef82193a4b9df 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 32a6d9ec881a9..7a240f4e58bcc 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 373f87bfdbcfa..7c876c82af293 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 a58c6ee1bccb6..8391e98ba8b07 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 324b8ecf2d393..e9ef7ea5afc74 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 03aa1d8f67862..d0b6fe2bc6fd0 100644 --- a/compiler/rustc_data_structures/src/sharded.rs +++ b/compiler/rustc_data_structures/src/sharded.rs @@ -8,7 +8,7 @@ use either::Either; 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 9673f94d7a433..0872bd2c9acc9 100644 --- a/compiler/rustc_data_structures/src/stable_hasher.rs +++ b/compiler/rustc_data_structures/src/stable_hasher.rs @@ -14,7 +14,7 @@ pub use rustc_stable_hash::{ 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 7cf942685e3e1..012ee7f900eaa 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 2b89431c2ed79..c7df19842d6d5 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 disabled::*; 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 @@ mod disabled { #[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 490d7d3ddd57c..ca052e2eac6db 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 44a6b03177e58..76b7270d4b815 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -24,7 +24,7 @@ use std::ffi::OsString; 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::traits::CodegenBackend; 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 74225d646bd2d..0733b8c0b98a1 100644 --- a/compiler/rustc_driver_impl/src/pretty.rs +++ b/compiler/rustc_driver_impl/src/pretty.rs @@ -8,11 +8,11 @@ use rustc_errors::FatalError; 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 411661824f0a2..d4f8199390cc5 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 e84d7be45d7a0..2ede7d805fa40 100644 --- a/compiler/rustc_error_messages/src/lib.rs +++ b/compiler/rustc_error_messages/src/lib.rs @@ -16,20 +16,20 @@ use std::path::{Path, PathBuf}; 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 556e6d46f899d..f468fbf4497e0 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 6b756cff225de..4352de3ad25fe 100644 --- a/compiler/rustc_errors/src/diagnostic.rs +++ b/compiler/rustc_errors/src/diagnostic.rs @@ -7,12 +7,12 @@ use std::panic; 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 9e3bc3e60b12f..19529f06ef1d2 100644 --- a/compiler/rustc_errors/src/diagnostic_impls.rs +++ b/compiler/rustc_errors/src/diagnostic_impls.rs @@ -7,9 +7,9 @@ use std::process::ExitStatus; 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 {rustc_ast as ast, rustc_hir as hir}; 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 3ab371b805752..1dc52c4d0a423 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_error_messages::{FluentArgs, SpanLabel}; 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 @@ use crate::snippet::{ 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 6a2ecf13f7b10..1972a522e394a 100644 --- a/compiler/rustc_errors/src/json.rs +++ b/compiler/rustc_errors/src/json.rs @@ -19,19 +19,19 @@ use derive_setters::Setters; 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 6af376d7afdb2..0de555b83d3ab 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 59866012069ca..39acacfbe59c8 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -42,6 +42,7 @@ use std::ops::DerefMut; 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 @@ pub use diagnostic_impls::{ 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 7557969f374ac..85199c34a147c 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 bfe4c9f2a3a2b..17a1635bd1143 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 8f9104135cddd..d0552a754feb0 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -15,8 +15,8 @@ use rustc_data_structures::sync::{self, Lrc}; 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::def_id::{CrateNum, DefId, LocalDefId}; 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 8ecdb551342dd..b5945759d43a0 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 @@ impl<'a> ExtCtxt<'a> { } 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 @@ impl<'a> ExtCtxt<'a> { } pub fn block_expr(&self, expr: P) -> P { - self.block( - expr.span, - thin_vec![ast::Stmt { - id: ast::DUMMY_NODE_ID, - span: expr.span, - kind: ast::StmtKind::Expr(expr), - }], - ) + self.block(expr.span, thin_vec![ast::Stmt { + id: ast::DUMMY_NODE_ID, + span: expr.span, + kind: ast::StmtKind::Expr(expr), + }]) } pub fn block(&self, span: Span, stmts: ThinVec) -> P { P(ast::Block { diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index b0d3fecbb479b..3208837427736 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -9,14 +9,14 @@ use rustc_ast::{self as ast, AttrStyle, Attribute, HasAttrs, HasTokens, MetaItem 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 84ae351ed72b6..079dcee99d3f4 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -8,7 +8,7 @@ use rustc_ast::mut_visit::*; 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 @@ use rustc_parse::parser::{ 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; @@ -42,9 +42,9 @@ use crate::errors::{ use crate::fluent_generated; use crate::mbe::diagnostics::annotate_err_with_kind; use crate::module::{ - mod_dir_path, mod_file_path_from_attr, parse_external_mod, DirOwnership, ParsedExternalMod, + DirOwnership, ParsedExternalMod, mod_dir_path, mod_file_path_from_attr, parse_external_mod, }; -use crate::placeholders::{placeholder, PlaceholderExpander}; +use crate::placeholders::{PlaceholderExpander, placeholder}; macro_rules! ast_fragments { ( diff --git a/compiler/rustc_expand/src/mbe.rs b/compiler/rustc_expand/src/mbe.rs index 08d4a03945489..e5d098f63d6d1 100644 --- a/compiler/rustc_expand/src/mbe.rs +++ b/compiler/rustc_expand/src/mbe.rs @@ -16,8 +16,8 @@ use metavar_expr::MetaVarExpr; 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 5778f6616227a..103bbb05e7ff3 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -12,11 +12,11 @@ use rustc_span::symbol::Ident; 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 68eeba6f415d5..b1d898b69494c 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 501a2417fcf31..3903203da3dbf 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::collections::hash_map::Entry::{Occupied, Vacant}; 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 256713ef73000..f40f99b6ea123 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::NtPatKind::*; 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 @@ use crate::base::{ 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 5df0aebfe57bd..f0a6c841f3121 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 2bd78d347368a..fb6fe0bb1d77b 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 27a9a330f3c5e..614f52bbd2851 100644 --- a/compiler/rustc_expand/src/module.rs +++ b/compiler/rustc_expand/src/module.rs @@ -2,13 +2,13 @@ use std::iter::once; 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; diff --git a/compiler/rustc_expand/src/placeholders.rs b/compiler/rustc_expand/src/placeholders.rs index 469bed3cd5926..610c69e9d21b4 100644 --- a/compiler/rustc_expand/src/placeholders.rs +++ b/compiler/rustc_expand/src/placeholders.rs @@ -4,9 +4,9 @@ use rustc_ast::token::Delimiter; 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 d1dcec0cc1574..dca0516f9f3b3 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -4,8 +4,8 @@ use rustc_ast::tokenstream::TokenStream; 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 5798bcedc2263..a7b251ab2527e 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -2,7 +2,7 @@ use std::ops::{Bound, Range}; 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::parser::Parser; 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 0088a7bbc1e50..70e92f545c639 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 fa5f152132ad3..17827b4e43b37 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 const BUILTIN_ATTRIBUTES: &[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 fe12930e6b9d6..8f4c0b0ac95f9 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 { } 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<'hir> Ty<'hir> { 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 @@ impl<'hir> InlineAsmOperand<'hir> { } pub fn is_clobber(&self) -> bool { - matches!( - self, - InlineAsmOperand::Out { reg: InlineAsmRegOrRegClass::Reg(_), late: _, expr: None } - ) + matches!(self, InlineAsmOperand::Out { + reg: InlineAsmRegOrRegClass::Reg(_), + late: _, + expr: None + }) } } diff --git a/compiler/rustc_hir/src/hir_id.rs b/compiler/rustc_hir/src/hir_id.rs index f2142359935b9..3fa06620ea8d1 100644 --- a/compiler/rustc_hir/src/hir_id.rs +++ b/compiler/rustc_hir/src/hir_id.rs @@ -2,10 +2,10 @@ use std::fmt::{self, Debug}; 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 a54596e3088dc..4da3224578519 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 c148dc7f53b7a..b161e6ba0fa51 100644 --- a/compiler/rustc_hir/src/lang_items.rs +++ b/compiler/rustc_hir/src/lang_items.rs @@ -11,8 +11,8 @@ use rustc_ast as ast; 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 73d1ea4070795..2ebbb4a06b6bf 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 f43008eda1181..155270ca6a7c2 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 16b3c4a9ab691..5c10fa4697156 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 ca133c5965dd0..337859cd1fbb1 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 46a0d4f498aa9..8d11328743c7e 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 14ea781629133..caf9960741d71 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 @@ impl<'tcx> Bounds<'tcx> { // 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 @@ impl<'tcx> Bounds<'tcx> { }; 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 1d686878eab4b..d725772a5b369 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::cell::LazyCell; 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_middle::ty::{ }; 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 cc7a0dff34e41..9ca5f25447b3e 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 std::iter; 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 @@ impl<'tcx> ty::FallibleTypeFolder> for RemapHiddenTyRegions<'tcx> { return Err(guar); }; - Ok(ty::Region::new_early_param( - self.tcx, - ty::EarlyParamRegion { - name: e.name, - index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32, - }, - )) + Ok(ty::Region::new_early_param(self.tcx, ty::EarlyParamRegion { + name: e.name, + index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32, + })) } } @@ -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 d2b7ede65234f..e07b587508a68 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_middle::ty::{ 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 d173915e480b0..97a29b32c0158 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 83d2c2c1e285f..7da2cd93d4e01 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_infer::infer::TyCtxtInferExt; 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 22d7d1fea9cb4..64307407b73e3 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 c2b2f08132ed8..25e219ef3f23a 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 3d5a22fce85af..71eb368185eb8 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_hir::{self as hir, LangItem}; 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 3a7366ef78abe..d3d88919d8795 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -75,7 +75,7 @@ use std::num::NonZero; 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::ty::{self, GenericArgs, GenericArgsRef, Ty, TyCtxt}; 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 10b3fe380ab69..f8a19e93a4128 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -4,11 +4,11 @@ use std::ops::{ControlFlow, Deref}; 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::ty::{ }; 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 480116a624921..bea8d28a9f756 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -7,20 +7,20 @@ use std::collections::BTreeMap; 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 9fce927e2c7f2..dfb3c088afb0c 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 as hir; 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; @@ -22,36 +22,38 @@ use crate::errors; pub(crate) fn crate_inherent_impls( tcx: TyCtxt<'_>, (): (), -) -> Result<&'_ CrateInherentImpls, ErrorGuaranteed> { +) -> (&'_ CrateInherentImpls, Result<(), ErrorGuaranteed>) { let mut collect = InherentCollect { tcx, impls_map: Default::default() }; + let mut res = Ok(()); for id in tcx.hir().items() { res = res.and(collect.check_item(id)); } - res?; - Ok(tcx.arena.alloc(collect.impls_map)) + + (tcx.arena.alloc(collect.impls_map), res) } -pub(crate) fn crate_incoherent_impls( +pub(crate) fn crate_inherent_impls_validity_check( tcx: TyCtxt<'_>, - simp: SimplifiedType, -) -> Result<&[DefId], ErrorGuaranteed> { - let crate_map = tcx.crate_inherent_impls(())?; - Ok(tcx.arena.alloc_from_iter( + (): (), +) -> Result<(), ErrorGuaranteed> { + tcx.crate_inherent_impls(()).1 +} + +pub(crate) fn crate_incoherent_impls(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] { + let (crate_map, _) = tcx.crate_inherent_impls(()); + tcx.arena.alloc_from_iter( crate_map.incoherent_impls.get(&simp).unwrap_or(&Vec::new()).iter().map(|d| d.to_def_id()), - )) + ) } /// On-demand query: yields a vector of the inherent impls for a specific type. -pub(crate) fn inherent_impls( - tcx: TyCtxt<'_>, - ty_def_id: LocalDefId, -) -> Result<&[DefId], ErrorGuaranteed> { - let crate_map = tcx.crate_inherent_impls(())?; - Ok(match crate_map.inherent_impls.get(&ty_def_id) { +pub(crate) fn inherent_impls(tcx: TyCtxt<'_>, ty_def_id: LocalDefId) -> &[DefId] { + let (crate_map, _) = tcx.crate_inherent_impls(()); + match crate_map.inherent_impls.get(&ty_def_id) { Some(v) => &v[..], None => &[], - }) + } } struct InherentCollect<'tcx> { 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 6825c2e33fe71..b8066b4b47d90 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls_overlap.rs @@ -177,8 +177,7 @@ impl<'tcx> InherentOverlapChecker<'tcx> { return Ok(()); } - let impls = self.tcx.inherent_impls(id.owner_id)?; - + let impls = self.tcx.inherent_impls(id.owner_id); let overlap_mode = OverlapMode::get(self.tcx, id.owner_id.to_def_id()); let impls_items = impls @@ -252,13 +251,10 @@ impl<'tcx> InherentOverlapChecker<'tcx> { for ident in &idents_to_add { connected_region_ids.insert(*ident, id_to_set); } - connected_regions.insert( - id_to_set, - ConnectedRegion { - idents: idents_to_add, - impl_blocks: std::iter::once(i).collect(), - }, - ); + connected_regions.insert(id_to_set, ConnectedRegion { + idents: idents_to_add, + impl_blocks: std::iter::once(i).collect(), + }); } // Take the only id inside the list &[id_to_set] => { diff --git a/compiler/rustc_hir_analysis/src/coherence/mod.rs b/compiler/rustc_hir_analysis/src/coherence/mod.rs index f2a97d0677130..b25406583f6c4 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; @@ -124,7 +124,10 @@ fn enforce_empty_impls_for_marker_traits( pub(crate) fn provide(providers: &mut Providers) { use self::builtin::coerce_unsized_info; - use self::inherent_impls::{crate_incoherent_impls, crate_inherent_impls, inherent_impls}; + use self::inherent_impls::{ + crate_incoherent_impls, crate_inherent_impls, crate_inherent_impls_validity_check, + inherent_impls, + }; use self::inherent_impls_overlap::crate_inherent_impls_overlap_check; use self::orphan::orphan_check_impl; @@ -133,6 +136,7 @@ pub(crate) fn provide(providers: &mut Providers) { crate_inherent_impls, crate_incoherent_impls, inherent_impls, + crate_inherent_impls_validity_check, crate_inherent_impls_overlap_check, coerce_unsized_info, orphan_check_impl, diff --git a/compiler/rustc_hir_analysis/src/coherence/unsafety.rs b/compiler/rustc_hir_analysis/src/coherence/unsafety.rs index 7513f680271e3..d66114a50d78b 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 4c59f7540eebe..93b021be24584 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::captures::Captures; 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::query::Providers; 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 c73d3a5390d93..d76d9213129fa 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 ba01ea3f512ea..0a8eef2006d5a 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::DefKind; 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 7a254c884c294..c64741625a4ec 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 @@ use rustc_middle::ty::{ 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 67d8813d1f7c9..9e9704622052f 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_hir::intravisit::{self, Visitor}; 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 d1601446b6f4c..c9b949ad88d54 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::middle::resolve_bound_vars::*; 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 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { ) }; - 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 b877cacd9983b..48b5e87cbd033 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 core::ops::ControlFlow; 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 2afb29abd68a6..fcea0052546f5 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_errors::StashKey; 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 2c9f20b7840f3..1ccb7faaf3053 100644 --- a/compiler/rustc_hir_analysis/src/delegation.rs +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -41,10 +41,10 @@ impl<'tcx> TypeFolder> for ParamIndexRemapper<'tcx> { if let ty::ReEarlyParam(param) = r.kind() && let Some(index) = self.remap_table.get(¶m.index).copied() { - return ty::Region::new_early_param( - self.tcx, - ty::EarlyParamRegion { index, name: param.name }, - ); + return ty::Region::new_early_param(self.tcx, ty::EarlyParamRegion { + index, + name: param.name, + }); } r } diff --git a/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/errors/wrong_number_of_generic_args.rs index 236543007fc3f..5ae7944f6d53e 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 6f7f312834729..45cd46e3df296 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_data_structures::fx::{FxIndexMap, FxIndexSet}; 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 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let mut num_bound_vars = candidate.bound_vars().len(); let args = candidate.skip_binder().args.extend_to(tcx, item_def_id, |param, _| { let arg = match param.kind { - ty::GenericParamDefKind::Lifetime => ty::Region::new_bound( - tcx, - ty::INNERMOST, - ty::BoundRegion { + ty::GenericParamDefKind::Lifetime => { + ty::Region::new_bound(tcx, ty::INNERMOST, ty::BoundRegion { var: ty::BoundVar::from_usize(num_bound_vars), kind: ty::BoundRegionKind::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 af319fd53bde7..5775a8867b16a 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::sorted_map::SortedMap; 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::bug; 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 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { .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(); @@ -1031,7 +1028,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { .. }) = node && let Some(ty_def_id) = qself_ty.ty_def_id() - && let Ok([inherent_impl]) = tcx.inherent_impls(ty_def_id) + && let [inherent_impl] = tcx.inherent_impls(ty_def_id) && let name = format!("{ident2}_{ident3}") && let Some(ty::AssocItem { kind: ty::AssocKind::Fn, .. }) = tcx .associated_items(inherent_impl) 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 8d5f98c7372e1..6e8a9ded4f370 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 149bc6d26984d..1fbf70fa20157 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::codes::*; 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 35eebcb6be117..d7d4a98e63fe6 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_ast::TraitObjectSyntax; 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::ty::{ 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 tracing::{debug, debug_span, instrument}; 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; @@ -1272,7 +1272,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } let candidates: Vec<_> = tcx - .inherent_impls(adt_did)? + .inherent_impls(adt_did) .iter() .filter_map(|&impl_| { let (item, scope) = 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 8853886371033..87a240f626c3f 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_middle::ty::{ 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 147646930dde3..0355adfcb11e1 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 1481a4dd141b2..92d85d48a42c0 100644 --- a/compiler/rustc_hir_analysis/src/lib.rs +++ b/compiler/rustc_hir_analysis/src/lib.rs @@ -100,8 +100,8 @@ use rustc_middle::mir::interpret::GlobalId; 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; @@ -170,7 +170,7 @@ pub fn check_crate(tcx: TyCtxt<'_>) { let _ = tcx.ensure().coherent_trait(trait_def_id); } // these queries are executed for side-effects (error reporting): - let _ = tcx.ensure().crate_inherent_impls(()); + let _ = tcx.ensure().crate_inherent_impls_validity_check(()); let _ = tcx.ensure().crate_inherent_impls_overlap_check(()); }); diff --git a/compiler/rustc_hir_analysis/src/outlives/utils.rs b/compiler/rustc_hir_analysis/src/outlives/utils.rs index a1eccc91dea82..0c9f5ba8b6fa8 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_data_structures::fx::FxIndexMap; 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 ace183986bd00..dbaf9c2c6f075 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 ac6707f931602..1c52283d537d3 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -18,9 +18,9 @@ use rustc_hir::{ 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 @@ impl<'a> State<'a> { let generic_params = generic_params .iter() .filter(|p| { - matches!( - p, - GenericParam { - kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit }, - .. - } - ) + matches!(p, GenericParam { + kind: GenericParamKind::Lifetime { kind: LifetimeParamKind::Explicit }, + .. + }) }) .collect::>(); diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 3dc8759a9edee..13ba615d4c927 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::adjustment::{ }; 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { closure_sig, ); let adjustments = self.adjust_steps(autoderef); - self.record_deferred_call_resolution( - def_id, - DeferredCallResolution { - call_expr, - callee_expr, - closure_ty: adjusted_ty, - adjustments, - fn_sig: closure_sig, - }, - ); + self.record_deferred_call_resolution(def_id, DeferredCallResolution { + call_expr, + callee_expr, + closure_ty: adjusted_ty, + adjustments, + fn_sig: closure_sig, + }); return Some(CallStep::DeferredClosure(def_id, closure_sig)); } @@ -202,16 +199,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { coroutine_closure_sig.abi, ); let adjustments = self.adjust_steps(autoderef); - self.record_deferred_call_resolution( - def_id, - DeferredCallResolution { - call_expr, - callee_expr, - closure_ty: adjusted_ty, - adjustments, - fn_sig: call_sig, - }, - ); + self.record_deferred_call_resolution(def_id, DeferredCallResolution { + call_expr, + callee_expr, + closure_ty: adjusted_ty, + adjustments, + fn_sig: call_sig, + }); return Some(CallStep::DeferredClosure(def_id, call_sig)); } @@ -554,11 +548,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 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 36892aaf80c56..fcd2940b83ae3 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -32,17 +32,18 @@ use rustc_data_structures::fx::FxHashSet; use rustc_errors::codes::*; use rustc_errors::{Applicability, Diag, ErrorGuaranteed}; use rustc_hir::{self as hir, ExprKind}; +use rustc_infer::infer::DefineOpaqueTypes; use rustc_macros::{TypeFoldable, TypeVisitable}; -use rustc_middle::bug; use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::AllowTwoPhase; use rustc_middle::ty::cast::{CastKind, CastTy}; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::{self, Ty, TyCtxt, TypeAndMut, TypeVisitableExt, VariantDef}; +use rustc_middle::{bug, span_bug}; 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}; @@ -152,12 +153,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } #[derive(Copy, Clone, Debug)] -pub enum CastError { +enum CastError<'tcx> { ErrorGuaranteed(ErrorGuaranteed), CastToBool, CastToChar, - DifferingKinds, + DifferingKinds { + src_kind: PointerKind<'tcx>, + dst_kind: PointerKind<'tcx>, + }, /// Cast of thin to fat raw ptr (e.g., `*const () as *const [u8]`). SizedUnsizedCast, IllegalCast, @@ -177,7 +181,7 @@ pub enum CastError { ForeignNonExhaustiveAdt, } -impl From for CastError { +impl From for CastError<'_> { fn from(err: ErrorGuaranteed) -> Self { CastError::ErrorGuaranteed(err) } @@ -251,7 +255,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { } } - fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError) { + fn report_cast_error(&self, fcx: &FnCtxt<'a, 'tcx>, e: CastError<'tcx>) { match e { CastError::ErrorGuaranteed(_) => { // an error has already been reported @@ -284,14 +288,11 @@ impl<'a, 'tcx> CastCheck<'tcx> { 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); @@ -306,10 +307,52 @@ impl<'a, 'tcx> CastCheck<'tcx> { CastError::IllegalCast => { make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx).emit(); } - CastError::DifferingKinds => { - make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx) - .with_note("vtable kinds may not match") - .emit(); + CastError::DifferingKinds { src_kind, dst_kind } => { + let mut err = + make_invalid_casting_error(self.span, self.expr_ty, self.cast_ty, fcx); + + match (src_kind, dst_kind) { + (PointerKind::VTable(_), PointerKind::VTable(_)) => { + err.note("the trait objects may have different vtables"); + } + ( + PointerKind::OfParam(_) | PointerKind::OfAlias(_), + PointerKind::OfParam(_) + | PointerKind::OfAlias(_) + | PointerKind::VTable(_) + | PointerKind::Length, + ) + | ( + PointerKind::VTable(_) | PointerKind::Length, + PointerKind::OfParam(_) | PointerKind::OfAlias(_), + ) => { + err.note("the pointers may have different metadata"); + } + (PointerKind::VTable(_), PointerKind::Length) + | (PointerKind::Length, PointerKind::VTable(_)) => { + err.note("the pointers have different metadata"); + } + ( + PointerKind::Thin, + PointerKind::Thin + | PointerKind::VTable(_) + | PointerKind::Length + | PointerKind::OfParam(_) + | PointerKind::OfAlias(_), + ) + | ( + PointerKind::VTable(_) + | PointerKind::Length + | PointerKind::OfParam(_) + | PointerKind::OfAlias(_), + PointerKind::Thin, + ) + | (PointerKind::Length, PointerKind::Length) => { + span_bug!(self.span, "unexpected cast error: {e:?}") + } + } + + err.emit(); } CastError::CastToBool => { let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty); @@ -620,12 +663,11 @@ impl<'a, 'tcx> CastCheck<'tcx> { }; let expr_ty = fcx.resolve_vars_if_possible(self.expr_ty); let cast_ty = fcx.resolve_vars_if_possible(self.cast_ty); - fcx.tcx.emit_node_span_lint( - lint, - self.expr.hir_id, - self.span, - errors::TrivialCast { numeric, expr_ty, cast_ty }, - ); + fcx.tcx.emit_node_span_lint(lint, self.expr.hir_id, self.span, errors::TrivialCast { + numeric, + expr_ty, + cast_ty, + }); } #[instrument(skip(fcx), level = "debug")] @@ -674,10 +716,20 @@ impl<'a, 'tcx> CastCheck<'tcx> { /// Checks a cast, and report an error if one exists. In some cases, this /// can return Ok and create type errors in the fcx rather than returning /// directly. coercion-cast is handled in check instead of here. - fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result { + fn do_check(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result> { use rustc_middle::ty::cast::CastTy::*; use rustc_middle::ty::cast::IntTy::*; + if self.cast_ty.is_dyn_star() { + if fcx.tcx.features().dyn_star { + span_bug!(self.span, "should be handled by `coerce`"); + } else { + // Report "casting is invalid" rather than "non-primitive cast" + // if the feature is not enabled. + return Err(CastError::IllegalCast); + } + } + let (t_from, t_cast) = match (CastTy::from_ty(self.expr_ty), CastTy::from_ty(self.cast_ty)) { (Some(t_from), Some(t_cast)) => (t_from, t_cast), @@ -784,16 +836,6 @@ impl<'a, 'tcx> CastCheck<'tcx> { (Int(Char) | Int(Bool), Int(_)) => Ok(CastKind::PrimIntCast), (Int(_) | Float, Int(_) | Float) => Ok(CastKind::NumericCast), - - (_, DynStar) => { - if fcx.tcx.features().dyn_star { - bug!("should be handled by `coerce`") - } else { - Err(CastError::IllegalCast) - } - } - - (DynStar, _) => Err(CastError::IllegalCast), } } @@ -802,27 +844,34 @@ impl<'a, 'tcx> CastCheck<'tcx> { fcx: &FnCtxt<'a, 'tcx>, m_src: ty::TypeAndMut<'tcx>, m_dst: ty::TypeAndMut<'tcx>, - ) -> Result { + ) -> Result> { debug!("check_ptr_ptr_cast m_src={m_src:?} m_dst={m_dst:?}"); - // ptr-ptr cast. vtables must match. + // ptr-ptr cast. metadata must match. let src_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_src.ty, self.span)?); let dst_kind = fcx.tcx.erase_regions(fcx.pointer_kind(m_dst.ty, self.span)?); - match (src_kind, dst_kind) { - // We can't cast if target pointer kind is unknown - (_, None) => Err(CastError::UnknownCastPtrKind), - // Cast to thin pointer is OK - (_, Some(PointerKind::Thin)) => Ok(CastKind::PtrPtrCast), + // We can't cast if target pointer kind is unknown + let Some(dst_kind) = dst_kind else { + return Err(CastError::UnknownCastPtrKind); + }; - // We can't cast to fat pointer if source pointer kind is unknown - (None, _) => Err(CastError::UnknownExprPtrKind), + // Cast to thin pointer is OK + if dst_kind == PointerKind::Thin { + return Ok(CastKind::PtrPtrCast); + } + + // We can't cast to fat pointer if source pointer kind is unknown + let Some(src_kind) = src_kind else { + return Err(CastError::UnknownCastPtrKind); + }; + match (src_kind, dst_kind) { // thin -> fat? report invalid cast (don't complain about vtable kinds) - (Some(PointerKind::Thin), _) => Err(CastError::SizedUnsizedCast), + (PointerKind::Thin, _) => Err(CastError::SizedUnsizedCast), // trait object -> trait object? need to do additional checks - (Some(PointerKind::VTable(src_tty)), Some(PointerKind::VTable(dst_tty))) => { + (PointerKind::VTable(src_tty), PointerKind::VTable(dst_tty)) => { match (src_tty.principal(), dst_tty.principal()) { // A + SrcAuto> -> B + DstAuto>. need to make sure // - `Src` and `Dst` traits are the same @@ -838,7 +887,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { // Note that trait upcasting goes through a different mechanism (`coerce_unsized`) // and is unaffected by this check. if src_principal.def_id() != dst_principal.def_id() { - return Err(CastError::DifferingKinds); + return Err(CastError::DifferingKinds { src_kind, dst_kind }); } // We need to reconstruct trait object types. @@ -864,7 +913,16 @@ impl<'a, 'tcx> CastCheck<'tcx> { )); // `dyn Src = dyn Dst`, this checks for matching traits/generics - fcx.demand_eqtype(self.span, src_obj, dst_obj); + // This is `demand_eqtype`, but inlined to give a better error. + let cause = fcx.misc(self.span); + if fcx + .at(&cause, fcx.param_env) + .eq(DefineOpaqueTypes::Yes, src_obj, dst_obj) + .map(|infer_ok| fcx.register_infer_ok_obligations(infer_ok)) + .is_err() + { + return Err(CastError::DifferingKinds { src_kind, dst_kind }); + } // Check that `SrcAuto` (+auto traits implied by `Src`) is a superset of `DstAuto`. // Emit an FCW otherwise. @@ -909,17 +967,17 @@ impl<'a, 'tcx> CastCheck<'tcx> { // dyn Trait -> dyn Auto? should be ok, but we used to not allow it. // FIXME: allow this - (Some(_), None) => Err(CastError::DifferingKinds), + (Some(_), None) => Err(CastError::DifferingKinds { src_kind, dst_kind }), // dyn Auto -> dyn Trait? not ok. - (None, Some(_)) => Err(CastError::DifferingKinds), + (None, Some(_)) => Err(CastError::DifferingKinds { src_kind, dst_kind }), } } // fat -> fat? metadata kinds must match - (Some(src_kind), Some(dst_kind)) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast), + (src_kind, dst_kind) if src_kind == dst_kind => Ok(CastKind::PtrPtrCast), - (_, _) => Err(CastError::DifferingKinds), + (_, _) => Err(CastError::DifferingKinds { src_kind, dst_kind }), } } @@ -927,7 +985,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { &self, fcx: &FnCtxt<'a, 'tcx>, m_cast: ty::TypeAndMut<'tcx>, - ) -> Result { + ) -> Result> { // fptr-ptr cast. must be to thin ptr match fcx.pointer_kind(m_cast.ty, self.span)? { @@ -941,7 +999,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { &self, fcx: &FnCtxt<'a, 'tcx>, m_expr: ty::TypeAndMut<'tcx>, - ) -> Result { + ) -> Result> { // ptr-addr cast. must be from thin ptr match fcx.pointer_kind(m_expr.ty, self.span)? { @@ -956,7 +1014,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { fcx: &FnCtxt<'a, 'tcx>, m_expr: ty::TypeAndMut<'tcx>, m_cast: ty::TypeAndMut<'tcx>, - ) -> Result { + ) -> Result> { // array-ptr-cast: allow mut-to-mut, mut-to-const, const-to-const if m_expr.mutbl >= m_cast.mutbl { if let ty::Array(ety, _) = m_expr.ty.kind() { @@ -991,7 +1049,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { &self, fcx: &FnCtxt<'a, 'tcx>, m_cast: TypeAndMut<'tcx>, - ) -> Result { + ) -> Result> { // ptr-addr cast. pointer must be thin. match fcx.pointer_kind(m_cast.ty, self.span)? { None => Err(CastError::UnknownCastPtrKind), diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index 9346ff2d6ef6f..f2d3a3b509a00 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 f71427e42d4a5..3e7ce2955fc05 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -14,14 +14,14 @@ use rustc_middle::span_bug; 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None => self.next_ty_var(expr_span), }; - let closure_args = ty::ClosureArgs::new( - tcx, - ty::ClosureArgsParts { - parent_args, - closure_kind_ty, - closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig), - tupled_upvars_ty, - }, - ); + let closure_args = ty::ClosureArgs::new(tcx, ty::ClosureArgsParts { + parent_args, + closure_kind_ty, + closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig), + tupled_upvars_ty, + }); (Ty::new_closure(tcx, expr_def_id.to_def_id(), closure_args.args), None) } @@ -180,18 +177,15 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => tcx.types.unit, }; - let coroutine_args = ty::CoroutineArgs::new( - tcx, - ty::CoroutineArgsParts { - parent_args, - kind_ty, - resume_ty, - yield_ty, - return_ty: liberated_sig.output(), - witness: interior, - tupled_upvars_ty, - }, - ); + let coroutine_args = ty::CoroutineArgs::new(tcx, ty::CoroutineArgsParts { + parent_args, + kind_ty, + resume_ty, + yield_ty, + return_ty: liberated_sig.output(), + witness: interior, + tupled_upvars_ty, + }); ( Ty::new_coroutine(tcx, expr_def_id.to_def_id(), coroutine_args.args), @@ -222,9 +216,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let coroutine_captures_by_ref_ty = self.next_ty_var(expr_span); - let closure_args = ty::CoroutineClosureArgs::new( - tcx, - ty::CoroutineClosureArgsParts { + let closure_args = + ty::CoroutineClosureArgs::new(tcx, ty::CoroutineClosureArgsParts { parent_args, closure_kind_ty, signature_parts_ty: Ty::new_fn_ptr( @@ -245,8 +238,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { tupled_upvars_ty, coroutine_captures_by_ref_ty, coroutine_witness_ty: interior, - }, - ); + }); let coroutine_kind_ty = match expected_kind { Some(kind) => Ty::from_coroutine_closure_kind(tcx, kind), diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 26c9b8dfdc3f5..b08c5bc6d9a36 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::visit::TypeVisitableExt; 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 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // the reborrow in coerce_borrowed_ptr will pick it up. let mutbl = AutoBorrowMutability::new(mutbl_b, AllowTwoPhase::No); - Some(( - Adjustment { kind: Adjust::Deref(None), target: ty_a }, - Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(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 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { 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. // @@ -775,7 +769,10 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { )); Ok(InferOk { - value: (vec![Adjustment { kind: Adjust::DynStar, target: b }], b), + value: ( + vec![Adjustment { kind: Adjust::Pointer(PointerCoercion::DynStar), target: b }], + b, + ), obligations, }) } @@ -1021,10 +1018,10 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // regionck knows that the region for `a` must be valid here. if is_ref { self.unify_and(a_unsafe, b, |target| { - vec![ - Adjustment { kind: Adjust::Deref(None), target: mt_a.ty }, - Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target }, - ] + vec![Adjustment { kind: Adjust::Deref(None), target: mt_a.ty }, Adjustment { + kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), + target, + }] }) } else if mt_a.mutbl != mutbl_b { self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCoercion::MutToConstPointer))) @@ -1241,10 +1238,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"), }; for expr in exprs.iter().map(|e| e.as_coercion_site()) { - self.apply_adjustments( - expr, - vec![Adjustment { kind: prev_adjustment.clone(), target: fn_ptr }], - ); + self.apply_adjustments(expr, vec![Adjustment { + kind: prev_adjustment.clone(), + target: fn_ptr, + }]); } self.apply_adjustments(new, vec![Adjustment { kind: next_adjustment, target: fn_ptr }]); return Ok(fn_ptr); diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 80a71f27a9990..cfa8fc4bbf2e6 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::fold::BottomUpFolder; 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 3066561a31d6d..1a10e19d0a5e9 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 821a90d7a8c44..b34ed4640db12 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::stack::ensure_sufficient_stack; 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::{ExprKind, HirId, QPath}; 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 @@ use crate::errors::{ 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let adj_ty = self.next_ty_var(expr.span); - self.apply_adjustments( - expr, - vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }], - ); + self.apply_adjustments(expr, vec![Adjustment { + kind: Adjust::NeverToAny, + target: adj_ty, + }]); ty = adj_ty; } @@ -1491,8 +1491,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { _ => 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( @@ -2123,7 +2126,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .tcx .inherent_impls(def_id) .into_iter() - .flatten() .flat_map(|i| self.tcx.associated_items(i).in_definition_order()) // Only assoc fn with no receivers. .filter(|item| { @@ -2800,9 +2802,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 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 3b2ddf659a141..bb5f351137305 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::cell::{Ref, RefCell}; 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 @@ use rustc_middle::hir::place::ProjectionKind; 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 @@ impl<'tcx> TypeInformationCtxt<'tcx> for &FnCtxt<'_, '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; @@ -757,9 +759,7 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx for adjustment in adjustments { debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment); match adjustment.kind { - adjustment::Adjust::NeverToAny - | adjustment::Adjust::Pointer(_) - | adjustment::Adjust::DynStar => { + adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => { // Creating a closure/fn-pointer or unsizing consumes // the input and stores it into the resulting rvalue. self.consume_or_copy(&place_with_id, place_with_id.hir_id); @@ -1294,8 +1294,7 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) | adjustment::Adjust::Borrow(_) - | adjustment::Adjust::ReborrowPin(..) - | adjustment::Adjust::DynStar => { + | adjustment::Adjust::ReborrowPin(..) => { // Result is an rvalue. Ok(self.cat_rvalue(expr.hir_id, target)) } diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 7a6ebf15fa9ca..4fd508ab896e7 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::vec_graph::VecGraph; 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 61898b06476fd..2c469c0d52c4f 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::ty::{ }; 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 tracing::{debug, instrument}; 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let autoborrow_mut = adj.iter().any(|adj| { - matches!( - adj, - &Adjustment { - kind: Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. })), - .. - } - ) + matches!(adj, &Adjustment { + kind: Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. })), + .. + }) }); match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) { @@ -968,16 +966,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut sp = MultiSpan::from_span(path_segment.ident.span); sp.push_span_label( path_segment.ident.span, - format!( - "this call modifies {} in-place", - match rcvr.kind { - ExprKind::Path(QPath::Resolved( - None, - hir::Path { segments: [segment], .. }, - )) => format!("`{}`", segment.ident), - _ => "its receiver".to_string(), - } - ), + format!("this call modifies {} in-place", match rcvr.kind { + ExprKind::Path(QPath::Resolved(None, hir::Path { segments: [segment], .. })) => + format!("`{}`", segment.ident), + _ => "its receiver".to_string(), + }), ); let modifies_rcvr_note = @@ -1477,6 +1470,33 @@ impl<'a, 'tcx> FnCtxt<'a, '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 a8ba9f139cc7e..f93d0e9340613 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::{DefKind, Res}; 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 8810f14aaa95c..550c58b5a17c6 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 itertools::Itertools; 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::visit::TypeVisitableExt; 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 a43d7aa31a522..e60bd1a312a1b 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_infer::infer; 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 b71e34864fd98..5f89f7dedc2cc 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::middle::stability::EvalResult; 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr.kind, hir::ExprKind::Call( hir::Expr { - kind: hir::ExprKind::Path(hir::QPath::Resolved( - None, - hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. }, - )), + kind: hir::ExprKind::Path(hir::QPath::Resolved(None, hir::Path { + res: Res::Def(hir::def::DefKind::Ctor(_, _), _), + .. + },)), .. }, .., - ) | hir::ExprKind::Path(hir::QPath::Resolved( - None, - hir::Path { res: Res::Def(hir::def::DefKind::Ctor(_, _), _), .. }, - )), + ) | hir::ExprKind::Path(hir::QPath::Resolved(None, hir::Path { + res: Res::Def(hir::def::DefKind::Ctor(_, _), _), + .. + },)), ); let (article, kind, variant, sugg_operator) = diff --git a/compiler/rustc_hir_typeck/src/gather_locals.rs b/compiler/rustc_hir_typeck/src/gather_locals.rs index 2f990de7e31be..83c9a4878d2f8 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::intravisit::{self, Visitor}; 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 81d940a3f9b47..a4121adf628af 100644 --- a/compiler/rustc_hir_typeck/src/intrinsicck.rs +++ b/compiler/rustc_hir_typeck/src/intrinsicck.rs @@ -101,7 +101,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } 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 e2c1eef837f29..f8352d9d44a97 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -43,7 +43,7 @@ pub use coercion::can_coerce; 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::query::Providers; 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 10a22eee7b74a..e3b0fa78eb705 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 @@ use rustc_middle::ty::{ 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 7019b718b16e8..586b753f45493 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -18,14 +18,14 @@ use rustc_middle::ty::{ 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 ac5e1040803e0..a8b5b6165db06 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_lint::{ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER}; 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 17aa43ae7c043..1a8afcf003d20 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -6,15 +6,15 @@ use std::ops::Deref; 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::def_id::{DefId, LocalDefId}; 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 @@ -728,13 +728,13 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { let Some(simp) = simplify_type(self.tcx, self_ty, TreatParams::InstantiateWithInfer) else { bug!("unexpected incoherent type: {:?}", self_ty) }; - for &impl_def_id in self.tcx.incoherent_impls(simp).into_iter().flatten() { + for &impl_def_id in self.tcx.incoherent_impls(simp).into_iter() { self.assemble_inherent_impl_probe(impl_def_id); } } fn assemble_inherent_impl_candidates_for_type(&mut self, def_id: DefId) { - let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id).into_iter().flatten(); + let impl_def_ids = self.tcx.at(self.span).inherent_impls(def_id).into_iter(); for &impl_def_id in impl_def_ids { self.assemble_inherent_impl_probe(impl_def_id); } diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index deabf693af2f5..e03be4f43f73d 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::fx::{FxIndexMap, FxIndexSet}; 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::lang_items::LangItem; 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}; @@ -680,7 +680,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.tcx .inherent_impls(adt_def.did()) .into_iter() - .flatten() .any(|def_id| self.associated_value(*def_id, item_name).is_some()) } else { false @@ -1438,7 +1437,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .tcx .inherent_impls(adt.did()) .into_iter() - .flatten() .copied() .filter(|def_id| { if let Some(assoc) = self.associated_value(*def_id, item_name) { @@ -1721,20 +1719,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - 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() @@ -1913,7 +1898,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { call_args: Option>>, ) -> Option { if let ty::Adt(adt, adt_args) = rcvr_ty.kind() { - for inherent_impl_did in self.tcx.inherent_impls(adt.did()).into_iter().flatten() { + for inherent_impl_did in self.tcx.inherent_impls(adt.did()).into_iter() { for inherent_method in self.tcx.associated_items(inherent_impl_did).in_definition_order() { @@ -2127,9 +2112,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty::Adt(adt_def, _) = rcvr_ty.kind() else { return; }; - // FIXME(oli-obk): try out bubbling this error up one level and cancelling the other error in that case. - let Ok(impls) = self.tcx.inherent_impls(adt_def.did()) else { return }; - let mut items = impls + let mut items = self + .tcx + .inherent_impls(adt_def.did()) .iter() .flat_map(|i| self.tcx.associated_items(i).in_definition_order()) // Only assoc fn with no receivers and only if @@ -2508,7 +2493,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .and_then(|simp| { tcx.incoherent_impls(simp) .into_iter() - .flatten() .find_map(|&id| self.associated_value(id, item_name)) }) .is_some() diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index c74270fc0e6a4..1574e9e98d4d8 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::print::with_no_trimmed_paths; 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 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 7dd6deb4fe6fd..49c5a7d8a652d 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -5,7 +5,7 @@ use rustc_ast as ast; 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_session::parse::feature_err; 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 ty::VariantDef; 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 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 e7f47ee56c9b2..8604f5f6920e7 100644 --- a/compiler/rustc_hir_typeck/src/place_op.rs +++ b/compiler/rustc_hir_typeck/src/place_op.rs @@ -7,8 +7,8 @@ use rustc_middle::ty::adjustment::{ 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ok = self.try_overloaded_deref(expr.span, oprnd_ty)?; let method = self.register_infer_ok_obligations(ok); if let ty::Ref(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 d65aaef4e8b3f..98d7f777d6b8a 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 52fa30a352f84..18e40cfa42874 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_infer::infer::{InferCtxt, InferOk, TyCtxtInferExt}; 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 7688a63a30a45..c5843b883a17b 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::fx::{FxIndexMap, FxIndexSet}; 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::ty::{ }; 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 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { bug!(); }; let place = self.place_for_root_variable(closure_def_id, local_id); - delegate.capture_information.push(( - place, - ty::CaptureInfo { - capture_kind_expr_id: Some(init.hir_id), - path_expr_id: Some(init.hir_id), - capture_kind: UpvarCapture::ByValue, - }, - )); + delegate.capture_information.push((place, ty::CaptureInfo { + capture_kind_expr_id: Some(init.hir_id), + path_expr_id: Some(init.hir_id), + capture_kind: UpvarCapture::ByValue, + })); } } @@ -381,11 +378,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let UpvarArgs::CoroutineClosure(args) = args && !args.references_error() { - let closure_env_region: ty::Region<'_> = ty::Region::new_bound( - self.tcx, - ty::INNERMOST, - ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::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 @@ impl<'tcx> euv::Delegate<'tcx> for InferBorrowKind<'tcx> { let PlaceBase::Upvar(upvar_id) = place_with_id.place.base else { return }; assert_eq!(self.closure_def_id, upvar_id.closure_expr_id); - self.capture_information.push(( - place_with_id.place.clone(), - ty::CaptureInfo { - capture_kind_expr_id: Some(diag_expr_id), - path_expr_id: Some(diag_expr_id), - capture_kind: ty::UpvarCapture::ByValue, - }, - )); + self.capture_information.push((place_with_id.place.clone(), ty::CaptureInfo { + capture_kind_expr_id: Some(diag_expr_id), + path_expr_id: Some(diag_expr_id), + capture_kind: ty::UpvarCapture::ByValue, + })); } #[instrument(skip(self), level = "debug")] @@ -2038,14 +2032,11 @@ impl<'tcx> euv::Delegate<'tcx> for InferBorrowKind<'tcx> { 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 2fbbc3200e12a..3254dddaee9a2 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -7,16 +7,16 @@ use std::mem; 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 46f30526d2a83..646b9dbe1331b 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::fs::{self, File}; 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 c79d108183c53..dda1232b80bf5 100644 --- a/compiler/rustc_incremental/src/lib.rs +++ b/compiler/rustc_incremental/src/lib.rs @@ -14,9 +14,9 @@ mod errors; 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 cef0b23143d00..9dc5cbaafce19 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_ast::{self as ast, Attribute, NestedMetaItem}; 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_FN_IN_TRAIT: &[&[&str]] = const LABELS_HIR_ONLY: &[&[&str]] = &[BASE_HIR]; /// Impl `DepNode`s. -const LABELS_TRAIT: &[&[&str]] = &[ - BASE_HIR, - &[label_strs::associated_item_def_ids, label_strs::predicates_of, label_strs::generics_of], -]; +const LABELS_TRAIT: &[&[&str]] = &[BASE_HIR, &[ + label_strs::associated_item_def_ids, + label_strs::predicates_of, + label_strs::generics_of, +]]; /// Impl `DepNode`s. const LABELS_IMPL: &[&[&str]] = &[BASE_HIR, BASE_IMPL]; diff --git a/compiler/rustc_incremental/src/persist/file_format.rs b/compiler/rustc_incremental/src/persist/file_format.rs index f834c48cbf8fc..4c664ea6ba0f4 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::path::{Path, PathBuf}; 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 feb25a9a89d0d..8769c4173c886 100644 --- a/compiler/rustc_incremental/src/persist/fs.rs +++ b/compiler/rustc_incremental/src/persist/fs.rs @@ -108,14 +108,14 @@ use std::io::{self, ErrorKind}; 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 18088a10dd00f..c74804cc7983d 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::memmap::Mmap; 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 a529b1dcec082..186db0a60a38f 100644 --- a/compiler/rustc_incremental/src/persist/mod.rs +++ b/compiler/rustc_incremental/src/persist/mod.rs @@ -11,6 +11,6 @@ mod save; 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 58a03cb8b30cd..53726df459797 100644 --- a/compiler/rustc_incremental/src/persist/save.rs +++ b/compiler/rustc_incremental/src/persist/save.rs @@ -7,8 +7,8 @@ use rustc_middle::dep_graph::{ 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 506afbae40c6e..c2b9cae680bf1 100644 --- a/compiler/rustc_index/src/bit_set.rs +++ b/compiler/rustc_index/src/bit_set.rs @@ -3,11 +3,11 @@ use std::ops::{BitAnd, BitAndAssign, BitOrAssign, Bound, Not, Range, RangeBounds 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 066aa46e35080..21e681d63f69b 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 381d79c24fcba..9cee2f2f5b23b 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 1930e357fc9cc..35ea42338250d 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -15,10 +15,10 @@ use rustc_middle::ty::{ 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 95d7bb7eb3830..7791bd736281c 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::ty::{self, BoundVar, GenericArg, GenericArgKind, Ty, TyCtxt}; 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 95888beb6b198..c06836edcfb55 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 aab64883bc50f..6af49accc8411 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 std::fmt; 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 0e767b7fb2efd..5fa1bf51634a3 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 opaque_types::OpaqueTypeStorage; 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::canonical::{Canonical, CanonicalVarValues}; 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 replace_param_and_infer_args_with_placeholder<'tcx>( self.idx += 1; idx }; - Ty::new_placeholder( - self.tcx, - ty::PlaceholderType { - universe: ty::UniverseIndex::ROOT, - bound: ty::BoundTy { - var: ty::BoundVar::from_u32(idx), - kind: ty::BoundTyKind::Anon, - }, + Ty::new_placeholder(self.tcx, ty::PlaceholderType { + universe: ty::UniverseIndex::ROOT, + bound: ty::BoundTy { + var: ty::BoundVar::from_u32(idx), + kind: ty::BoundTyKind::Anon, }, - ) + }) } else { t.super_fold_with(self) } @@ -1793,17 +1790,14 @@ fn replace_param_and_infer_args_with_placeholder<'tcx>( fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> { if let ty::ConstKind::Infer(_) = c.kind() { - ty::Const::new_placeholder( - self.tcx, - ty::PlaceholderConst { - universe: ty::UniverseIndex::ROOT, - bound: ty::BoundVar::from_u32({ - let idx = self.idx; - self.idx += 1; - idx - }), - }, - ) + ty::Const::new_placeholder(self.tcx, ty::PlaceholderConst { + universe: ty::UniverseIndex::ROOT, + bound: ty::BoundVar::from_u32({ + let idx = self.idx; + self.idx += 1; + idx + }), + }) } else { c.super_fold_with(self) } diff --git a/compiler/rustc_infer/src/infer/opaque_types/mod.rs b/compiler/rustc_infer/src/infer/opaque_types/mod.rs index 5ceaaf1a3c4fe..55c51bc856f8e 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 hir::def_id::{DefId, LocalDefId}; 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 77c711e57bb62..a071b84a1a00f 100644 --- a/compiler/rustc_infer/src/infer/outlives/env.rs +++ b/compiler/rustc_infer/src/infer/outlives/env.rs @@ -5,8 +5,8 @@ use rustc_middle::ty::{self, Region}; 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 0c397350067c3..634cda86bc338 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -68,7 +68,7 @@ use rustc_middle::ty::{ 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 @@ impl<'tcx> InferCtxt<'tcx> { ) { debug!(?sup_type, ?sub_region, ?cause); let origin = SubregionOrigin::from_obligation_cause(cause, || { - infer::RelateParamBound( - cause.span, - sup_type, - match cause.code().peel_derives() { - ObligationCauseCode::WhereClause(_, span) - | ObligationCauseCode::WhereClauseInExpr(_, span, ..) - 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 711f20444defc..74a80a1b9aa7c 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 f2ec1dd3df74a..e75d7b7db1453 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::glb::Glb; 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 fbe64f47741ba..a6d10aa5968c7 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -17,7 +17,7 @@ use super::{ 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 7b12003643eb1..ed108f42969db 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_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; 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 ab6a19265f3fc..7908733e7348e 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 rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable}; 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 @@ impl<'tcx> InferCtxt<'tcx> { let delegate = FnMutDelegate { regions: &mut |br: ty::BoundRegion| { - ty::Region::new_placeholder( - self.tcx, - ty::PlaceholderRegion { universe: next_universe, bound: br }, - ) + ty::Region::new_placeholder(self.tcx, ty::PlaceholderRegion { + universe: next_universe, + bound: br, + }) }, types: &mut |bound_ty: ty::BoundTy| { - Ty::new_placeholder( - self.tcx, - ty::PlaceholderType { universe: next_universe, bound: bound_ty }, - ) + Ty::new_placeholder(self.tcx, ty::PlaceholderType { + universe: next_universe, + bound: bound_ty, + }) }, consts: &mut |bound_var: ty::BoundVar| { - ty::Const::new_placeholder( - self.tcx, - ty::PlaceholderConst { universe: next_universe, bound: bound_var }, - ) + ty::Const::new_placeholder(self.tcx, ty::PlaceholderConst { + universe: next_universe, + bound: bound_var, + }) }, }; diff --git a/compiler/rustc_infer/src/infer/relate/lub.rs b/compiler/rustc_infer/src/infer/relate/lub.rs index bf4d68b942863..35c7ab5000d70 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_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt}; 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 be16fca45216a..a402a8009ff8d 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 20db6583a2ba1..964fb1f681955 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_data_structures::undo_log::UndoLogs; 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 9aa02f89d2a76..79ea0915c9c05 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::infer::unify_key::{ConstVidKey, EffectVidKey, RegionVidKey}; 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 fd38040406d47..a076cdad672ab 100644 --- a/compiler/rustc_infer/src/traits/engine.rs +++ b/compiler/rustc_infer/src/traits/engine.rs @@ -45,15 +45,12 @@ pub trait TraitEngine<'tcx, E: 'tcx>: 'tcx { cause: ObligationCause<'tcx>, ) { let trait_ref = ty::TraitRef::new(infcx.tcx, def_id, [ty]); - self.register_predicate_obligation( - infcx, - Obligation { - cause, - recursion_depth: 0, - param_env, - predicate: trait_ref.upcast(infcx.tcx), - }, - ); + self.register_predicate_obligation(infcx, Obligation { + cause, + recursion_depth: 0, + param_env, + predicate: trait_ref.upcast(infcx.tcx), + }); } fn register_predicate_obligation( diff --git a/compiler/rustc_infer/src/traits/mod.rs b/compiler/rustc_infer/src/traits/mod.rs index 3a05b576a9744..34b0fe3e96788 100644 --- a/compiler/rustc_infer/src/traits/mod.rs +++ b/compiler/rustc_infer/src/traits/mod.rs @@ -18,14 +18,14 @@ pub use rustc_middle::traits::*; 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 f6b05340952a9..fa813d0f90ca0 100644 --- a/compiler/rustc_infer/src/traits/project.rs +++ b/compiler/rustc_infer/src/traits/project.rs @@ -200,10 +200,10 @@ impl<'tcx> ProjectionCache<'_, 'tcx> { 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 3e4f9b4816660..a977bd15d3bb9 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 347dc185043e4..c2241773c8ccb 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -2,7 +2,7 @@ use std::path::PathBuf; 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_query_system::query::print_query_stack; 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 3b6c2acaf3083..94ebe51f213f6 100644 --- a/compiler/rustc_interface/src/lib.rs +++ b/compiler/rustc_interface/src/lib.rs @@ -14,7 +14,7 @@ mod queries; 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 b93bc3ed84f54..617581cf667f0 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -13,10 +13,10 @@ use rustc_data_structures::sync::{AppendOnlyIndexVec, FreezeLock, Lrc, OnceLock, 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::cstore::Untracked; 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 44e07b36b616b..3a1833452d4b6 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -3,8 +3,8 @@ use std::cell::{RefCell, RefMut}; 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::arena::Arena; 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 080f2a1785afb..57aa3deae806b 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -6,22 +6,22 @@ use std::sync::Arc; 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 761d288a7c2eb..71e8accf5a328 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 493ec2b0f6045..556bbf1f5182e 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 5b99495f47581..6fa7a150516b8 100644 --- a/compiler/rustc_lexer/src/unescape/tests.rs +++ b/compiler/rustc_lexer/src/unescape/tests.rs @@ -108,15 +108,12 @@ fn test_unescape_str_warn() { check("\\\n", &[]); check("\\\n ", &[]); - check( - "\\\n \u{a0} x", - &[ - (0..5, Err(EscapeError::UnskippedWhitespaceWarning)), - (3..5, Ok('\u{a0}')), - (5..6, Ok(' ')), - (6..7, Ok('x')), - ], - ); + check("\\\n \u{a0} x", &[ + (0..5, Err(EscapeError::UnskippedWhitespaceWarning)), + (3..5, Ok('\u{a0}')), + (5..6, Ok(' ')), + (6..7, Ok('x')), + ]); check("\\\n \n x", &[(0..7, Err(EscapeError::MultipleSkippedLinesWarning)), (7..8, Ok('x'))]); } diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index e71c5676ce4f5..375cfccbe9f71 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -395,8 +395,6 @@ lint_improper_ctypes_opaque = opaque types have no C equivalent lint_improper_ctypes_pat_help = consider using the base type instead lint_improper_ctypes_pat_reason = pattern types have no C equivalent - -lint_improper_ctypes_recursion_limit_reached = type is infinitely recursive lint_improper_ctypes_slice_help = consider using a raw pointer instead lint_improper_ctypes_slice_reason = slices have no C equivalent @@ -592,10 +590,7 @@ lint_non_local_definitions_cargo_update = the {$macro_kind} `{$macro_name}` may lint_non_local_definitions_deprecation = this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue lint_non_local_definitions_impl = non-local `impl` definition, `impl` blocks should be written at the same level as their item - .remove_help = remove `{$may_remove_part}` to make the `impl` local - .without_trait = methods and associated constants are still usable outside the current expression, only `impl Local` and `impl dyn Local` can ever be private, and only if the type is nested in the same item as the `impl` - .with_trait = an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` - .bounds = `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type + .non_local = an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` .doctest = make this doc-test a standalone test with its own `fn main() {"{"} ... {"}"}` .exception = items in an anonymous const item (`const _: () = {"{"} ... {"}"}`) are treated as in the same scope as the anonymous const's declaration for the purpose of this lint .const_anon = use a const-anon item to suppress this lint @@ -617,12 +612,6 @@ lint_non_local_definitions_macro_rules = non-local `macro_rules!` definition, `# remove the `#[macro_export]` or make this doc-test a standalone test with its own `fn main() {"{"} ... {"}"}` .non_local = a `macro_rules!` definition is non-local if it is nested inside an item and has a `#[macro_export]` attribute -lint_non_local_definitions_may_move = may need to be moved as well - -lint_non_local_definitions_of_trait_not_local = `{$of_trait_str}` is not local - -lint_non_local_definitions_self_ty_not_local = `{$self_ty_str}` is not local - lint_non_snake_case = {$sort} `{$name}` should have a snake case name .rename_or_convert_suggestion = rename the identifier or convert it to a snake case raw identifier .cannot_convert_note = `{$sc}` cannot be used as a raw identifier @@ -899,6 +888,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 8b92180e9bd00..8bd9c899a6286 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -28,10 +28,10 @@ use rustc_ast::visit::{FnCtxt, FnKind}; 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::lint::in_external_macro; 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 @@ use crate::lints::{ 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 @@ impl EarlyLintPass for WhileTrue { "{}loop", label.map_or_else(String::new, |label| format!("{}: ", label.ident,)) ); - cx.emit_span_lint( - WHILE_TRUE, - condition_span, - BuiltinWhileTrue { suggestion: condition_span, replace }, - ); + cx.emit_span_lint(WHILE_TRUE, condition_span, BuiltinWhileTrue { + suggestion: condition_span, + replace, + }); } } } @@ -436,11 +435,10 @@ impl MissingDoc { let attrs = cx.tcx.hir().attrs(cx.tcx.local_def_id_to_hir_id(def_id)); let has_doc = attrs.iter().any(has_doc); if !has_doc { - cx.emit_span_lint( - MISSING_DOCS, - cx.tcx.def_span(def_id), - BuiltinMissingDoc { article, desc }, - ); + cx.emit_span_lint(MISSING_DOCS, cx.tcx.def_span(def_id), BuiltinMissingDoc { + article, + desc, + }); } } } @@ -721,11 +719,10 @@ impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { .next() .is_some(); if !has_impl { - cx.emit_span_lint( - MISSING_DEBUG_IMPLEMENTATIONS, - item.span, - BuiltinMissingDebugImpl { tcx: cx.tcx, def_id: debug }, - ); + cx.emit_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, item.span, BuiltinMissingDebugImpl { + tcx: cx.tcx, + def_id: debug, + }); } } } @@ -847,24 +844,21 @@ impl EarlyLintPass for DeprecatedAttr { BuiltinDeprecatedAttrLinkSuggestion::Default { suggestion: attr.span } } }; - cx.emit_span_lint( - DEPRECATED, - attr.span, - BuiltinDeprecatedAttrLink { name, reason, link, suggestion }, - ); + cx.emit_span_lint(DEPRECATED, attr.span, BuiltinDeprecatedAttrLink { + name, + reason, + link, + suggestion, + }); } return; } } 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 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { match param.kind { GenericParamKind::Lifetime { .. } => {} GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => { - cx.emit_span_lint( - NO_MANGLE_GENERIC_ITEMS, - span, - BuiltinNoMangleGeneric { suggestion: no_mangle_attr.span }, - ); + cx.emit_span_lint(NO_MANGLE_GENERIC_ITEMS, span, BuiltinNoMangleGeneric { + suggestion: no_mangle_attr.span, + }); break; } } @@ -1064,11 +1056,9 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { // Const items do not refer to a particular location in memory, and therefore // don't have anything to attach a symbol to - cx.emit_span_lint( - NO_MANGLE_CONST_ITEMS, - it.span, - BuiltinConstNoMangle { suggestion }, - ); + cx.emit_span_lint(NO_MANGLE_CONST_ITEMS, it.span, BuiltinConstNoMangle { + suggestion, + }); } } hir::ItemKind::Impl(hir::Impl { generics, items, .. }) => { @@ -1316,15 +1306,11 @@ impl UnreachablePub { 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 @@ impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { let enable_feat_help = cx.tcx.sess.is_nightly_build(); if let [.., label_sp] = *where_spans { - cx.emit_span_lint( - TYPE_ALIAS_BOUNDS, - where_spans, - BuiltinTypeAliasBounds { - in_where_clause: true, - label: label_sp, - enable_feat_help, - suggestions: vec![(generics.where_clause_span, String::new())], - preds: generics.predicates, - ty: ty.take(), - }, - ); + cx.emit_span_lint(TYPE_ALIAS_BOUNDS, where_spans, BuiltinTypeAliasBounds { + in_where_clause: true, + label: label_sp, + enable_feat_help, + suggestions: vec![(generics.where_clause_span, String::new())], + preds: generics.predicates, + ty: ty.take(), + }); } if let [.., label_sp] = *inline_spans { - cx.emit_span_lint( - TYPE_ALIAS_BOUNDS, - inline_spans, - BuiltinTypeAliasBounds { - in_where_clause: false, - label: label_sp, - enable_feat_help, - suggestions: inline_sugg, - preds: generics.predicates, - ty, - }, - ); + cx.emit_span_lint(TYPE_ALIAS_BOUNDS, inline_spans, BuiltinTypeAliasBounds { + in_where_clause: false, + label: label_sp, + enable_feat_help, + suggestions: inline_sugg, + preds: generics.predicates, + ty, + }); } } } @@ -1579,11 +1557,10 @@ impl<'tcx> LateLintPass<'tcx> for TrivialConstraints { | 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 @@ impl KeywordIdents { return; } - cx.emit_span_lint( - lint, - ident.span, - BuiltinKeywordIdents { kw: ident, next: edition, suggestion: ident.span, prefix }, - ); + cx.emit_span_lint(lint, ident.span, BuiltinKeywordIdents { + kw: ident, + next: edition, + suggestion: ident.span, + prefix, + }); } } @@ -2322,11 +2300,11 @@ impl EarlyLintPass for IncompleteInternalFeatures { let help = HAS_MIN_FEATURES.contains(&name).then_some(BuiltinIncompleteFeaturesHelp); - cx.emit_span_lint( - INCOMPLETE_FEATURES, - span, - BuiltinIncompleteFeatures { name, note, help }, - ); + cx.emit_span_lint(INCOMPLETE_FEATURES, span, BuiltinIncompleteFeatures { + name, + note, + help, + }); } else { cx.emit_span_lint(INTERNAL_FEATURES, span, BuiltinInternalFeatures { name }); } @@ -2647,17 +2625,13 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { InitKind::Uninit => fluent::lint_builtin_unpermitted_type_init_uninit, }; let sub = BuiltinUnpermittedTypeInitSub { err }; - cx.emit_span_lint( - INVALID_VALUE, - expr.span, - BuiltinUnpermittedTypeInit { - msg, - ty: conjured_ty, - label: expr.span, - sub, - tcx: cx.tcx, - }, - ); + cx.emit_span_lint(INVALID_VALUE, expr.span, BuiltinUnpermittedTypeInit { + msg, + ty: conjured_ty, + label: expr.span, + sub, + tcx: cx.tcx, + }); } } } @@ -2735,11 +2709,9 @@ impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { 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 @@ impl<'tcx> LateLintPass<'tcx> for AsmLabels { let span = span.unwrap_or(*template_span); match label_kind { AsmLabelKind::Named => { - cx.emit_span_lint( - NAMED_ASM_LABELS, - span, - InvalidAsmLabel::Named { missing_precise_span }, - ); + cx.emit_span_lint(NAMED_ASM_LABELS, span, InvalidAsmLabel::Named { + missing_precise_span, + }); } AsmLabelKind::FormatArg => { - cx.emit_span_lint( - NAMED_ASM_LABELS, - span, - InvalidAsmLabel::FormatArg { missing_precise_span }, - ); + cx.emit_span_lint(NAMED_ASM_LABELS, span, InvalidAsmLabel::FormatArg { + missing_precise_span, + }); } // the binary asm issue only occurs when using intel syntax on x86 targets AsmLabelKind::Binary @@ -2977,11 +2945,10 @@ impl<'tcx> LateLintPass<'tcx> for AsmLabels { 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 c9e2eee16b3b9..39f90a8e9ed14 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -29,15 +29,15 @@ use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; 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 @@ impl LintStore { } pub fn register_group_alias(&mut self, lint_name: &'static str, alias: &'static str) { - self.lint_groups.insert( - alias, - LintGroup { - lint_ids: vec![], - is_externally_loaded: false, - depr: Some(LintAlias { name: lint_name, silent: true }), - }, - ); + self.lint_groups.insert(alias, LintGroup { + lint_ids: vec![], + is_externally_loaded: false, + depr: Some(LintAlias { name: lint_name, silent: true }), + }); } pub fn register_group( @@ -273,14 +270,11 @@ impl LintStore { .insert(name, LintGroup { lint_ids: to, is_externally_loaded, depr: None }) .is_none(); if let Some(deprecated) = deprecated_name { - self.lint_groups.insert( - deprecated, - LintGroup { - lint_ids: vec![], - is_externally_loaded, - depr: Some(LintAlias { name, silent: false }), - }, - ); + self.lint_groups.insert(deprecated, LintGroup { + lint_ids: vec![], + is_externally_loaded, + depr: Some(LintAlias { name, silent: false }), + }); } if !new { diff --git a/compiler/rustc_lint/src/context/diagnostics.rs b/compiler/rustc_lint/src/context/diagnostics.rs index fd13c418c09aa..168e3a8e92c5f 100644 --- a/compiler/rustc_lint/src/context/diagnostics.rs +++ b/compiler/rustc_lint/src/context/diagnostics.rs @@ -5,13 +5,13 @@ use std::borrow::Cow; 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 38c4e48928ff3..16994846545df 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 f174470b7a731..657642e093ccd 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 @@ impl<'tcx> LateLintPass<'tcx> for DerefIntoDynSupertrait { .find_map(|i| (i.ident.name == sym::Target).then_some(i.span)) .map(|label| SupertraitAsDerefTargetLabel { label }); let span = tcx.def_span(item.owner_id.def_id); - cx.emit_span_lint( - DEREF_INTO_DYN_SUPERTRAIT, - span, - SupertraitAsDerefTarget { - self_ty, - supertrait_principal: supertrait_principal.map_bound(|trait_ref| { - ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref) - }), - target_principal, - label: span, - label2, - }, - ); + cx.emit_span_lint(DEREF_INTO_DYN_SUPERTRAIT, span, SupertraitAsDerefTarget { + self_ty, + supertrait_principal: supertrait_principal + .map_bound(|trait_ref| ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)), + target_principal, + label: span, + label2, + }); } } } diff --git a/compiler/rustc_lint/src/drop_forget_useless.rs b/compiler/rustc_lint/src/drop_forget_useless.rs index a9de258e005c9..364c6fd488a8e 100644 --- a/compiler/rustc_lint/src/drop_forget_useless.rs +++ b/compiler/rustc_lint/src/drop_forget_useless.rs @@ -163,44 +163,32 @@ impl<'tcx> LateLintPass<'tcx> for DropForgetUseless { }; match fn_name { sym::mem_drop if arg_ty.is_ref() && !drop_is_single_call_in_arm => { - cx.emit_span_lint( - DROPPING_REFERENCES, - expr.span, - DropRefDiag { arg_ty, label: arg.span, sugg: let_underscore_ignore_sugg() }, - ); + cx.emit_span_lint(DROPPING_REFERENCES, expr.span, DropRefDiag { + arg_ty, + label: arg.span, + sugg: let_underscore_ignore_sugg(), + }); } sym::mem_forget if arg_ty.is_ref() => { - cx.emit_span_lint( - FORGETTING_REFERENCES, - expr.span, - ForgetRefDiag { - arg_ty, - label: arg.span, - sugg: let_underscore_ignore_sugg(), - }, - ); + cx.emit_span_lint(FORGETTING_REFERENCES, expr.span, ForgetRefDiag { + arg_ty, + label: arg.span, + sugg: let_underscore_ignore_sugg(), + }); } sym::mem_drop if is_copy && !drop_is_single_call_in_arm => { - cx.emit_span_lint( - DROPPING_COPY_TYPES, - expr.span, - DropCopyDiag { - arg_ty, - label: arg.span, - sugg: let_underscore_ignore_sugg(), - }, - ); + cx.emit_span_lint(DROPPING_COPY_TYPES, expr.span, DropCopyDiag { + arg_ty, + label: arg.span, + sugg: let_underscore_ignore_sugg(), + }); } sym::mem_forget if is_copy => { - cx.emit_span_lint( - FORGETTING_COPY_TYPES, - expr.span, - ForgetCopyDiag { - arg_ty, - label: arg.span, - sugg: let_underscore_ignore_sugg(), - }, - ); + cx.emit_span_lint(FORGETTING_COPY_TYPES, expr.span, ForgetCopyDiag { + arg_ty, + label: arg.span, + sugg: let_underscore_ignore_sugg(), + }); } sym::mem_drop if let ty::Adt(adt, _) = arg_ty.kind() diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index 0ee9dda1fefa2..2285877c9ef26 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 4e3eca496eadb..8e22a9bdc45a7 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 2450afbca064a..289e2c9b72243 100644 --- a/compiler/rustc_lint/src/expect.rs +++ b/compiler/rustc_lint/src/expect.rs @@ -3,8 +3,8 @@ use rustc_hir::CRATE_OWNER_ID; 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 1b25f21ef84dd..fcb7a6108c0e2 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::infer::TyCtxtInferExt; 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 @@ impl<'tcx> LateLintPass<'tcx> for ForLoopsOverFallibles { end_span: pat.span.between(arg.span), }; - cx.emit_span_lint( - FOR_LOOPS_OVER_FALLIBLES, - arg.span, - ForLoopsOverFalliblesDiag { article, ref_prefix, ty, sub, question_mark, suggestion }, - ); + cx.emit_span_lint(FOR_LOOPS_OVER_FALLIBLES, arg.span, ForLoopsOverFalliblesDiag { + article, + ref_prefix, + ty, + sub, + question_mark, + suggestion, + }); } } diff --git a/compiler/rustc_lint/src/foreign_modules.rs b/compiler/rustc_lint/src/foreign_modules.rs index 33b8b7c544bcc..1ead377607f1b 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -5,12 +5,12 @@ use rustc_hir::def::DefKind; 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 ebd8bd5605d78..025fd45204064 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 @@ impl HiddenUnicodeCodepoints { HiddenUnicodeCodepointsDiagSub::NoEscape { spans } }; - cx.emit_span_lint( - TEXT_DIRECTION_CODEPOINT_IN_LITERAL, - span, - HiddenUnicodeCodepointsDiag { label, count, span_label: span, labels, sub }, - ); + cx.emit_span_lint(TEXT_DIRECTION_CODEPOINT_IN_LITERAL, span, HiddenUnicodeCodepointsDiag { + label, + count, + span_label: span, + labels, + sub, + }); } } 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 7138d40a48f64..229d0c3642174 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_macros::LintDiagnostic; 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 @@ impl IfLetRescope { } } if let Some((span, hir_id)) = first_if_to_lint { - tcx.emit_node_span_lint( - IF_LET_RESCOPE, - hir_id, - span, - IfLetRescopeLint { - significant_droppers, - lifetime_ends, - rewrite: first_if_to_rewrite.then_some(IfLetRescopeRewrite { - match_heads, - consequent_heads, - closing_brackets: ClosingBrackets { - span: expr_end, - count: closing_brackets, - empty_alt, - }, - alt_heads, - }), - }, - ); + tcx.emit_node_span_lint(IF_LET_RESCOPE, hir_id, span, IfLetRescopeLint { + significant_droppers, + lifetime_ends, + rewrite: first_if_to_rewrite.then_some(IfLetRescopeRewrite { + match_heads, + consequent_heads, + closing_brackets: ClosingBrackets { + span: expr_end, + count: closing_brackets, + empty_alt, + }, + alt_heads, + }), + }); } } } diff --git a/compiler/rustc_lint/src/impl_trait_overcaptures.rs b/compiler/rustc_lint/src/impl_trait_overcaptures.rs index c43c650a9f912..a073d16f634d8 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_errors::{Applicability, LintDiagnostic}; 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::lint::FutureIncompatibilityReason; 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 @@ where // We only computed variance of lifetimes... debug_assert_matches!(self.tcx.def_kind(def_id), DefKind::LifetimeParam); let uncaptured = match *kind { - ParamKind::Early(name, index) => ty::Region::new_early_param( - self.tcx, - ty::EarlyParamRegion { name, index }, - ), + ParamKind::Early(name, index) => { + ty::Region::new_early_param(self.tcx, ty::EarlyParamRegion { + name, + index, + }) + } ParamKind::Free(def_id, name) => ty::Region::new_late_param( self.tcx, self.parent_def_id.to_def_id(), diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 9d637c1eb7f84..94cc58e495681 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -10,9 +10,9 @@ use rustc_hir::{ }; 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 @@ impl LateLintPass<'_> for DefaultHashTypes { Some(sym::HashSet) => "FxHashSet", _ => return, }; - cx.emit_span_lint( - DEFAULT_HASH_TYPES, - path.span, - DefaultHashTypesDiag { preferred, used: cx.tcx.item_name(def_id) }, - ); + cx.emit_span_lint(DEFAULT_HASH_TYPES, path.span, DefaultHashTypesDiag { + preferred, + used: cx.tcx.item_name(def_id), + }); } } @@ -107,18 +106,14 @@ impl LateLintPass<'_> for QueryStability { 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 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { match span { Some(span) => { - cx.emit_span_lint( - USAGE_OF_TY_TYKIND, - path.span, - TykindKind { suggestion: span }, - ); + cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindKind { + suggestion: span, + }); } None => cx.emit_span_lint(USAGE_OF_TY_TYKIND, path.span, TykindDiag), } @@ -220,11 +213,10 @@ impl<'tcx> LateLintPass<'tcx> for TyTyKind { && path.segments.len() > 1 && let Some(ty) = is_ty_or_ty_ctxt(cx, path) { - cx.emit_span_lint( - USAGE_OF_QUALIFIED_TY, - path.span, - TyQualified { ty, suggestion: path.span }, - ); + cx.emit_span_lint(USAGE_OF_QUALIFIED_TY, path.span, TyQualified { + ty, + suggestion: path.span, + }); } } _ => {} @@ -418,11 +410,9 @@ impl<'tcx> LateLintPass<'tcx> for ExistingDocKeyword { 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 @@ impl LateLintPass<'_> for BadOptAccess { && let Some(lit) = item.lit() && let ast::LitKind::Str(val, _) = lit.kind { - cx.emit_span_lint( - BAD_OPT_ACCESS, - expr.span, - BadOptAccessDiag { msg: val.as_str() }, - ); + cx.emit_span_lint(BAD_OPT_ACCESS, expr.span, BadOptAccessDiag { + msg: val.as_str(), + }); } } } diff --git a/compiler/rustc_lint/src/late.rs b/compiler/rustc_lint/src/late.rs index cb369d99a8450..de40139715076 100644 --- a/compiler/rustc_lint/src/late.rs +++ b/compiler/rustc_lint/src/late.rs @@ -18,14 +18,14 @@ use std::any::Any; 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 1368cc87e3e16..a12a97ee5730e 100644 --- a/compiler/rustc_lint/src/let_underscore.rs +++ b/compiler/rustc_lint/src/let_underscore.rs @@ -2,7 +2,7 @@ use rustc_errors::MultiSpan; 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 @@ impl<'tcx> LateLintPass<'tcx> for LetUnderscore { }; if is_sync_lock { let span = MultiSpan::from_span(pat.span); - cx.emit_span_lint( - LET_UNDERSCORE_LOCK, - span, - NonBindingLet::SyncLock { sub, pat: pat.span }, - ); + cx.emit_span_lint(LET_UNDERSCORE_LOCK, span, NonBindingLet::SyncLock { + sub, + pat: pat.span, + }); // Only emit let_underscore_drop for top-level `_` patterns. } else if can_use_init.is_some() { cx.emit_span_lint(LET_UNDERSCORE_DROP, local.span, NonBindingLet::DropType { sub }); diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 796d66f13d435..007e86ae0d2b2 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -2,25 +2,25 @@ use rustc_ast_pretty::pprust; 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 d1da2809cc743..c74cb866f21fa 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -86,6 +86,7 @@ mod tail_expr_drop_order; mod traits; mod types; mod unit_bindings; +mod unqualified_local_imports; mod unused; use async_closures::AsyncClosureUsage; @@ -126,6 +127,7 @@ use tail_expr_drop_order::TailExprDropOrder; use traits::*; use types::*; use unit_bindings::*; +use unqualified_local_imports::*; use unused::*; #[rustfmt::skip] @@ -133,7 +135,7 @@ pub use builtin::{MissingDoc, SoftLints}; 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 @@ late_lint_methods!( 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 11006862d05b0..0045cfcaa56ad 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -13,15 +13,15 @@ use rustc_hir::{self as hir, MissingLifetimeKind}; 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)] @@ -1375,12 +1375,7 @@ pub(crate) enum NonLocalDefinitionsDiag { body_name: String, cargo_update: Option, const_anon: Option>, - move_to: Option<(Span, Vec)>, doctest: bool, - may_remove: Option<(Span, String)>, - has_trait: bool, - self_ty_str: String, - of_trait_str: Option, macro_to_change: Option<(String, &'static str)>, }, MacroRules { @@ -1401,22 +1396,13 @@ impl<'a> LintDiagnostic<'a, ()> for NonLocalDefinitionsDiag { body_name, cargo_update, const_anon, - move_to, doctest, - may_remove, - has_trait, - self_ty_str, - of_trait_str, macro_to_change, } => { diag.primary_message(fluent::lint_non_local_definitions_impl); diag.arg("depth", depth); diag.arg("body_kind_descr", body_kind_descr); diag.arg("body_name", body_name); - diag.arg("self_ty_str", self_ty_str); - if let Some(of_trait_str) = of_trait_str { - diag.arg("of_trait_str", of_trait_str); - } if let Some((macro_to_change, macro_kind)) = macro_to_change { diag.arg("macro_to_change", macro_to_change); @@ -1427,34 +1413,12 @@ impl<'a> LintDiagnostic<'a, ()> for NonLocalDefinitionsDiag { diag.subdiagnostic(cargo_update); } - if has_trait { - diag.note(fluent::lint_bounds); - diag.note(fluent::lint_with_trait); - } else { - diag.note(fluent::lint_without_trait); - } + diag.note(fluent::lint_non_local); - if let Some((move_help, may_move)) = move_to { - let mut ms = MultiSpan::from_span(move_help); - for sp in may_move { - ms.push_span_label(sp, fluent::lint_non_local_definitions_may_move); - } - diag.span_help(ms, fluent::lint_non_local_definitions_impl_move_help); - } if doctest { diag.help(fluent::lint_doctest); } - if let Some((span, part)) = may_remove { - diag.arg("may_remove_part", part); - diag.span_suggestion( - span, - fluent::lint_remove_help, - "", - Applicability::MaybeIncorrect, - ); - } - if let Some(const_anon) = const_anon { diag.note(fluent::lint_exception); if let Some(const_anon) = const_anon { @@ -3093,3 +3057,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 e3b1967da09c7..23f4f7289067d 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::edition::Edition; 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 3b27e45613690..776d51a672718 100644 --- a/compiler/rustc_lint/src/map_unit_fn.rs +++ b/compiler/rustc_lint/src/map_unit_fn.rs @@ -60,39 +60,25 @@ impl<'tcx> LateLintPass<'tcx> for MapUnitFn { let fn_ty = cx.tcx.fn_sig(id).skip_binder(); let ret_ty = fn_ty.output().skip_binder(); if is_unit_type(ret_ty) { - cx.emit_span_lint( - MAP_UNIT_FN, - span, - MappingToUnit { - function_label: cx - .tcx - .span_of_impl(*id) - .unwrap_or(default_span), - argument_label: args[0].span, - map_label: arg_ty.default_span(cx.tcx), - suggestion: path.ident.span, - replace: "for_each".to_string(), - }, - ) + cx.emit_span_lint(MAP_UNIT_FN, span, MappingToUnit { + function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span), + argument_label: args[0].span, + map_label: arg_ty.default_span(cx.tcx), + suggestion: path.ident.span, + replace: "for_each".to_string(), + }) } } else if let ty::Closure(id, subs) = arg_ty.kind() { let cl_ty = subs.as_closure().sig(); let ret_ty = cl_ty.output().skip_binder(); if is_unit_type(ret_ty) { - cx.emit_span_lint( - MAP_UNIT_FN, - span, - MappingToUnit { - function_label: cx - .tcx - .span_of_impl(*id) - .unwrap_or(default_span), - argument_label: args[0].span, - map_label: arg_ty.default_span(cx.tcx), - suggestion: path.ident.span, - replace: "for_each".to_string(), - }, - ) + cx.emit_span_lint(MAP_UNIT_FN, span, MappingToUnit { + function_label: cx.tcx.span_of_impl(*id).unwrap_or(default_span), + argument_label: args[0].span, + map_label: arg_ty.default_span(cx.tcx), + suggestion: path.ident.span, + replace: "for_each".to_string(), + }) } } } diff --git a/compiler/rustc_lint/src/methods.rs b/compiler/rustc_lint/src/methods.rs index dff72bb622f23..df22bf0972d71 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 08d054b6a8bd3..9b495c19990c1 100644 --- a/compiler/rustc_lint/src/non_ascii_idents.rs +++ b/compiler/rustc_lint/src/non_ascii_idents.rs @@ -209,30 +209,22 @@ impl EarlyLintPass for NonAsciiIdents { if codepoints.is_empty() { continue; } - cx.emit_span_lint( - UNCOMMON_CODEPOINTS, - sp, - IdentifierUncommonCodepoints { - codepoints_len: codepoints.len(), - codepoints: codepoints.into_iter().map(|(c, _)| c).collect(), - identifier_type: id_ty_descr, - }, - ); + cx.emit_span_lint(UNCOMMON_CODEPOINTS, sp, IdentifierUncommonCodepoints { + codepoints_len: codepoints.len(), + codepoints: codepoints.into_iter().map(|(c, _)| c).collect(), + identifier_type: id_ty_descr, + }); } let remaining = chars .extract_if(|(c, _)| !GeneralSecurityProfile::identifier_allowed(*c)) .collect::>(); if !remaining.is_empty() { - cx.emit_span_lint( - UNCOMMON_CODEPOINTS, - sp, - IdentifierUncommonCodepoints { - codepoints_len: remaining.len(), - codepoints: remaining.into_iter().map(|(c, _)| c).collect(), - identifier_type: "Restricted", - }, - ); + cx.emit_span_lint(UNCOMMON_CODEPOINTS, sp, IdentifierUncommonCodepoints { + codepoints_len: remaining.len(), + codepoints: remaining.into_iter().map(|(c, _)| c).collect(), + identifier_type: "Restricted", + }); } } } @@ -261,16 +253,12 @@ impl EarlyLintPass for NonAsciiIdents { .entry(skeleton_sym) .and_modify(|(existing_symbol, existing_span, existing_is_ascii)| { if !*existing_is_ascii || !is_ascii { - cx.emit_span_lint( - CONFUSABLE_IDENTS, - sp, - ConfusableIdentifierPair { - existing_sym: *existing_symbol, - sym: symbol, - label: *existing_span, - main_label: sp, - }, - ); + cx.emit_span_lint(CONFUSABLE_IDENTS, sp, ConfusableIdentifierPair { + existing_sym: *existing_symbol, + sym: symbol, + label: *existing_span, + main_label: sp, + }); } if *existing_is_ascii && !is_ascii { *existing_symbol = symbol; @@ -382,11 +370,10 @@ impl EarlyLintPass for NonAsciiIdents { let char_info = format!("'{}' (U+{:04X})", ch, ch as u32); includes += &char_info; } - cx.emit_span_lint( - MIXED_SCRIPT_CONFUSABLES, - sp, - MixedScriptConfusables { set: script_set.to_string(), includes }, - ); + cx.emit_span_lint(MIXED_SCRIPT_CONFUSABLES, sp, MixedScriptConfusables { + set: script_set.to_string(), + includes, + }); } } } diff --git a/compiler/rustc_lint/src/non_fmt_panic.rs b/compiler/rustc_lint/src/non_fmt_panic.rs index 10a517bfbcb76..51877e8a03495 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::lint::FutureIncompatibilityReason; 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 1546d79e4fd91..56f930ea7f62e 100644 --- a/compiler/rustc_lint/src/non_local_def.rs +++ b/compiler/rustc_lint/src/non_local_def.rs @@ -1,23 +1,15 @@ use rustc_errors::MultiSpan; -use rustc_hir::def::DefKind; +use rustc_hir::def::{DefKind, Res}; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::{Body, HirId, Item, ItemKind, Node, Path, QPath, TyKind}; -use rustc_infer::infer::InferCtxt; -use rustc_infer::traits::{Obligation, ObligationCause}; -use rustc_middle::ty::{ - self, Binder, EarlyBinder, TraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, -}; +use rustc_hir::{Body, HirId, Item, ItemKind, Node, Path, TyKind}; +use rustc_middle::ty::TyCtxt; 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_trait_selection::error_reporting::traits::ambiguity::{ - compute_applicable_impls_for_diagnostics, CandidateSource, -}; -use rustc_trait_selection::infer::TyCtxtInferExt; +use rustc_span::{ExpnKind, MacroKind, Span, sym}; 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]` @@ -49,7 +41,7 @@ declare_lint! { /// All nested bodies (functions, enum discriminant, array length, consts) (expect for /// `const _: Ty = { ... }` in top-level module, which is still undecided) are checked. pub NON_LOCAL_DEFINITIONS, - Allow, + Warn, "checks for non-local definitions", report_in_external_macro } @@ -142,42 +134,28 @@ impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions { None }; - // Part 1: Is the Self type local? - let self_ty_has_local_parent = - ty_has_local_parent(&impl_.self_ty.kind, cx, parent, parent_parent); - - if self_ty_has_local_parent { - return; + // 1. We collect all the `hir::Path` from the `Self` type and `Trait` ref + // of the `impl` definition + let mut collector = PathCollector { paths: Vec::new() }; + collector.visit_ty(&impl_.self_ty); + if let Some(of_trait) = &impl_.of_trait { + collector.visit_trait_ref(of_trait); } - // Part 2: Is the Trait local? - let of_trait_has_local_parent = impl_ - .of_trait - .map(|of_trait| path_has_local_parent(of_trait.path, cx, parent, parent_parent)) - .unwrap_or(false); - - if of_trait_has_local_parent { - return; - } - - // Part 3: Is the impl definition leaking outside it's defining scope? - // - // We always consider inherent impls to be leaking. - let impl_has_enough_non_local_candidates = cx - .tcx - .impl_trait_ref(def_id) - .map(|binder| { - impl_trait_ref_has_enough_non_local_candidates( - cx.tcx, - item.span, - def_id, - binder, - |did| did_has_local_parent(did, cx.tcx, parent, parent_parent), - ) - }) - .unwrap_or(false); + // 1.5. Remove any path that doesn't resolve to a `DefId` or if it resolve to a + // type-param (e.g. `T`). + collector.paths.retain( + |p| matches!(p.res, Res::Def(def_kind, _) if def_kind != DefKind::TyParam), + ); - if impl_has_enough_non_local_candidates { + // 2. We check if any of path reference a "local" parent and if that the case + // we bail out as asked by T-lang, even though this isn't correct from a + // type-system point of view, as inference exists and could still leak the impl. + if collector + .paths + .iter() + .any(|path| path_has_local_parent(path, cx, parent, parent_parent)) + { return; } @@ -199,76 +177,28 @@ impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions { let const_anon = matches!(parent_def_kind, DefKind::Const | DefKind::Static { .. }) .then_some(span_for_const_anon_suggestion); - let may_remove = match &impl_.self_ty.kind { - TyKind::Ptr(mut_ty) | TyKind::Ref(_, mut_ty) - if ty_has_local_parent(&mut_ty.ty.kind, cx, parent, parent_parent) => - { - let type_ = - if matches!(impl_.self_ty.kind, TyKind::Ptr(_)) { "*" } else { "&" }; - let part = format!("{}{}", type_, mut_ty.mutbl.prefix_str()); - Some((impl_.self_ty.span.shrink_to_lo().until(mut_ty.ty.span), part)) - } - _ => None, - }; - let impl_span = item.span.shrink_to_lo().to(impl_.self_ty.span); let mut ms = MultiSpan::from_span(impl_span); - let (self_ty_span, self_ty_str) = - self_ty_kind_for_diagnostic(&impl_.self_ty, cx.tcx); - - ms.push_span_label( - self_ty_span, - fluent::lint_non_local_definitions_self_ty_not_local, - ); - let of_trait_str = if let Some(of_trait) = &impl_.of_trait { + for path in &collector.paths { + // FIXME: While a translatable diagnostic message can have an argument + // we (currently) have no way to set different args per diag msg with + // `MultiSpan::push_span_label`. + #[allow(rustc::untranslatable_diagnostic)] ms.push_span_label( - path_span_without_args(&of_trait.path), - fluent::lint_non_local_definitions_of_trait_not_local, + path_span_without_args(path), + format!("`{}` is not local", path_name_to_string(path)), ); - Some(path_name_to_string(&of_trait.path)) - } else { - None - }; - - let (doctest, move_to) = if is_at_toplevel_doctest() { - (true, None) - } else { - let mut collector = PathCollector { paths: Vec::new() }; - collector.visit_ty(&impl_.self_ty); - if let Some(of_trait) = &impl_.of_trait { - collector.visit_trait_ref(of_trait); - } - collector.visit_generics(&impl_.generics); - - let mut may_move: Vec = collector - .paths - .into_iter() - .filter_map(|path| { - if let Some(did) = path.res.opt_def_id() - && did_has_local_parent(did, cx.tcx, parent, parent_parent) - { - Some(cx.tcx.def_span(did)) - } else { - None - } - }) - .collect(); - may_move.sort(); - may_move.dedup(); + } - let move_to = if may_move.is_empty() { - ms.push_span_label( - cx.tcx.def_span(parent), - fluent::lint_non_local_definitions_impl_move_help, - ); - None - } else { - Some((cx.tcx.def_span(parent), may_move)) - }; + let doctest = is_at_toplevel_doctest(); - (false, move_to) - }; + if !doctest { + ms.push_span_label( + cx.tcx.def_span(parent), + fluent::lint_non_local_definitions_impl_move_help, + ); + } let macro_to_change = if let ExpnKind::Macro(kind, name) = item.span.ctxt().outer_expn_data().kind { @@ -277,26 +207,17 @@ impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions { None }; - cx.emit_span_lint( - NON_LOCAL_DEFINITIONS, - ms, - NonLocalDefinitionsDiag::Impl { - depth: self.body_depth, - body_kind_descr: cx.tcx.def_kind_descr(parent_def_kind, parent), - body_name: parent_opt_item_name - .map(|s| s.to_ident_string()) - .unwrap_or_else(|| "".to_string()), - cargo_update: cargo_update(), - const_anon, - 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, + doctest, + macro_to_change, + }) } ItemKind::Macro(_macro, MacroKind::Bang) if cx.tcx.has_attr(item.owner_id.def_id, sym::macro_export) => @@ -320,90 +241,6 @@ impl<'tcx> LateLintPass<'tcx> for NonLocalDefinitions { } } -// Detecting if the impl definition is leaking outside of its defining scope. -// -// Rule: for each impl, instantiate all local types with inference vars and -// then assemble candidates for that goal, if there are more than 1 (non-private -// impls), it does not leak. -// -// https://github.com/rust-lang/rust/issues/121621#issuecomment-1976826895 -fn impl_trait_ref_has_enough_non_local_candidates<'tcx>( - tcx: TyCtxt<'tcx>, - infer_span: Span, - trait_def_id: DefId, - binder: EarlyBinder<'tcx, TraitRef<'tcx>>, - mut did_has_local_parent: impl FnMut(DefId) -> bool, -) -> bool { - let infcx = tcx - .infer_ctxt() - // We use the new trait solver since the obligation we are trying to - // prove here may overflow and those are fatal in the old trait solver. - // Which is unacceptable for a lint. - // - // Thanksfully the part we use here are very similar to the - // new-trait-solver-as-coherence, which is in stabilization. - // - // https://github.com/rust-lang/rust/issues/123573 - .with_next_trait_solver(true) - .build(); - - let trait_ref = binder.instantiate(tcx, infcx.fresh_args_for_item(infer_span, trait_def_id)); - - let trait_ref = trait_ref.fold_with(&mut ReplaceLocalTypesWithInfer { - infcx: &infcx, - infer_span, - did_has_local_parent: &mut did_has_local_parent, - }); - - let poly_trait_obligation = Obligation::new( - tcx, - ObligationCause::dummy(), - ty::ParamEnv::empty(), - Binder::dummy(trait_ref), - ); - - let ambiguities = compute_applicable_impls_for_diagnostics(&infcx, &poly_trait_obligation); - - let mut it = ambiguities.iter().filter(|ambi| match ambi { - CandidateSource::DefId(did) => !did_has_local_parent(*did), - CandidateSource::ParamEnv(_) => unreachable!(), - }); - - let _ = it.next(); - it.next().is_some() -} - -/// Replace every local type by inference variable. -/// -/// ```text -/// as std::cmp::PartialEq>> -/// to -/// as std::cmp::PartialEq>> -/// ``` -struct ReplaceLocalTypesWithInfer<'a, 'tcx, F: FnMut(DefId) -> bool> { - infcx: &'a InferCtxt<'tcx>, - did_has_local_parent: F, - infer_span: Span, -} - -impl<'a, 'tcx, F: FnMut(DefId) -> bool> TypeFolder> - for ReplaceLocalTypesWithInfer<'a, 'tcx, F> -{ - fn cx(&self) -> TyCtxt<'tcx> { - self.infcx.tcx - } - - fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { - if let Some(def) = t.ty_adt_def() - && (self.did_has_local_parent)(def.did()) - { - self.infcx.next_ty_var(self.infer_span) - } else { - t.super_fold_with(self) - } - } -} - /// Simple hir::Path collector struct PathCollector<'tcx> { paths: Vec>, @@ -416,42 +253,6 @@ impl<'tcx> Visitor<'tcx> for PathCollector<'tcx> { } } -/// Given a `Ty` we check if the (outermost) type is local. -fn ty_has_local_parent( - ty_kind: &TyKind<'_>, - cx: &LateContext<'_>, - impl_parent: DefId, - impl_parent_parent: Option, -) -> bool { - match ty_kind { - TyKind::Path(QPath::Resolved(_, ty_path)) => { - path_has_local_parent(ty_path, cx, impl_parent, impl_parent_parent) - } - TyKind::TraitObject([principle_poly_trait_ref, ..], _, _) => path_has_local_parent( - principle_poly_trait_ref.0.trait_ref.path, - cx, - impl_parent, - impl_parent_parent, - ), - TyKind::TraitObject([], _, _) - | TyKind::InferDelegation(_, _) - | TyKind::Slice(_) - | TyKind::Array(_, _) - | TyKind::Ptr(_) - | TyKind::Ref(_, _) - | TyKind::BareFn(_) - | TyKind::Never - | TyKind::Tup(_) - | TyKind::Path(_) - | TyKind::Pat(..) - | TyKind::AnonAdt(_) - | TyKind::OpaqueDef(_, _, _) - | TyKind::Typeof(_) - | TyKind::Infer - | TyKind::Err(_) => false, - } -} - /// Given a path and a parent impl def id, this checks if the if parent resolution /// def id correspond to the def id of the parent impl definition. /// @@ -507,38 +308,3 @@ fn path_span_without_args(path: &Path<'_>) -> Span { fn path_name_to_string(path: &Path<'_>) -> String { path.segments.last().unwrap().ident.name.to_ident_string() } - -/// Compute the `Span` and visual representation for the `Self` we want to point at; -/// It follows part of the actual logic of non-local, and if possible return the least -/// amount possible for the span and representation. -fn self_ty_kind_for_diagnostic(ty: &rustc_hir::Ty<'_>, tcx: TyCtxt<'_>) -> (Span, String) { - match ty.kind { - TyKind::Path(QPath::Resolved(_, ty_path)) => ( - path_span_without_args(ty_path), - ty_path - .res - .opt_def_id() - .map(|did| tcx.opt_item_name(did)) - .flatten() - .as_ref() - .map(|s| Symbol::as_str(s)) - .unwrap_or("") - .to_string(), - ), - TyKind::TraitObject([principle_poly_trait_ref, ..], _, _) => { - let path = &principle_poly_trait_ref.0.trait_ref.path; - ( - path_span_without_args(path), - path.res - .opt_def_id() - .map(|did| tcx.opt_item_name(did)) - .flatten() - .as_ref() - .map(|s| Symbol::as_str(s)) - .unwrap_or("") - .to_string(), - ) - } - _ => (ty.span, rustc_hir_pretty::ty_to_string(&tcx, ty)), - } -} diff --git a/compiler/rustc_lint/src/nonstandard_style.rs b/compiler/rustc_lint/src/nonstandard_style.rs index ce4ee45c485ed..83a8ca4307e03 100644 --- a/compiler/rustc_lint/src/nonstandard_style.rs +++ b/compiler/rustc_lint/src/nonstandard_style.rs @@ -5,7 +5,7 @@ use rustc_middle::ty; 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 @@ impl NonCamelCaseTypes { } else { NonCamelCaseTypeSub::Label { span: ident.span } }; - cx.emit_span_lint( - NON_CAMEL_CASE_TYPES, - ident.span, - NonCamelCaseType { sort, name, sub }, - ); + cx.emit_span_lint(NON_CAMEL_CASE_TYPES, ident.span, NonCamelCaseType { + sort, + name, + sub, + }); } } } @@ -489,11 +489,11 @@ impl NonUpperCaseGlobals { } else { NonUpperCaseGlobalSub::Label { span: ident.span } }; - cx.emit_span_lint( - NON_UPPER_CASE_GLOBALS, - ident.span, - NonUpperCaseGlobal { sort, name, sub }, - ); + cx.emit_span_lint(NON_UPPER_CASE_GLOBALS, ident.span, NonUpperCaseGlobal { + sort, + name, + sub, + }); } } } diff --git a/compiler/rustc_lint/src/noop_method_call.rs b/compiler/rustc_lint/src/noop_method_call.rs index d08a959f6547b..4890a93fa76a9 100644 --- a/compiler/rustc_lint/src/noop_method_call.rs +++ b/compiler/rustc_lint/src/noop_method_call.rs @@ -128,17 +128,13 @@ impl<'tcx> LateLintPass<'tcx> for NoopMethodCall { ty::Adt(def, _) => Some(cx.tcx.def_span(def.did()).shrink_to_lo()), _ => None, }; - cx.emit_span_lint( - NOOP_METHOD_CALL, - span, - NoopMethodCallDiag { - method: call.ident.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 c9ca1ea5e7a79..83652bbf54631 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::fold::BottomUpFolder; 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 23b200998a537..ec306f5f83472 100644 --- a/compiler/rustc_lint/src/pass_by_value.rs +++ b/compiler/rustc_lint/src/pass_by_value.rs @@ -31,11 +31,10 @@ impl<'tcx> LateLintPass<'tcx> for PassByValue { } } if let Some(t) = path_for_pass_by_value(cx, inner_ty) { - cx.emit_span_lint( - PASS_BY_VALUE, - ty.span, - PassByValueDiag { ty: t, suggestion: ty.span }, - ); + cx.emit_span_lint(PASS_BY_VALUE, ty.span, PassByValueDiag { + ty: t, + suggestion: ty.span, + }); } } _ => {} diff --git a/compiler/rustc_lint/src/passes.rs b/compiler/rustc_lint/src/passes.rs index bf16e3b7d150f..a1d436e0d3dbf 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 b43e4938b736c..036bfd06856f6 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 bb122509d0a89..a73904cd7769b 100644 --- a/compiler/rustc_lint/src/shadowed_into_iter.rs +++ b/compiler/rustc_lint/src/shadowed_into_iter.rs @@ -146,10 +146,11 @@ impl<'tcx> LateLintPass<'tcx> for ShadowedIntoIter { None }; - cx.emit_span_lint( - lint, - call.ident.span, - ShadowedIntoIterDiag { target, edition, suggestion: call.ident.span, sub }, - ); + cx.emit_span_lint(lint, call.ident.span, ShadowedIntoIterDiag { + target, + edition, + suggestion: call.ident.span, + sub, + }); } } diff --git a/compiler/rustc_lint/src/static_mut_refs.rs b/compiler/rustc_lint/src/static_mut_refs.rs index 3dd26fb9c532a..5d78b41944fef 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_hir::{Expr, Stmt}; 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 91f3e2e3bb6a6..44a36142ed480 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_macros::LintDiagnostic; 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 988d1645fba22..7fbf381a8d321 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 a0fe4b5af7402..c0a01b0065ef9 100644 --- a/compiler/rustc_lint/src/traits.rs +++ b/compiler/rustc_lint/src/traits.rs @@ -101,11 +101,11 @@ impl<'tcx> LateLintPass<'tcx> for DropTraitConstraints { continue; } let Some(def_id) = cx.tcx.get_diagnostic_item(sym::needs_drop) else { return }; - cx.emit_span_lint( - DROP_BOUNDS, - span, - DropTraitConstraintsDiag { predicate, tcx: cx.tcx, def_id }, - ); + cx.emit_span_lint(DROP_BOUNDS, span, DropTraitConstraintsDiag { + predicate, + tcx: cx.tcx, + def_id, + }); } } } diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 3d042f217452f..15fe18adbfb10 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -12,7 +12,7 @@ use rustc_middle::ty::{ 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 @@ use crate::lints::{ 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 @@ impl<'tcx> LateLintPass<'tcx> for TypeLimits { } fn rev_binop(binop: hir::BinOp) -> hir::BinOp { - source_map::respan( - binop.span, - match binop.node { - hir::BinOpKind::Lt => hir::BinOpKind::Gt, - hir::BinOpKind::Le => hir::BinOpKind::Ge, - hir::BinOpKind::Gt => hir::BinOpKind::Lt, - hir::BinOpKind::Ge => hir::BinOpKind::Le, - _ => return binop, - }, - ) + source_map::respan(binop.span, match binop.node { + hir::BinOpKind::Lt => hir::BinOpKind::Gt, + hir::BinOpKind::Le => hir::BinOpKind::Ge, + hir::BinOpKind::Gt => hir::BinOpKind::Lt, + hir::BinOpKind::Ge => hir::BinOpKind::Le, + _ => return binop, + }) } fn check_limits( @@ -595,8 +592,6 @@ struct CTypesVisitorState<'tcx> { /// The original type being checked, before we recursed /// to any other types it contains. base_ty: Ty<'tcx>, - /// Number of times we recursed while checking the type - recursion_depth: usize, } enum FfiResult<'tcx> { @@ -902,23 +897,12 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { // Protect against infinite recursion, for example // `struct S(*mut S);`. + // FIXME: A recursion limit is necessary as well, for irregular + // recursive types. if !acc.cache.insert(ty) { return FfiSafe; } - // Additional recursion check for more complex types like - // `struct A { v: *const A>, ... }` for which the - // cache check above won't be enough (fixes #130310) - if !tcx.recursion_limit().value_within_limit(acc.recursion_depth) { - return FfiUnsafe { - ty: acc.base_ty, - reason: fluent::lint_improper_ctypes_recursion_limit_reached, - help: None, - }; - } - - acc.recursion_depth += 1; - match *ty.kind() { ty::Adt(def, args) => { if let Some(boxed) = ty.boxed_ty() @@ -1193,11 +1177,14 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { } else { None }; - self.cx.emit_span_lint( - lint, - sp, - ImproperCTypes { ty, desc, label: sp, help, note, span_note }, - ); + self.cx.emit_span_lint(lint, sp, ImproperCTypes { + ty, + desc, + label: sp, + help, + note, + span_note, + }); } fn check_for_opaque_ty(&mut self, sp: Span, ty: Ty<'tcx>) -> bool { @@ -1261,8 +1248,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { return; } - let mut acc = - CTypesVisitorState { cache: FxHashSet::default(), base_ty: ty, recursion_depth: 0 }; + let mut acc = CTypesVisitorState { cache: FxHashSet::default(), base_ty: ty }; match self.check_type_for_ffi(&mut acc, ty) { FfiResult::FfiSafe => {} FfiResult::FfiPhantom(ty) => { @@ -1666,11 +1652,11 @@ impl InvalidAtomicOrdering { } fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { - let Some((method, args)) = Self::inherent_atomic_method_call( - cx, - expr, - &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak], - ) else { + let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[ + sym::fetch_update, + sym::compare_exchange, + sym::compare_exchange_weak, + ]) else { return; }; diff --git a/compiler/rustc_lint/src/types/literal.rs b/compiler/rustc_lint/src/types/literal.rs index 67404be24b52e..d1e850990dc3e 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 ed015908ae54a..3c2c5f8fae095 100644 --- a/compiler/rustc_lint/src/unit_bindings.rs +++ b/compiler/rustc_lint/src/unit_bindings.rs @@ -63,11 +63,9 @@ impl<'tcx> LateLintPass<'tcx> for UnitBindings { && !matches!(init.kind, hir::ExprKind::Tup([])) && !matches!(local.pat.kind, hir::PatKind::Tuple([], ..)) { - cx.emit_span_lint( - UNIT_BINDINGS, - local.span, - UnitBindingsDiag { label: local.pat.span }, - ); + cx.emit_span_lint(UNIT_BINDINGS, local.span, UnitBindingsDiag { + label: local.pat.span, + }); } } } diff --git a/compiler/rustc_lint/src/unqualified_local_imports.rs b/compiler/rustc_lint/src/unqualified_local_imports.rs new file mode 100644 index 0000000000000..bea01a33bd6ce --- /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 b7f7b782c7722..12d5b5cf97938 100644 --- a/compiler/rustc_lint/src/unused.rs +++ b/compiler/rustc_lint/src/unused.rs @@ -4,14 +4,14 @@ use std::ops::ControlFlow; 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 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { let mut op_warned = false; if let Some(must_use_op) = must_use_op { - cx.emit_span_lint( - UNUSED_MUST_USE, - expr.span, - UnusedOp { - op: must_use_op, - label: expr.span, - suggestion: if expr_is_from_block { - UnusedOpSuggestion::BlockTailExpr { - before_span: expr.span.shrink_to_lo(), - after_span: expr.span.shrink_to_hi(), - } - } else { - UnusedOpSuggestion::NormalExpr { span: expr.span.shrink_to_lo() } - }, + cx.emit_span_lint(UNUSED_MUST_USE, expr.span, UnusedOp { + op: must_use_op, + label: expr.span, + suggestion: if expr_is_from_block { + UnusedOpSuggestion::BlockTailExpr { + before_span: expr.span.shrink_to_lo(), + after_span: expr.span.shrink_to_hi(), + } + } else { + UnusedOpSuggestion::NormalExpr { span: expr.span.shrink_to_lo() } }, - ); + }); op_warned = true; } @@ -497,39 +493,35 @@ impl<'tcx> LateLintPass<'tcx> for UnusedResults { ); } MustUsePath::Closure(span) => { - cx.emit_span_lint( - UNUSED_MUST_USE, - *span, - UnusedClosure { count: plural_len, pre: descr_pre, post: descr_post }, - ); + cx.emit_span_lint(UNUSED_MUST_USE, *span, UnusedClosure { + count: plural_len, + pre: descr_pre, + post: descr_post, + }); } MustUsePath::Coroutine(span) => { - cx.emit_span_lint( - UNUSED_MUST_USE, - *span, - UnusedCoroutine { count: plural_len, pre: descr_pre, post: descr_post }, - ); + cx.emit_span_lint(UNUSED_MUST_USE, *span, UnusedCoroutine { + count: plural_len, + pre: descr_pre, + post: descr_post, + }); } MustUsePath::Def(span, def_id, reason) => { - cx.emit_span_lint( - UNUSED_MUST_USE, - *span, - UnusedDef { - pre: descr_pre, - post: descr_post, - cx, - def_id: *def_id, - note: *reason, - suggestion: (!is_inner).then_some(if expr_is_from_block { - UnusedDefSuggestion::BlockTailExpr { - before_span: span.shrink_to_lo(), - after_span: span.shrink_to_hi(), - } - } else { - UnusedDefSuggestion::NormalExpr { span: span.shrink_to_lo() } - }), - }, - ); + cx.emit_span_lint(UNUSED_MUST_USE, *span, UnusedDef { + pre: descr_pre, + post: descr_post, + cx, + def_id: *def_id, + note: *reason, + suggestion: (!is_inner).then_some(if expr_is_from_block { + UnusedDefSuggestion::BlockTailExpr { + before_span: span.shrink_to_lo(), + after_span: span.shrink_to_hi(), + } + } else { + UnusedDefSuggestion::NormalExpr { span: span.shrink_to_lo() } + }), + }); } } } @@ -791,7 +783,7 @@ trait UnusedDelimLint { // ``` // 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 @@ trait UnusedDelimLint { end_replace: hi_replace, } }); - cx.emit_span_lint( - self.lint(), - primary_span, - UnusedDelim { delim: Self::DELIM_STR, item: msg, suggestion }, - ); + cx.emit_span_lint(self.lint(), primary_span, UnusedDelim { + delim: Self::DELIM_STR, + item: msg, + suggestion, + }); } fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { @@ -1558,11 +1550,9 @@ impl UnusedImportBraces { ast::UseTreeKind::Nested { .. } => return, }; - cx.emit_span_lint( - UNUSED_IMPORT_BRACES, - item.span, - UnusedImportBracesDiag { node: node_name }, - ); + cx.emit_span_lint(UNUSED_IMPORT_BRACES, item.span, UnusedImportBracesDiag { + node: node_name, + }); } } } diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index acdedb0614122..549dc64a562b2 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 f5ed69658ce5f..734e7069c9026 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -14,7 +14,7 @@ use rustc_hir::{HashStableContext, HirId, MissingLifetimeKind}; 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 9f3e00801101d..165fb7aa6c3d3 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 b6d870768a862..a3890fc937e79 100644 --- a/compiler/rustc_log/src/lib.rs +++ b/compiler/rustc_log/src/lib.rs @@ -44,8 +44,8 @@ use std::io::{self, IsTerminal}; 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 52d892a20f4d3..185d070496694 100644 --- a/compiler/rustc_macros/src/diagnostics/diagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/diagnostic.rs @@ -8,7 +8,7 @@ use syn::spanned::Spanned; 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 5c2a429a1ebbe..72f1e5992472d 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 5d5d279eaf0a5..909083d5e8652 100644 --- a/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs +++ b/compiler/rustc_macros/src/diagnostics/subdiagnostic.rs @@ -8,13 +8,13 @@ use synstructure::{BindingInfo, Structure, VariantInfo}; 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 0d3b2f52fa2af..5946b11828ea0 100644 --- a/compiler/rustc_macros/src/diagnostics/utils.rs +++ b/compiler/rustc_macros/src/diagnostics/utils.rs @@ -5,16 +5,16 @@ use std::str::FromStr; 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 bbaa477237b16..781a06f32eba8 100644 --- a/compiler/rustc_macros/src/extension.rs +++ b/compiler/rustc_macros/src/extension.rs @@ -4,9 +4,9 @@ use syn::parse::{Parse, ParseStream}; 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 bf4a7665ceb88..341447f7e6f26 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 886a38c8ff252..88ea6e07d6eb6 100644 --- a/compiler/rustc_macros/src/query.rs +++ b/compiler/rustc_macros/src/query.rs @@ -4,8 +4,8 @@ use syn::parse::{Parse, ParseStream, Result}; 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 2c33a0ac0aafe..ce692abfb9834 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 341186ac1ca3a..2552c0a0cfc79 100644 --- a/compiler/rustc_macros/src/symbols.rs +++ b/compiler/rustc_macros/src/symbols.rs @@ -30,7 +30,7 @@ use proc_macro2::{Span, TokenStream}; 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 9c53453df5b54..b32ce60e204ab 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 8ddfa96e0952f..bc3b82c2893fa 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 14a1a7f67e56e..8adec7554a834 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -8,7 +8,7 @@ use std::time::Duration; 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_data_structures::sync::{self, FreezeReadGuard, FreezeWriteGuard}; 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::lint::{self, BuiltinLintDiag}; 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 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { let cnum = self.resolve_crate(name, item.span, dep_kind)?; let path_len = definitions.def_path(def_id).data.len(); - self.cstore.update_extern_crate( - cnum, - ExternCrate { - src: ExternCrateSource::Extern(def_id.to_def_id()), - span: item.span, - path_len, - dependency_of: LOCAL_CRATE, - }, - ); + self.cstore.update_extern_crate(cnum, ExternCrate { + src: ExternCrateSource::Extern(def_id.to_def_id()), + span: item.span, + path_len, + dependency_of: LOCAL_CRATE, + }); Some(cnum) } _ => bug!(), @@ -1081,16 +1078,13 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { pub fn process_path_extern(&mut self, name: Symbol, span: Span) -> Option { let cnum = self.resolve_crate(name, span, CrateDepKind::Explicit)?; - self.cstore.update_extern_crate( - cnum, - ExternCrate { - src: ExternCrateSource::Path, - span, - // to have the least priority in `update_extern_crate` - path_len: usize::MAX, - dependency_of: LOCAL_CRATE, - }, - ); + self.cstore.update_extern_crate(cnum, ExternCrate { + src: ExternCrateSource::Path, + span, + // to have the least priority in `update_extern_crate` + path_len: usize::MAX, + dependency_of: LOCAL_CRATE, + }); Some(cnum) } diff --git a/compiler/rustc_metadata/src/errors.rs b/compiler/rustc_metadata/src/errors.rs index 42dec978b78cd..6587125ec677f 100644 --- a/compiler/rustc_metadata/src/errors.rs +++ b/compiler/rustc_metadata/src/errors.rs @@ -4,7 +4,7 @@ use std::path::{Path, PathBuf}; 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 b2a979ed6d832..a58f3c6b5caad 100644 --- a/compiler/rustc_metadata/src/fs.rs +++ b/compiler/rustc_metadata/src/fs.rs @@ -12,7 +12,7 @@ use crate::errors::{ 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 02a9ce455b280..1759ea7d44154 100644 --- a/compiler/rustc_metadata/src/lib.rs +++ b/compiler/rustc_metadata/src/lib.rs @@ -34,12 +34,12 @@ pub mod errors; 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 90228db378a95..089ac060ba848 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -224,20 +224,20 @@ use rustc_data_structures::owned_slice::slice_owned; 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 0329a193d89dd..82b907d2501fe 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::cstore::{ 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 f3ae24a5895a8..4425c93211a01 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -22,16 +22,16 @@ use rustc_hir::diagnostic_items::DiagnosticItems; 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 b9d287730fa6e..69707fdbe8fa1 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::ty::{self, TyCtxt}; 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> { @@ -347,7 +347,7 @@ provide! { tcx, def_id, other, cdata, tcx.arena.alloc_from_iter(cdata.get_associated_item_or_field_def_ids(def_id.index)) } associated_item => { cdata.get_associated_item(def_id.index, tcx.sess) } - inherent_impls => { Ok(cdata.get_inherent_implementations_for_type(tcx, def_id.index)) } + inherent_impls => { cdata.get_inherent_implementations_for_type(tcx, def_id.index) } item_attrs => { tcx.arena.alloc_from_iter(cdata.get_item_attrs(def_id.index, tcx.sess)) } is_mir_available => { cdata.is_item_mir_available(def_id.index) } is_ctfe_mir_available => { cdata.is_ctfe_mir_available(def_id.index) } @@ -393,7 +393,7 @@ provide! { tcx, def_id, other, cdata, traits => { tcx.arena.alloc_from_iter(cdata.get_traits()) } trait_impls_in_crate => { tcx.arena.alloc_from_iter(cdata.get_trait_impls()) } implementations_of_trait => { cdata.get_implementations_of_trait(tcx, other) } - crate_incoherent_impls => { Ok(cdata.get_incoherent_impls(tcx, other)) } + crate_incoherent_impls => { cdata.get_incoherent_impls(tcx, other) } dep_kind => { cdata.dep_kind } module_children => { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 46dc0696638cc..5f756672b049e 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -7,11 +7,11 @@ use std::path::{Path, PathBuf}; 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::fast_reject::{self, TreatParams}; 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; @@ -1540,7 +1540,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { } } - for (def_id, impls) in &tcx.crate_inherent_impls(()).unwrap().inherent_impls { + for (def_id, impls) in &tcx.crate_inherent_impls(()).0.inherent_impls { record_defaulted_array!(self.tables.inherent_impls[def_id.to_def_id()] <- impls.iter().map(|def_id| { assert!(def_id.is_local()); def_id.index @@ -2089,7 +2089,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { let all_impls: Vec<_> = tcx .crate_inherent_impls(()) - .unwrap() + .0 .incoherent_impls .iter() .map(|(&simp, impls)| IncoherentImpls { diff --git a/compiler/rustc_metadata/src/rmeta/mod.rs b/compiler/rustc_metadata/src/rmeta/mod.rs index c791a1f541c52..79bd1c13b1216 100644 --- a/compiler/rustc_metadata/src/rmeta/mod.rs +++ b/compiler/rustc_metadata/src/rmeta/mod.rs @@ -5,7 +5,7 @@ pub(crate) use decoder::{CrateMetadata, CrateNumMap, MetadataBlob}; 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::{CtorKind, DefKind, DocLinkResMap}; 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 2d47d1d19afb9..87bbeb178ee19 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 b24954584fe26..2090c3e6da6fa 100644 --- a/compiler/rustc_middle/src/dep_graph/mod.rs +++ b/compiler/rustc_middle/src/dep_graph/mod.rs @@ -7,12 +7,12 @@ use crate::ty::{self, TyCtxt}; #[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 8b0a855612c19..e11361a615f4c 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}; @@ -598,7 +598,10 @@ impl<'hir> Map<'hir> { /// in the HIR which is recorded by the map and is an item, either an item /// in a module, trait, or impl. pub fn get_parent_item(self, hir_id: HirId) -> OwnerId { - if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() { + if hir_id.local_id != ItemLocalId::ZERO { + // If this is a child of a HIR owner, return the owner. + hir_id.owner + } else if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() { def_id } else { CRATE_OWNER_ID diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index 596d9f077372e..7a07ef80dedb4 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -9,7 +9,7 @@ pub mod place; 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 bde05210d9fc5..742797fdeef14 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 3fd4aba31696e..cf692b145b8dc 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::cmp; 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 70da66af64be8..b5862565e8e87 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -5,11 +5,11 @@ use rustc_data_structures::sorted_map::SortedMap; 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 f141af4490057..b20673fe8daf5 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 70810f51a1f34..270bcabcc86a2 100644 --- a/compiler/rustc_middle/src/middle/limits.rs +++ b/compiler/rustc_middle/src/middle/limits.rs @@ -12,7 +12,7 @@ use std::num::IntErrorKind; 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 0c4f37ab14f79..83873439bd927 100644 --- a/compiler/rustc_middle/src/middle/mod.rs +++ b/compiler/rustc_middle/src/middle/mod.rs @@ -6,8 +6,8 @@ pub mod lang_items; 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 db70f53b7b498..03549091d62d3 100644 --- a/compiler/rustc_middle/src/middle/privacy.rs +++ b/compiler/rustc_middle/src/middle/privacy.rs @@ -9,7 +9,7 @@ use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; 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 999743ed73b84..4e44de33611b9 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -14,7 +14,7 @@ use rustc_data_structures::unord::UnordMap; 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 86dca27f04f7e..54cfd99583215 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -15,12 +15,12 @@ use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdMap}; 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 63ce47ef32727..4602c918160b7 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 rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; 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 c6105d1f383b1..89d4c46016006 100644 --- a/compiler/rustc_middle/src/mir/consts.rs +++ b/compiler/rustc_middle/src/mir/consts.rs @@ -2,13 +2,13 @@ use std::fmt::{self, Debug, Display, Formatter}; 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 4c5da188860c6..b8ecfa3c3f946 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_macros::{HashStable, TyDecodable, TyEncodable}; 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 4fe219441a064..b3940530f69cc 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_serialize::{Decodable, Decoder, Encodable, Encoder}; 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 8c89c15f9611d..46646e759d59e 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_errors::{DiagArgName, DiagArgValue, DiagMessage, ErrorGuaranteed, Into 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 { @@ -365,8 +365,10 @@ pub enum UndefinedBehaviorInfo<'tcx> { InvalidVTablePointer(Pointer), /// Using a vtable for the wrong trait. InvalidVTableTrait { - expected_trait: &'tcx ty::List>, - vtable_trait: Option>, + /// The vtable that was actually referenced by the wide pointer metadata. + vtable_dyn_type: &'tcx ty::List>, + /// The vtable that was expected at the point in MIR that it was accessed. + expected_dyn_type: &'tcx ty::List>, }, /// Using a string that is not valid UTF-8, InvalidStr(std::str::Utf8Error), @@ -479,8 +481,10 @@ pub enum ValidationErrorKind<'tcx> { value: String, }, InvalidMetaWrongTrait { - expected_trait: &'tcx ty::List>, - vtable_trait: Option>, + /// The vtable that was actually referenced by the wide pointer metadata. + vtable_dyn_type: &'tcx ty::List>, + /// The vtable that was expected at the point in MIR that it was accessed. + expected_dyn_type: &'tcx ty::List>, }, InvalidMetaSliceTooLarge { ptr_kind: PointerKind, diff --git a/compiler/rustc_middle/src/mir/interpret/mod.rs b/compiler/rustc_middle/src/mir/interpret/mod.rs index 91e71c12cae45..d7809cc4343d2 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 { }; 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, @@ -232,9 +232,8 @@ impl<'s> AllocDecodingSession<'s> { } AllocDiscriminant::VTable => { trace!("creating vtable alloc ID"); - let ty = as Decodable>::decode(decoder); - let poly_trait_ref = - > as Decodable>::decode(decoder); + let ty = Decodable::decode(decoder); + let poly_trait_ref = Decodable::decode(decoder); trace!("decoded vtable alloc instance: {ty:?}, {poly_trait_ref:?}"); decoder.interner().reserve_and_set_vtable_alloc(ty, poly_trait_ref, CTFE_ALLOC_SALT) } @@ -259,7 +258,10 @@ pub enum GlobalAlloc<'tcx> { /// The alloc ID is used as a function pointer. Function { instance: Instance<'tcx> }, /// This alloc ID points to a symbolic (not-reified) vtable. - VTable(Ty<'tcx>, Option>), + /// We remember the full dyn type, not just the principal trait, so that + /// const-eval and Miri can detect UB due to invalid transmutes of + /// `dyn Trait` types. + VTable(Ty<'tcx>, &'tcx ty::List>), /// The alloc ID points to a "lazy" static variable that did not get computed (yet). /// This is also used to break the cycle in recursive statics. Static(DefId), @@ -293,7 +295,7 @@ impl<'tcx> GlobalAlloc<'tcx> { #[inline] pub fn unwrap_vtable(&self) -> (Ty<'tcx>, Option>) { match *self { - GlobalAlloc::VTable(ty, poly_trait_ref) => (ty, poly_trait_ref), + GlobalAlloc::VTable(ty, dyn_ty) => (ty, dyn_ty.principal()), _ => bug!("expected vtable, got {:?}", self), } } @@ -398,10 +400,10 @@ impl<'tcx> TyCtxt<'tcx> { pub fn reserve_and_set_vtable_alloc( self, ty: Ty<'tcx>, - poly_trait_ref: Option>, + dyn_ty: &'tcx ty::List>, salt: usize, ) -> AllocId { - self.reserve_and_set_dedup(GlobalAlloc::VTable(ty, poly_trait_ref), salt) + self.reserve_and_set_dedup(GlobalAlloc::VTable(ty, dyn_ty), salt) } /// Interns the `Allocation` and return a new `AllocId`, even if there's already an identical diff --git a/compiler/rustc_middle/src/mir/interpret/queries.rs b/compiler/rustc_middle/src/mir/interpret/queries.rs index 675e78603aebd..59bc55269a30a 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 989f03d3d1399..c6c2ab414ed41 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 54dcfaf5d5429..cd148aef29ba8 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::fx::{FxHashMap, FxHashSet}; 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_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisit 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::interpret::{AllocRange, Scalar}; 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 terminator::*; 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 @@ impl<'tcx> BasicBlockData<'tcx> { // existing elements from before the gap to the end of the gap. // For now, this is safe code, emulating a gap but initializing it. let mut gap = self.statements.len()..self.statements.len() + extra_stmts; - self.statements.resize( - gap.end, - Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop }, - ); + self.statements.resize(gap.end, Statement { + source_info: SourceInfo::outermost(DUMMY_SP), + kind: StatementKind::Nop, + }); for (splice_start, new_stmts) in splices.into_iter().rev() { let splice_end = splice_start + new_stmts.size_hint().0; while gap.end > splice_end { diff --git a/compiler/rustc_middle/src/mir/mono.rs b/compiler/rustc_middle/src/mir/mono.rs index 69b5e0a79c7fa..954f746ce5b61 100644 --- a/compiler/rustc_middle/src/mir/mono.rs +++ b/compiler/rustc_middle/src/mir/mono.rs @@ -2,19 +2,19 @@ use std::fmt; 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 d66d0be10095f..119aed1106dde 100644 --- a/compiler/rustc_middle/src/mir/pretty.rs +++ b/compiler/rustc_middle/src/mir/pretty.rs @@ -6,8 +6,8 @@ use std::path::{Path, PathBuf}; 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::*; @@ -1536,11 +1536,8 @@ pub fn write_allocations<'tcx>( // gracefully handle it and allow buggy rustc to be debugged via allocation printing. None => write!(w, " (deallocated)")?, Some(GlobalAlloc::Function { instance, .. }) => write!(w, " (fn: {instance})")?, - Some(GlobalAlloc::VTable(ty, Some(trait_ref))) => { - write!(w, " (vtable: impl {trait_ref} for {ty})")? - } - Some(GlobalAlloc::VTable(ty, None)) => { - write!(w, " (vtable: impl for {ty})")? + Some(GlobalAlloc::VTable(ty, dyn_ty)) => { + write!(w, " (vtable: impl {dyn_ty} for {ty})")? } Some(GlobalAlloc::Static(did)) if !tcx.is_foreign_item(did) => { match tcx.eval_static_initializer(did) { diff --git a/compiler/rustc_middle/src/mir/query.rs b/compiler/rustc_middle/src/mir/query.rs index a36e49f6ee0fb..70331214ac5a8 100644 --- a/compiler/rustc_middle/src/mir/query.rs +++ b/compiler/rustc_middle/src/mir/query.rs @@ -10,8 +10,8 @@ use rustc_hir::def_id::LocalDefId; 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; @@ -234,7 +234,9 @@ pub enum ConstraintCategory<'tcx> { UseAsStatic, TypeAnnotation, Cast { - /// Whether this is an unsizing cast and if yes, this contains the target type. + /// Whether this cast is a coercion that was automatically inserted by the compiler. + is_implicit_coercion: bool, + /// Whether this is an unsizing coercion and if yes, this contains the target type. /// Region variables are erased to ReErased. #[derive_where(skip)] unsize_to: Option>, diff --git a/compiler/rustc_middle/src/mir/statement.rs b/compiler/rustc_middle/src/mir/statement.rs index bc7dfa6205e71..88ed90c311463 100644 --- a/compiler/rustc_middle/src/mir/statement.rs +++ b/compiler/rustc_middle/src/mir/statement.rs @@ -432,9 +432,8 @@ impl<'tcx> Rvalue<'tcx> { | CastKind::IntToFloat | CastKind::FnPtrToPtr | CastKind::PtrToPtr - | CastKind::PointerCoercion(_) + | CastKind::PointerCoercion(_, _) | CastKind::PointerWithExposedProvenance - | CastKind::DynStar | CastKind::Transmute, _, _, diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index f5590aa27625d..ae75f2d4187ba 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; @@ -579,7 +579,8 @@ pub struct CopyNonOverlapping<'tcx> { pub count: Operand<'tcx>, } -/// Represents how a `TerminatorKind::Call` was constructed, used for diagnostics +/// Represents how a [`TerminatorKind::Call`] was constructed. +/// Used only for diagnostics. #[derive(Clone, Copy, TyEncodable, TyDecodable, Debug, PartialEq, Hash, HashStable)] #[derive(TypeFoldable, TypeVisitable)] pub enum CallSource { @@ -1403,9 +1404,7 @@ pub enum CastKind { /// * [`PointerCoercion::MutToConstPointer`] /// /// Both are runtime nops, so should be [`CastKind::PtrToPtr`] instead in runtime MIR. - PointerCoercion(PointerCoercion), - /// Cast into a dyn* object. - DynStar, + PointerCoercion(PointerCoercion, CoercionSource), IntToInt, FloatToInt, FloatToFloat, @@ -1421,6 +1420,16 @@ pub enum CastKind { Transmute, } +/// Represents how a [`CastKind::PointerCoercion`] was constructed. +/// Used only for diagnostics. +#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] +pub enum CoercionSource { + /// The coercion was manually written by the user with an `as` cast. + AsCast, + /// The coercion was automatically inserted by the compiler. + Implicit, +} + #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] #[derive(TypeFoldable, TypeVisitable)] pub enum AggregateKind<'tcx> { diff --git a/compiler/rustc_middle/src/mir/terminator.rs b/compiler/rustc_middle/src/mir/terminator.rs index c34e22eb87311..783952fb9cb8a 100644 --- a/compiler/rustc_middle/src/mir/terminator.rs +++ b/compiler/rustc_middle/src/mir/terminator.rs @@ -5,7 +5,7 @@ use std::slice; 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/erase.rs b/compiler/rustc_middle/src/query/erase.rs index bd20e6aa00537..48bf4ffced0ce 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -1,6 +1,8 @@ use std::intrinsics::transmute_unchecked; use std::mem::MaybeUninit; +use rustc_span::ErrorGuaranteed; + use crate::query::CyclePlaceholder; use crate::ty::adjustment::CoerceUnsizedInfo; use crate::ty::{self, Ty}; @@ -216,6 +218,10 @@ impl EraseType for (&'_ T0, &'_ [T1]) { type Result = [u8; size_of::<(&'static (), &'static [()])>()]; } +impl EraseType for (&'_ T0, Result<(), ErrorGuaranteed>) { + type Result = [u8; size_of::<(&'static (), Result<(), ErrorGuaranteed>)>()]; +} + macro_rules! trivial { ($($ty:ty),+ $(,)?) => { $( diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index 6562d46d7b866..80adbe74fe702 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 969374cb0e540..9609ef46d5c31 100644 --- a/compiler/rustc_middle/src/query/mod.rs +++ b/compiler/rustc_middle/src/query/mod.rs @@ -12,8 +12,8 @@ use std::path::PathBuf; 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_hir::{Crate, ItemLocalId, ItemLocalMap, TraitCandidate}; 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 @@ use crate::mir::interpret::{ 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 @@ use crate::traits::query::{ 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, @@ -881,13 +881,13 @@ rustc_queries! { /// Maps a `DefId` of a type to a list of its inherent impls. /// Contains implementations of methods that are inherent to a type. /// Methods in these implementations don't need to be exported. - query inherent_impls(key: DefId) -> Result<&'tcx [DefId], ErrorGuaranteed> { + query inherent_impls(key: DefId) -> &'tcx [DefId] { desc { |tcx| "collecting inherent impls for `{}`", tcx.def_path_str(key) } cache_on_disk_if { key.is_local() } separate_provide_extern } - query incoherent_impls(key: SimplifiedType) -> Result<&'tcx [DefId], ErrorGuaranteed> { + query incoherent_impls(key: SimplifiedType) -> &'tcx [DefId] { desc { |tcx| "collecting all inherent impls for `{:?}`", key } } @@ -1017,8 +1017,14 @@ rustc_queries! { /// Gets a complete map from all types to their inherent impls. /// Not meant to be used directly outside of coherence. - query crate_inherent_impls(k: ()) -> Result<&'tcx CrateInherentImpls, ErrorGuaranteed> { + query crate_inherent_impls(k: ()) -> (&'tcx CrateInherentImpls, Result<(), ErrorGuaranteed>) { desc { "finding all inherent impls defined in crate" } + } + + /// Checks all types in the crate for overlap in their inherent impls. Reports errors. + /// Not meant to be used directly outside of coherence. + query crate_inherent_impls_validity_check(_: ()) -> Result<(), ErrorGuaranteed> { + desc { "check for inherent impls that should not be defined in crate" } ensure_forwards_result_if_red } @@ -1715,7 +1721,7 @@ rustc_queries! { /// /// Do not call this directly, but instead use the `incoherent_impls` query. /// This query is only used to get the data necessary for that query. - query crate_incoherent_impls(key: (CrateNum, SimplifiedType)) -> Result<&'tcx [DefId], ErrorGuaranteed> { + query crate_incoherent_impls(key: (CrateNum, SimplifiedType)) -> &'tcx [DefId] { desc { |tcx| "collecting all impls for a type in a crate" } separate_provide_extern } diff --git a/compiler/rustc_middle/src/query/on_disk_cache.rs b/compiler/rustc_middle/src/query/on_disk_cache.rs index ca52358218e92..06c9ebc87b5ab 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::memmap::Mmap; 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 @@ impl<'sess> OnDiskCache<'sess> { // 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 0320a91d142b7..564d274bc8b1e 100644 --- a/compiler/rustc_middle/src/query/plumbing.rs +++ b/compiler/rustc_middle/src/query/plumbing.rs @@ -5,11 +5,11 @@ use rustc_data_structures::sync::{AtomicU64, WorkerLocal}; 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 aca1390935ef1..e614d41899a0e 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -16,7 +16,7 @@ use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece}; 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; @@ -338,6 +338,8 @@ pub enum ExprKind<'tcx> { PointerCoercion { cast: PointerCoercion, source: ExprId, + /// Whether this coercion is written with an `as` cast in the source code. + is_from_as_cast: bool, }, /// A `loop` expression. Loop { @@ -453,12 +455,14 @@ pub enum ExprKind<'tcx> { source: ExprId, /// Type that the user gave to this expression user_ty: UserTy<'tcx>, + user_ty_span: Span, }, - /// A type ascription on a value, e.g. `42: i32`. + /// A type ascription on a value, e.g. `type_ascribe!(42, i32)` or `42 as i32`. ValueTypeAscription { source: ExprId, /// Type that the user gave to this expression user_ty: UserTy<'tcx>, + user_ty_span: Span, }, /// A closure definition. Closure(Box>), diff --git a/compiler/rustc_middle/src/thir/visit.rs b/compiler/rustc_middle/src/thir/visit.rs index e246ecebbec0b..58e2ebaeaf8df 100644 --- a/compiler/rustc_middle/src/thir/visit.rs +++ b/compiler/rustc_middle/src/thir/visit.rs @@ -68,7 +68,9 @@ pub fn walk_expr<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( Cast { source } => visitor.visit_expr(&visitor.thir()[source]), Use { source } => visitor.visit_expr(&visitor.thir()[source]), NeverToAny { source } => visitor.visit_expr(&visitor.thir()[source]), - PointerCoercion { source, cast: _ } => visitor.visit_expr(&visitor.thir()[source]), + PointerCoercion { source, cast: _, is_from_as_cast: _ } => { + visitor.visit_expr(&visitor.thir()[source]) + } Let { expr, ref pat } => { visitor.visit_expr(&visitor.thir()[expr]); visitor.visit_pat(pat); @@ -129,7 +131,8 @@ pub fn walk_expr<'thir, 'tcx: 'thir, V: Visitor<'thir, 'tcx>>( visitor.visit_expr(&visitor.thir()[base.base]); } } - PlaceTypeAscription { source, user_ty: _ } | ValueTypeAscription { source, user_ty: _ } => { + PlaceTypeAscription { source, user_ty: _, user_ty_span: _ } + | ValueTypeAscription { source, user_ty: _, user_ty_span: _ } => { visitor.visit_expr(&visitor.thir()[source]) } Closure(box ClosureExpr { diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index a3277fb96d229..c3295a9ce51cc 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -14,17 +14,17 @@ use std::hash::{Hash, Hasher}; 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/adjustment.rs b/compiler/rustc_middle/src/ty/adjustment.rs index 5a32078760e5b..41a20e89cbf78 100644 --- a/compiler/rustc_middle/src/ty/adjustment.rs +++ b/compiler/rustc_middle/src/ty/adjustment.rs @@ -35,6 +35,9 @@ pub enum PointerCoercion { /// type. Codegen backends and miri figure out what has to be done /// based on the precise source/target type at hand. Unsize, + + /// Go from a pointer-like type to a `dyn*` object. + DynStar, } /// Represents coercing a value to a different type of value. @@ -102,9 +105,6 @@ pub enum Adjust<'tcx> { Pointer(PointerCoercion), - /// Cast into a dyn* object. - DynStar, - /// Take a pinned reference and reborrow as a `Pin<&mut T>` or `Pin<&T>`. ReborrowPin(ty::Region<'tcx>, hir::Mutability), } diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index 204f61b4804e4..8f89f5c25afb4 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -17,7 +17,7 @@ use rustc_macros::{HashStable, TyDecodable, TyEncodable}; 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/cast.rs b/compiler/rustc_middle/src/ty/cast.rs index 46f3765953678..b1316ceef5ac7 100644 --- a/compiler/rustc_middle/src/ty/cast.rs +++ b/compiler/rustc_middle/src/ty/cast.rs @@ -34,15 +34,12 @@ pub enum CastTy<'tcx> { FnPtr, /// Raw pointers. Ptr(ty::TypeAndMut<'tcx>), - /// Casting into a `dyn*` value. - DynStar, } /// Cast Kind. See [RFC 401](https://rust-lang.github.io/rfcs/0401-coercions.html) /// (or rustc_hir_analysis/check/cast.rs). #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)] pub enum CastKind { - CoercionCast, PtrPtrCast, PtrAddrCast, AddrPtrCast, @@ -53,7 +50,6 @@ pub enum CastKind { ArrayPtrCast, FnPtrPtrCast, FnPtrAddrCast, - DynStarCast, } impl<'tcx> CastTy<'tcx> { @@ -71,7 +67,6 @@ impl<'tcx> CastTy<'tcx> { ty::Adt(d, _) if d.is_enum() && d.is_payloadfree() => Some(CastTy::Int(IntTy::CEnum)), ty::RawPtr(ty, mutbl) => Some(CastTy::Ptr(ty::TypeAndMut { ty, mutbl })), ty::FnPtr(..) => Some(CastTy::FnPtr), - ty::Dynamic(_, _, ty::DynStar) => Some(CastTy::DynStar), _ => None, } } @@ -86,7 +81,6 @@ pub fn mir_cast_kind<'tcx>(from_ty: Ty<'tcx>, cast_ty: Ty<'tcx>) -> mir::CastKin mir::CastKind::PointerExposeProvenance } (Some(CastTy::Int(_)), Some(CastTy::Ptr(_))) => mir::CastKind::PointerWithExposedProvenance, - (_, Some(CastTy::DynStar)) => mir::CastKind::DynStar, (Some(CastTy::Int(_)), Some(CastTy::Int(_))) => mir::CastKind::IntToInt, (Some(CastTy::FnPtr), Some(CastTy::Ptr(_))) => mir::CastKind::FnPtrToPtr, diff --git a/compiler/rustc_middle/src/ty/closure.rs b/compiler/rustc_middle/src/ty/closure.rs index 809801c33e1ad..9ee8294291123 100644 --- a/compiler/rustc_middle/src/ty/closure.rs +++ b/compiler/rustc_middle/src/ty/closure.rs @@ -3,8 +3,8 @@ use std::fmt::Write; 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 1a584cf289004..73d0acf95f4f5 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -18,7 +18,7 @@ mod valtree; 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 @@ impl<'tcx> Const<'tcx> { 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 0024a2ae756ea..1732374ab8c26 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 c7c2e8afa1e71..91b764ae1d451 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 @@ impl<'tcx> ty::UnevaluatedConst<'tcx> { // 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 cd06d7b8e533e..f017216489d0c 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -30,7 +30,7 @@ use rustc_errors::{ }; 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::config::CrateType; 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 @@ impl<'tcx> CommonLifetimes<'tcx> { .map(|i| { (0..NUM_PREINTERNED_RE_LATE_BOUNDS_V) .map(|v| { - mk(ty::ReBound( - ty::DebruijnIndex::from(i), - ty::BoundRegion { var: ty::BoundVar::from(v), kind: ty::BrAnon }, - )) + mk(ty::ReBound(ty::DebruijnIndex::from(i), ty::BoundRegion { + var: ty::BoundVar::from(v), + kind: ty::BrAnon, + })) }) .collect() }) @@ -3052,15 +3052,12 @@ impl<'tcx> TyCtxt<'tcx> { } let generics = self.generics_of(new_parent); - return ty::Region::new_early_param( - self, - ty::EarlyParamRegion { - index: generics - .param_def_id_to_index(self, ebv.to_def_id()) - .expect("early-bound var should be present in fn generics"), - name: self.item_name(ebv.to_def_id()), - }, - ); + return ty::Region::new_early_param(self, ty::EarlyParamRegion { + index: generics + .param_def_id_to_index(self, ebv.to_def_id()) + .expect("early-bound var should be present in fn generics"), + name: self.item_name(ebv.to_def_id()), + }); } 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 c14dadc68c903..992eb264163ba 100644 --- a/compiler/rustc_middle/src/ty/diagnostics.rs +++ b/compiler/rustc_middle/src/ty/diagnostics.rs @@ -5,7 +5,7 @@ use std::fmt::Write; 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 d974a86a3036f..b02eff3bfd6a3 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -8,7 +8,7 @@ use rustc_hir::def::{CtorOf, DefKind}; 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 7892ef818194a..2ee7497497aa9 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 @@ impl<'tcx> TyCtxt<'tcx> { T: TypeFoldable>, { let shift_bv = |bv: ty::BoundVar| ty::BoundVar::from_usize(bv.as_usize() + bound_vars); - self.replace_escaping_bound_vars_uncached( - value, - FnMutDelegate { - regions: &mut |r: ty::BoundRegion| { - ty::Region::new_bound( - self, - ty::INNERMOST, - ty::BoundRegion { var: shift_bv(r.var), kind: r.kind }, - ) - }, - 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 80c31e236e2c2..daf1362e25c1f 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_ast_ir::walk_visitable_list; 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 5f9a89c3a5bda..660686f4aa280 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -2,8 +2,8 @@ use rustc_ast as ast; 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 072951d131917..bfef4c4c8c6b9 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -12,12 +12,12 @@ use rustc_index::bit_set::FiniteBitSet; 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 41a966da8aa49..ed0fb37d3b897 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 941091b71d38b..cf0c29e0c8c39 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -7,13 +7,13 @@ use rustc_errors::{ 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 @@ pub trait FnAbiOf<'tcx>: FnAbiOfHelpers<'tcx> { // 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 af76d5b7d9267..ec9ca65dbda83 100644 --- a/compiler/rustc_middle/src/ty/list.rs +++ b/compiler/rustc_middle/src/ty/list.rs @@ -4,7 +4,7 @@ use std::hash::{Hash, Hasher}; 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 e637ced7139a6..2b1212a5eb567 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -26,52 +26,55 @@ pub use generics::*; 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 @@ pub use self::typeck_results::{ 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 d3f44326c272d..cf789807bb04a 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 8e72505b86200..534a8c99c5adb 100644 --- a/compiler/rustc_middle/src/ty/predicate.rs +++ b/compiler/rustc_middle/src/ty/predicate.rs @@ -3,7 +3,7 @@ use std::cmp::Ordering; 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 988516d100f72..5b4ee2791f8dd 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::fmt::{self, Write as _}; 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::LangItem; use rustc_hir::def::{self, CtorKind, DefKind, Namespace}; -use rustc_hir::def_id::{DefIdMap, DefIdSet, ModDefId, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefIdMap, DefIdSet, LOCAL_CRATE, ModDefId}; use rustc_hir::definitions::{DefKey, DefPathDataName}; -use rustc_hir::LangItem; -use rustc_macros::{extension, Lift}; -use rustc_session::cstore::{ExternCrate, ExternCrateSource}; +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 44956d5b0a6bd..be4772e888f86 100644 --- a/compiler/rustc_middle/src/ty/region.rs +++ b/compiler/rustc_middle/src/ty/region.rs @@ -4,8 +4,8 @@ use rustc_data_structures::intern::Interned; 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 80b33c2cda929..cd9ff9b60d859 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::print::PrettyPrinter; 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 44309697ba987..db9978a7f5334 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -11,15 +11,15 @@ use hir::def::{CtorKind, DefKind}; 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/trait_def.rs b/compiler/rustc_middle/src/ty/trait_def.rs index 82690f70e5f18..188107e5d5498 100644 --- a/compiler/rustc_middle/src/ty/trait_def.rs +++ b/compiler/rustc_middle/src/ty/trait_def.rs @@ -253,30 +253,16 @@ pub(super) fn trait_impls_of_provider(tcx: TyCtxt<'_>, trait_id: DefId) -> Trait } /// Query provider for `incoherent_impls`. -pub(super) fn incoherent_impls_provider( - tcx: TyCtxt<'_>, - simp: SimplifiedType, -) -> Result<&[DefId], ErrorGuaranteed> { +pub(super) fn incoherent_impls_provider(tcx: TyCtxt<'_>, simp: SimplifiedType) -> &[DefId] { let mut impls = Vec::new(); - - let mut res = Ok(()); for cnum in iter::once(LOCAL_CRATE).chain(tcx.crates(()).iter().copied()) { - let incoherent_impls = match tcx.crate_incoherent_impls((cnum, simp)) { - Ok(impls) => impls, - Err(e) => { - res = Err(e); - continue; - } - }; - for &impl_def_id in incoherent_impls { + for &impl_def_id in tcx.crate_incoherent_impls((cnum, simp)) { impls.push(impl_def_id) } } - debug!(?impls); - res?; - Ok(tcx.arena.alloc_slice(&impls)) + tcx.arena.alloc_slice(&impls) } pub(super) fn traits_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] { diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index a92bdb2eae0de..17280c3d0476f 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::hir::place::Place as HirPlace; 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 a0262f12cb5d6..321b51289fb08 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -11,12 +11,12 @@ use rustc_hir as hir; 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 951112dfe858e..963fa12a8c739 100644 --- a/compiler/rustc_middle/src/ty/vtable.rs +++ b/compiler/rustc_middle/src/ty/vtable.rs @@ -3,7 +3,7 @@ use std::fmt; 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 abd6df17514bb..a93a146ec7c42 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 32f5251568f1b..b99336c2c85ba 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 75ae4e11fa9ea..fe30cbfae4e32 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 8c95988477d9c..8dafc42264485 100644 --- a/compiler/rustc_middle/src/util/mod.rs +++ b/compiler/rustc_middle/src/util/mod.rs @@ -3,7 +3,7 @@ pub mod call_kind; 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 6163fa2932d08..c98d88e22d409 100644 --- a/compiler/rustc_middle/src/values.rs +++ b/compiler/rustc_middle/src/values.rs @@ -4,12 +4,12 @@ use std::ops::ControlFlow; 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 7afa628843f22..89e64015bc439 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_middle::{span_bug, ty}; 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 e80b654309ea5..9c5ee5b0996e5 100644 --- a/compiler/rustc_mir_build/src/build/cfg.rs +++ b/compiler/rustc_mir_build/src/build/cfg.rs @@ -40,10 +40,10 @@ impl<'tcx> CFG<'tcx> { place: Place<'tcx>, rvalue: Rvalue<'tcx>, ) { - self.push( - block, - Statement { source_info, kind: StatementKind::Assign(Box::new((place, rvalue))) }, - ); + self.push(block, Statement { + source_info, + kind: StatementKind::Assign(Box::new((place, rvalue))), + }); } pub(crate) fn push_assign_constant( diff --git a/compiler/rustc_mir_build/src/build/custom/mod.rs b/compiler/rustc_mir_build/src/build/custom/mod.rs index 1e1fa21b5f3d2..4815db47b16c1 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 0cbd2da10db2b..9e3af89105294 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::mir::*; 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 4f1166f91118e..ae164cf760569 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_middle::{bug, mir, span_bug}; 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 07784982631f8..c7298e3ddfa90 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::thir::*; 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. @@ -470,60 +470,56 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { block.and(place_builder) } - ExprKind::PlaceTypeAscription { source, ref user_ty } => { + ExprKind::PlaceTypeAscription { source, ref user_ty, user_ty_span } => { let place_builder = unpack!( block = this.expr_as_place(block, source, mutability, fake_borrow_temps,) ); if let Some(user_ty) = user_ty { + let ty_source_info = this.source_info(user_ty_span); let annotation_index = this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation { - span: source_info.span, + span: user_ty_span, user_ty: user_ty.clone(), inferred_ty: expr.ty, }); 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: ty_source_info, + kind: StatementKind::AscribeUserType( + Box::new((place, UserTypeProjection { + base: annotation_index, + projs: vec![], + })), + Variance::Invariant, + ), + }); } block.and(place_builder) } - ExprKind::ValueTypeAscription { source, ref user_ty } => { + ExprKind::ValueTypeAscription { source, ref user_ty, user_ty_span } => { let source_expr = &this.thir[source]; let temp = unpack!( block = this.as_temp(block, source_expr.temp_lifetime, source, mutability) ); if let Some(user_ty) = user_ty { + let ty_source_info = this.source_info(user_ty_span); let annotation_index = this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation { - span: source_info.span, + span: user_ty_span, 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: ty_source_info, + kind: StatementKind::AscribeUserType( + Box::new((Place::from(temp), UserTypeProjection { + base: annotation_index, + projs: vec![], + })), + Variance::Invariant, + ), + }); } block.and(PlaceBuilder::from(temp)) } diff --git a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs index 0c9571da3cf7f..fd949a533845e 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::middle::region; 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); let storage = this.temp(Ty::new_mut_ptr(tcx, tcx.types.u8), expr_span); let success = this.cfg.start_new_block(); - this.cfg.terminate( - block, - source_info, - TerminatorKind::Call { - func: exchange_malloc, - args: [ - Spanned { node: Operand::Move(size), span: DUMMY_SP }, - Spanned { node: Operand::Move(align), span: DUMMY_SP }, - ] - .into(), - destination: storage, - target: Some(success), - unwind: UnwindAction::Continue, - call_source: CallSource::Misc, - fn_span: expr_span, - }, - ); + this.cfg.terminate(block, source_info, TerminatorKind::Call { + func: exchange_malloc, + args: [Spanned { node: Operand::Move(size), span: DUMMY_SP }, Spanned { + node: Operand::Move(align), + span: DUMMY_SP, + }] + .into(), + destination: storage, + target: Some(success), + unwind: UnwindAction::Continue, + call_source: CallSource::Misc, + fn_span: expr_span, + }); this.diverge_from(block); block = success; @@ -171,10 +167,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // and therefore is not considered during coroutine auto-trait // determination. See the comment about `box` at `yield_in_scope`. let result = this.local_decls.push(LocalDecl::new(expr.ty, expr_span)); - this.cfg.push( - block, - Statement { source_info, kind: StatementKind::StorageLive(result) }, - ); + this.cfg.push(block, Statement { + source_info, + kind: StatementKind::StorageLive(result), + }); if let Some(scope) = scope { // schedule a shallow free of that memory, lest we unwind: this.schedule_drop_storage_and_value(expr_span, scope, result); @@ -268,15 +264,12 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); merge_place }; - this.cfg.push( - block, - Statement { - source_info, - kind: StatementKind::Intrinsic(Box::new( - NonDivergingIntrinsic::Assume(Operand::Move(assert_place)), - )), - }, - ); + this.cfg.push(block, Statement { + source_info, + kind: StatementKind::Intrinsic(Box::new( + NonDivergingIntrinsic::Assume(Operand::Move(assert_place)), + )), + }); } (op, ty) @@ -299,7 +292,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let cast_kind = mir_cast_kind(ty, expr.ty); block.and(Rvalue::Cast(cast_kind, source, expr.ty)) } - ExprKind::PointerCoercion { cast, source } => { + ExprKind::PointerCoercion { cast, source, is_from_as_cast } => { let source = unpack!( block = this.as_operand( block, @@ -309,7 +302,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { NeedsTemporary::No ) ); - block.and(Rvalue::Cast(CastKind::PointerCoercion(cast), source, expr.ty)) + let origin = + if is_from_as_cast { CoercionSource::AsCast } else { CoercionSource::Implicit }; + block.and(Rvalue::Cast(CastKind::PointerCoercion(cast, origin), source, expr.ty)) } ExprKind::Array { ref fields } => { // (*) We would (maybe) be closer to codegen if we @@ -721,16 +716,12 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); if let Operand::Move(to_drop) = value_operand { let success = this.cfg.start_new_block(); - this.cfg.terminate( - block, - outer_source_info, - TerminatorKind::Drop { - place: to_drop, - target: success, - unwind: UnwindAction::Continue, - replace: false, - }, - ); + this.cfg.terminate(block, outer_source_info, TerminatorKind::Drop { + place: to_drop, + target: success, + unwind: UnwindAction::Continue, + replace: false, + }); this.diverge_from(block); block = success; } diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index 1c805ed20cc36..86fe447f39973 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { this.in_breakable_scope(Some(loop_block), destination, expr_span, move |this| { // conduct the test, if necessary let body_block = this.cfg.start_new_block(); - this.cfg.terminate( - loop_block, - source_info, - TerminatorKind::FalseUnwind { - real_target: body_block, - unwind: UnwindAction::Continue, - }, - ); + this.cfg.terminate(loop_block, source_info, TerminatorKind::FalseUnwind { + real_target: body_block, + unwind: UnwindAction::Continue, + }); this.diverge_from(loop_block); // The “return” value of the loop body must always be a unit. We therefore @@ -259,30 +255,26 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { debug!("expr_into_dest: fn_span={:?}", fn_span); - this.cfg.terminate( - block, - source_info, - TerminatorKind::Call { - func: fun, - args, - unwind: UnwindAction::Continue, - destination, - // The presence or absence of a return edge affects control-flow sensitive - // MIR checks and ultimately whether code is accepted or not. We can only - // omit the return edge if a return type is visibly uninhabited to a module - // that makes the call. - target: expr - .ty - .is_inhabited_from(this.tcx, this.parent_module, this.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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let tmp = this.get_unit_temp(); let target = this.ast_block(tmp, target, block, source_info).into_block(); - this.cfg.terminate( - target, - source_info, - TerminatorKind::Goto { target: destination_block }, - ); + this.cfg.terminate(target, source_info, TerminatorKind::Goto { + target: destination_block, + }); mir::InlineAsmOperand::Label { target_index } } @@ -484,22 +474,18 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ) ); 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 b38f0a41e5d21..76034c03b4bf6 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { unpack!(block = this.break_for_tail_call(block, &args, source_info)); - this.cfg.terminate( - block, - source_info, - TerminatorKind::TailCall { func: fun, args, fn_span }, - ); + this.cfg.terminate(block, source_info, TerminatorKind::TailCall { + func: fun, + args, + fn_span, + }); this.cfg.start_new_block().unit() }) diff --git a/compiler/rustc_mir_build/src/build/matches/match_pair.rs b/compiler/rustc_mir_build/src/build/matches/match_pair.rs index ab2bfcbca3aa6..6df50057ee83a 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::mir::*; 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { 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 @@ impl<'pat, 'tcx> MatchPairTree<'pat, 'tcx> { let ascription = place.map(|source| { let span = pattern.span; let parent_id = cx.tcx.typeck_root_def_id(cx.def_id.to_def_id()); - let args = ty::InlineConstArgs::new( - cx.tcx, - ty::InlineConstArgsParts { - parent_args: ty::GenericArgs::identity_for_item(cx.tcx, parent_id), - ty: cx.infcx.next_ty_var(span), - }, - ) + let args = ty::InlineConstArgs::new(cx.tcx, ty::InlineConstArgsParts { + parent_args: ty::GenericArgs::identity_for_item(cx.tcx, parent_id), + ty: cx.infcx.next_ty_var(span), + }) .args; let user_ty = cx.infcx.canonicalize_user_type_annotation(ty::UserType::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 cae4aa7bad3d2..51ead57020556 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_span::{BytePos, Pos, Span}; 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { variable_source_info: SourceInfo, declare_let_bindings: DeclareLetBindings, ) -> BlockAnd<()> { - self.then_else_break_inner( - block, - expr_id, - ThenElseArgs { temp_scope_override, variable_source_info, declare_let_bindings }, - ) + self.then_else_break_inner(block, expr_id, ThenElseArgs { + temp_scope_override, + variable_source_info, + declare_let_bindings, + }) } fn then_else_break_inner( @@ -134,24 +134,16 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let local_scope = this.local_scope(); let (lhs_success_block, failure_block) = this.in_if_then_scope(local_scope, expr_span, |this| { - this.then_else_break_inner( - block, - lhs, - ThenElseArgs { - declare_let_bindings: DeclareLetBindings::LetNotPermitted, - ..args - }, - ) - }); - 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { if this.tcx.sess.instrument_coverage() { this.cfg.push_coverage_span_marker(block, this.source_info(expr_span)); } - this.then_else_break_inner( - block, - arg, - ThenElseArgs { - declare_let_bindings: DeclareLetBindings::LetNotPermitted, - ..args - }, - ) + this.then_else_break_inner(block, arg, ThenElseArgs { + declare_let_bindings: DeclareLetBindings::LetNotPermitted, + ..args + }) }); this.break_for_else(success_block, args.variable_source_info); failure_block.unit() @@ -638,30 +626,27 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let ty_source_info = self.source_info(annotation.span); let base = self.canonical_user_type_annotations.push(annotation.clone()); - self.cfg.push( - block, - Statement { - source_info: ty_source_info, - kind: StatementKind::AscribeUserType( - Box::new((place, UserTypeProjection { base, projs: Vec::new() })), - // We always use invariant as the variance here. This is because the - // variance field from the ascription refers to the variance to use - // when applying the type to the value being matched, but this - // ascription applies rather to the type of the binding. e.g., in this - // example: - // - // ``` - // let x: T = - // ``` - // - // We are creating an ascription that defines the type of `x` to be - // exactly `T` (i.e., with invariance). The variance field, in - // contrast, is intended to be used to relate `T` to the type of - // ``. - ty::Invariant, - ), - }, - ); + self.cfg.push(block, Statement { + source_info: ty_source_info, + kind: StatementKind::AscribeUserType( + Box::new((place, UserTypeProjection { base, projs: Vec::new() })), + // We always use invariant as the variance here. This is because the + // variance field from the ascription refers to the variance to use + // when applying the type to the value being matched, but this + // ascription applies rather to the type of the binding. e.g., in this + // example: + // + // ``` + // let x: T = + // ``` + // + // We are creating an ascription that defines the type of `x` to be + // exactly `T` (i.e., with invariance). The variance field, in + // contrast, is intended to be used to relate `T` to the type of + // ``. + ty::Invariant, + ), + }); self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard); block.unit() @@ -2559,19 +2544,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let source_info = self.source_info(ascription.annotation.span); let base = self.canonical_user_type_annotations.push(ascription.annotation); - self.cfg.push( - block, - Statement { - source_info, - kind: StatementKind::AscribeUserType( - Box::new(( - ascription.source, - UserTypeProjection { base, projs: Vec::new() }, - )), - ascription.variance, - ), - }, - ); + self.cfg.push(block, Statement { + source_info, + kind: StatementKind::AscribeUserType( + Box::new((ascription.source, UserTypeProjection { base, projs: Vec::new() })), + ascription.variance, + ), + }); } } diff --git a/compiler/rustc_mir_build/src/build/matches/simplify.rs b/compiler/rustc_mir_build/src/build/matches/simplify.rs index 04cf81d54e9df..5b402604395af 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 std::mem; 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 7af1ede24a4f4..020c202f96503 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::ty::{self, GenericArg, Ty, TyCtxt}; 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); // `let temp = ::deref(ref_src);` // or `let temp = ::deref_mut(ref_src);` - self.cfg.terminate( - block, - source_info, - TerminatorKind::Call { - func: Operand::Constant(Box::new(ConstOperand { - span, - user_ty: None, - const_: method, - })), - args: [Spanned { node: Operand::Move(ref_src), span }].into(), - destination: temp, - target: Some(target_block), - unwind: UnwindAction::Continue, - call_source: CallSource::Misc, - fn_span: source_info.span, - }, - ); + self.cfg.terminate(block, source_info, TerminatorKind::Call { + func: Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_: method })), + args: [Spanned { node: Operand::Move(ref_src), span }].into(), + destination: temp, + target: Some(target_block), + unwind: UnwindAction::Continue, + call_source: CallSource::Misc, + fn_span: source_info.span, + }); } /// Compare using the provided built-in comparison operator @@ -415,7 +407,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { source_info, temp, Rvalue::Cast( - CastKind::PointerCoercion(PointerCoercion::Unsize), + CastKind::PointerCoercion( + PointerCoercion::Unsize, + CoercionSource::Implicit, + ), Operand::Copy(val), ty, ), @@ -429,7 +424,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { source_info, slice, Rvalue::Cast( - CastKind::PointerCoercion(PointerCoercion::Unsize), + CastKind::PointerCoercion( + PointerCoercion::Unsize, + CoercionSource::Implicit, + ), expect, ty, ), @@ -466,33 +464,29 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let bool_ty = self.tcx.types.bool; let eq_result = self.temp(bool_ty, source_info.span); let eq_block = self.cfg.start_new_block(); - self.cfg.terminate( - block, - source_info, - TerminatorKind::Call { - func: Operand::Constant(Box::new(ConstOperand { - span: source_info.span, - - // 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, - }, - ); + 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, + + 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 8491b5fe380c7..555684ded81a1 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_middle::ty::Ty; 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { source_info: SourceInfo, ) { if imaginary_target != real_target { - self.cfg.terminate( - from_block, - source_info, - TerminatorKind::FalseEdge { real_target, imaginary_target }, - ); + self.cfg.terminate(from_block, source_info, TerminatorKind::FalseEdge { + real_target, + imaginary_target, + }); } else { self.cfg.goto(from_block, source_info, real_target) } diff --git a/compiler/rustc_mir_build/src/build/misc.rs b/compiler/rustc_mir_build/src/build/misc.rs index 26906973ca86c..53cb99d44e8f8 100644 --- a/compiler/rustc_mir_build/src/build/misc.rs +++ b/compiler/rustc_mir_build/src/build/misc.rs @@ -45,16 +45,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ) -> Place<'tcx> { let usize_ty = self.tcx.types.usize; let temp = self.temp(usize_ty, source_info.span); - self.cfg.push_assign_constant( - block, - source_info, - temp, - ConstOperand { - span: source_info.span, - user_ty: None, - const_: Const::from_usize(self.tcx, value), - }, - ); + self.cfg.push_assign_constant(block, source_info, temp, ConstOperand { + span: source_info.span, + user_ty: None, + const_: Const::from_usize(self.tcx, value), + }); temp } diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index b98deda8fd022..8c20d2e0d3a62 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 693037d03e017..dfc82f705a81b 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::thir::{ExprId, LintLevel}; 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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { (Some(normal_block), Some(exit_block)) => { let target = self.cfg.start_new_block(); let source_info = self.source_info(span); - self.cfg.terminate( - normal_block.into_block(), - source_info, - TerminatorKind::Goto { target }, - ); - self.cfg.terminate( - exit_block.into_block(), - source_info, - TerminatorKind::Goto { target }, - ); + self.cfg.terminate(normal_block.into_block(), source_info, TerminatorKind::Goto { + target, + }); + self.cfg.terminate(exit_block.into_block(), source_info, TerminatorKind::Goto { + target, + }); target.unit() } } @@ -806,25 +802,21 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { unwind_drops.add_entry_point(block, unwind_entry_point); let next = self.cfg.start_new_block(); - self.cfg.terminate( - block, - source_info, - TerminatorKind::Drop { - place: local.into(), - target: next, - unwind: UnwindAction::Continue, - replace: false, - }, - ); + self.cfg.terminate(block, source_info, TerminatorKind::Drop { + place: local.into(), + target: next, + unwind: UnwindAction::Continue, + replace: false, + }); block = next; } DropKind::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 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let assign_unwind = self.cfg.start_new_cleanup_block(); self.cfg.push_assign(assign_unwind, source_info, place, value.clone()); - self.cfg.terminate( - block, - source_info, - TerminatorKind::Drop { - place, - target: assign, - unwind: UnwindAction::Cleanup(assign_unwind), - replace: true, - }, - ); + self.cfg.terminate(block, source_info, TerminatorKind::Drop { + place, + target: assign, + unwind: UnwindAction::Cleanup(assign_unwind), + replace: true, + }); self.diverge_from(block); assign.unit() @@ -1312,17 +1300,13 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let source_info = self.source_info(span); let success_block = self.cfg.start_new_block(); - self.cfg.terminate( - block, - source_info, - TerminatorKind::Assert { - cond, - expected, - msg: Box::new(msg), - target: success_block, - unwind: UnwindAction::Continue, - }, - ); + self.cfg.terminate(block, source_info, TerminatorKind::Assert { + cond, + expected, + msg: Box::new(msg), + target: success_block, + unwind: UnwindAction::Continue, + }); self.diverge_from(block); success_block @@ -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 4fe984b961e71..8512763a595d5 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::visit::Visitor; 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 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { .copied() .filter(|feature| missing.contains(feature)) .collect(); - self.requires_unsafe( - expr.span, - CallToFunctionWith { function: func_did, missing, build_enabled }, - ); + self.requires_unsafe(expr.span, CallToFunctionWith { + function: func_did, + missing, + build_enabled, + }); } } } @@ -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 411e9420914da..42be7f9402ecc 100644 --- a/compiler/rustc_mir_build/src/errors.rs +++ b/compiler/rustc_mir_build/src/errors.rs @@ -7,8 +7,8 @@ use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; 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 80e91811b1c5f..cb9a4e2604e25 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 3f730b5d18306..fbd45f59a4fb4 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 @@ use rustc_middle::ty::{ 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> { @@ -104,16 +104,29 @@ impl<'tcx> Cx<'tcx> { }; let kind = match adjustment.kind { - Adjust::Pointer(PointerCoercion::Unsize) => { - adjust_span(&mut expr); + Adjust::Pointer(cast) => { + if cast == PointerCoercion::Unsize { + adjust_span(&mut expr); + } + + let is_from_as_cast = if let hir::Node::Expr(hir::Expr { + kind: hir::ExprKind::Cast(..), + span: cast_span, + .. + }) = self.tcx.parent_hir_node(hir_expr.hir_id) + { + // Use the whole span of the `x as T` expression for the coercion. + span = *cast_span; + true + } else { + false + }; ExprKind::PointerCoercion { - cast: PointerCoercion::Unsize, + cast, source: self.thir.exprs.push(expr), + is_from_as_cast, } } - Adjust::Pointer(cast) => { - ExprKind::PointerCoercion { cast, source: self.thir.exprs.push(expr) } - } Adjust::NeverToAny if adjustment.target.is_never() => return expr, Adjust::NeverToAny => ExprKind::NeverToAny { source: self.thir.exprs.push(expr) }, Adjust::Deref(None) => { @@ -146,7 +159,6 @@ impl<'tcx> Cx<'tcx> { Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => { ExprKind::RawBorrow { mutability, arg: self.thir.exprs.push(expr) } } - Adjust::DynStar => ExprKind::Cast { source: self.thir.exprs.push(expr) }, Adjust::ReborrowPin(region, mutbl) => { debug!("apply ReborrowPin adjustment"); // Rewrite `$expr` as `Pin { __pointer: &(mut)? *($expr).__pointer }` @@ -236,6 +248,7 @@ impl<'tcx> Cx<'tcx> { ExprKind::PointerCoercion { source: self.mirror_expr(source), cast: PointerCoercion::ArrayToPointer, + is_from_as_cast: true, } } else if let hir::ExprKind::Path(ref qpath) = source.kind && let res = self.typeck_results().qpath_res(qpath, source.hir_id) @@ -841,6 +854,7 @@ impl<'tcx> Cx<'tcx> { ExprKind::ValueTypeAscription { source: cast_expr, user_ty: Some(Box::new(*user_ty)), + user_ty_span: cast_ty.span, } } else { cast @@ -852,9 +866,17 @@ impl<'tcx> Cx<'tcx> { debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty); let mirrored = self.mirror_expr(source); if source.is_syntactic_place_expr() { - ExprKind::PlaceTypeAscription { source: mirrored, user_ty } + ExprKind::PlaceTypeAscription { + source: mirrored, + user_ty, + user_ty_span: ty.span, + } } else { - ExprKind::ValueTypeAscription { source: mirrored, user_ty } + ExprKind::ValueTypeAscription { + source: mirrored, + user_ty, + user_ty_span: ty.span, + } } } hir::ExprKind::DropTemps(source) => ExprKind::Use { source: self.mirror_expr(source) }, diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index 5b5f97cb51410..377931e3be730 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 @@ impl<'tcx> Cx<'tcx> { let ty = if fn_decl.c_variadic && index == fn_decl.inputs.len() { let va_list_did = self.tcx.require_lang_item(LangItem::VaList, Some(param.span)); - self.tcx - .type_of(va_list_did) - .instantiate(self.tcx, &[self.tcx.lifetimes.re_erased.into()]) + self.tcx.type_of(va_list_did).instantiate(self.tcx, &[self + .tcx + .lifetimes + .re_erased + .into()]) } else { fn_sig.inputs()[index] }; diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 3fde6466d8cb0..ae77bce6bb199 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_ast::Mutability; 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 @@ use rustc_session::lint::builtin::{ 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 53393046610ac..2c3611afca9a7 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::thir::{FieldPat, Pat, PatKind}; 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 d78e1f5da09f0..04e921ecc2e05 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 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> { 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_build/src/thir/print.rs b/compiler/rustc_mir_build/src/thir/print.rs index ce7774f594882..61317925d09e5 100644 --- a/compiler/rustc_mir_build/src/thir/print.rs +++ b/compiler/rustc_mir_build/src/thir/print.rs @@ -292,9 +292,14 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { self.print_expr(*source, depth_lvl + 2); print_indented!(self, "}", depth_lvl); } - PointerCoercion { cast, source } => { + PointerCoercion { cast, is_from_as_cast, source } => { print_indented!(self, "Pointer {", depth_lvl); print_indented!(self, format!("cast: {:?}", cast), depth_lvl + 1); + print_indented!( + self, + format!("is_from_as_cast: {:?}", is_from_as_cast), + depth_lvl + 1 + ); print_indented!(self, "source:", depth_lvl + 1); self.print_expr(*source, depth_lvl + 2); print_indented!(self, "}", depth_lvl); @@ -454,16 +459,18 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> { self.print_adt_expr(&**adt_expr, depth_lvl + 1); print_indented!(self, "}", depth_lvl); } - PlaceTypeAscription { source, user_ty } => { + PlaceTypeAscription { source, user_ty, user_ty_span } => { print_indented!(self, "PlaceTypeAscription {", depth_lvl); print_indented!(self, format!("user_ty: {:?}", user_ty), depth_lvl + 1); + print_indented!(self, format!("user_ty_span: {:?}", user_ty_span), depth_lvl + 1); print_indented!(self, "source:", depth_lvl + 1); self.print_expr(*source, depth_lvl + 2); print_indented!(self, "}", depth_lvl); } - ValueTypeAscription { source, user_ty } => { + ValueTypeAscription { source, user_ty, user_ty_span } => { print_indented!(self, "ValueTypeAscription {", depth_lvl); print_indented!(self, format!("user_ty: {:?}", user_ty), depth_lvl + 1); + print_indented!(self, format!("user_ty_span: {:?}", user_ty_span), depth_lvl + 1); print_indented!(self, "source:", depth_lvl + 1); self.print_expr(*source, depth_lvl + 2); print_indented!(self, "}", depth_lvl); diff --git a/compiler/rustc_mir_dataflow/src/elaborate_drops.rs b/compiler/rustc_mir_dataflow/src/elaborate_drops.rs index c4d06cbb1b0fe..f2541c37167f0 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::span_bug; 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 @@ where .patch_terminator(bb, TerminatorKind::Goto { target: self.succ }); } DropStyle::Static => { - self.elaborator.patch().patch_terminator( - bb, - TerminatorKind::Drop { - place: self.place, - target: self.succ, - unwind: self.unwind.into_action(), - replace: false, - }, - ); + self.elaborator.patch().patch_terminator(bb, TerminatorKind::Drop { + place: self.place, + target: self.succ, + unwind: self.unwind.into_action(), + replace: false, + }); } DropStyle::Conditional => { let drop_bb = self.complete_drop(self.succ, self.unwind); @@ -732,15 +729,12 @@ where }; let loop_block = self.elaborator.patch().new_block(loop_block); - self.elaborator.patch().patch_terminator( - drop_block, - TerminatorKind::Drop { - place: tcx.mk_place_deref(ptr), - target: loop_block, - unwind: unwind.into_action(), - replace: false, - }, - ); + self.elaborator.patch().patch_terminator(drop_block, TerminatorKind::Drop { + place: tcx.mk_place_deref(ptr), + target: loop_block, + unwind: unwind.into_action(), + replace: false, + }); loop_block } diff --git a/compiler/rustc_mir_dataflow/src/framework/engine.rs b/compiler/rustc_mir_dataflow/src/framework/engine.rs index 54206501d9f6a..947bdf860b58d 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_data_structures::work_queue::WorkQueue; 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 5e4f36e4ae3ae..ed540cd148c45 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 e72dca2c83478..96a70f4fa5b0c 100644 --- a/compiler/rustc_mir_dataflow/src/framework/graphviz.rs +++ b/compiler/rustc_mir_dataflow/src/framework/graphviz.rs @@ -8,7 +8,7 @@ use std::{io, ops, str}; 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 @@ where r#"{state}"#, colspan = this.style.num_state_columns(), fmt = fmt, - state = dot::escape_html(&format!( - "{:?}", - DebugWithAdapter { this: state, ctxt: analysis } - )), + state = dot::escape_html(&format!("{:?}", DebugWithAdapter { + this: state, + ctxt: analysis + })), ) }) } diff --git a/compiler/rustc_mir_dataflow/src/framework/mod.rs b/compiler/rustc_mir_dataflow/src/framework/mod.rs index 6da3a20dc02c3..d0472e35fe00a 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::cursor::ResultsCursor; 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 52db931b68e1e..1861f4cffc717 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 a88927427bac2..25e8726cf6162 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::elaborate_drops::DropFlagState; 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 f283660e1e793..9b5bfa9bfa00a 100644 --- a/compiler/rustc_mir_dataflow/src/impls/mod.rs +++ b/compiler/rustc_mir_dataflow/src/impls/mod.rs @@ -7,7 +7,7 @@ mod initialized; 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 9385b52103f69..cb7c7edc413a6 100644 --- a/compiler/rustc_mir_dataflow/src/lib.rs +++ b/compiler/rustc_mir_dataflow/src/lib.rs @@ -17,9 +17,9 @@ pub use self::drop_flag_effects::{ 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 87ea729923895..3c8be2f73e14a 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::tcx::{PlaceTy, RvalueInitializationState}; 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 adfa94464a054..73abb669a1117 100644 --- a/compiler/rustc_mir_dataflow/src/points.rs +++ b/compiler/rustc_mir_dataflow/src/points.rs @@ -3,7 +3,7 @@ use rustc_index::interval::SparseIntervalMatrix; 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 ac9b853f21b82..75732b19cd0b2 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_hir::def_id::DefId; 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 0540436632014..aa09fe1dd45e9 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -39,8 +39,8 @@ use std::ops::Range; 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 8291df9be5349..d889bc90c9d74 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 74df5f7479e06..559df222a5040 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 8ad364ed05502..53176eec9bcb9 100644 --- a/compiler/rustc_mir_transform/src/add_retag.rs +++ b/compiler/rustc_mir_transform/src/add_retag.rs @@ -111,13 +111,10 @@ impl<'tcx> crate::MirPass<'tcx> for AddRetag { .collect::>(); // Now we go over the returns we collected to retag the return values. for (source_info, dest_place, dest_block) in returns { - basic_blocks[dest_block].statements.insert( - 0, - Statement { - source_info, - kind: StatementKind::Retag(RetagKind::Default, Box::new(dest_place)), - }, - ); + basic_blocks[dest_block].statements.insert(0, Statement { + source_info, + kind: StatementKind::Retag(RetagKind::Default, Box::new(dest_place)), + }); } // PART 3 @@ -172,13 +169,10 @@ impl<'tcx> crate::MirPass<'tcx> for AddRetag { }; // Insert a retag after the statement. let source_info = block_data.statements[i].source_info; - block_data.statements.insert( - i + 1, - Statement { - source_info, - kind: StatementKind::Retag(retag_kind, Box::new(place)), - }, - ); + block_data.statements.insert(i + 1, Statement { + source_info, + kind: StatementKind::Retag(retag_kind, Box::new(place)), + }); } } } diff --git a/compiler/rustc_mir_transform/src/check_const_item_mutation.rs b/compiler/rustc_mir_transform/src/check_const_item_mutation.rs index 9c3cbbe1fc963..7968b666dff2f 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::visit::Visitor; 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 97ce16c06616f..6a22a58470c95 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; @@ -42,6 +42,7 @@ impl<'tcx> crate::MirPass<'tcx> for CleanupPostBorrowck { ref mut cast_kind @ CastKind::PointerCoercion( PointerCoercion::ArrayToPointer | PointerCoercion::MutToConstPointer, + _, ), .., ), diff --git a/compiler/rustc_mir_transform/src/copy_prop.rs b/compiler/rustc_mir_transform/src/copy_prop.rs index b3db566912108..7d6ae9843b15f 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 1fb74f5d82ca2..8f032728f6be0 100644 --- a/compiler/rustc_mir_transform/src/coroutine.rs +++ b/compiler/rustc_mir_transform/src/coroutine.rs @@ -67,14 +67,14 @@ use rustc_middle::ty::{ 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 @@ impl<'tcx> crate::MirPass<'tcx> for StateTransform { // (which is now a generator interior). let source_info = SourceInfo::outermost(body.span); let stmts = &mut body.basic_blocks_mut()[START_BLOCK].statements; - stmts.insert( - 0, - Statement { - source_info, - kind: StatementKind::Assign(Box::new(( - old_resume_local.into(), - Rvalue::Use(Operand::Move(resume_local.into())), - ))), - }, - ); + stmts.insert(0, Statement { + source_info, + kind: StatementKind::Assign(Box::new(( + old_resume_local.into(), + Rvalue::Use(Operand::Move(resume_local.into())), + ))), + }); let always_live_locals = always_storage_live_locals(body); @@ -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 6476f3c623841..65442877d2dd5 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 743aa6790583f..d839f46cfbd55 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::captures::Captures; 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 2ac08ea85d253..ec5ba354805f1 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::mir::{self, BasicBlock, StatementKind}; 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 f78fc7931f9f9..104f340c8d63f 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -9,7 +9,7 @@ mod tests; 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 b904b0d2599b1..da7d20cf19a68 100644 --- a/compiler/rustc_mir_transform/src/coverage/spans.rs +++ b/compiler/rustc_mir_transform/src/coverage/spans.rs @@ -8,9 +8,9 @@ use tracing::{debug, debug_span, instrument}; 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 7f5765c9462de..875db23ce0969 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_middle::mir::{ }; 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 a4db11bb2c160..233ca9981c50c 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_data_structures::graph::{DirectedGraph, Successors}; 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 @@ impl<'tcx> MockBlocks<'tcx> { } fn call(&mut self, some_from_block: Option) -> BasicBlock { - self.add_block_from( - some_from_block, - TerminatorKind::Call { - func: Operand::Copy(self.dummy_place.clone()), - args: [].into(), - destination: self.dummy_place.clone(), - target: Some(TEMP_BLOCK), - unwind: UnwindAction::Continue, - call_source: CallSource::Misc, - fn_span: DUMMY_SP, - }, - ) + self.add_block_from(some_from_block, TerminatorKind::Call { + func: Operand::Copy(self.dummy_place.clone()), + args: [].into(), + destination: self.dummy_place.clone(), + target: Some(TEMP_BLOCK), + unwind: UnwindAction::Continue, + call_source: CallSource::Misc, + fn_span: DUMMY_SP, + }) } fn goto(&mut self, some_from_block: Option) -> BasicBlock { diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index 997b8c06a96a9..88dc8e74a8c29 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::value_analysis::{ }; 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. @@ -189,7 +189,7 @@ impl<'tcx> ValueAnalysis<'tcx> for ConstAnalysis<'_, 'tcx> { } } Rvalue::Cast( - CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize), + CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _), operand, _, ) => { diff --git a/compiler/rustc_mir_transform/src/dead_store_elimination.rs b/compiler/rustc_mir_transform/src/dead_store_elimination.rs index 65c037559c595..edffe6ce78f67 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::bug; 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 c0cb0e641ac1b..753bae8e15688 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 f123658580da4..ad83c0295baec 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_index::interval::SparseIntervalMatrix; 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 1640d34d6c8ee..d7c473604196c 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/elaborate_drops.rs b/compiler/rustc_mir_transform/src/elaborate_drops.rs index 42d13fa3613ab..c35aec42408ca 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 4550ef0631512..84d44c2ab4c41 100644 --- a/compiler/rustc_mir_transform/src/errors.rs +++ b/compiler/rustc_mir_transform/src/errors.rs @@ -4,8 +4,8 @@ use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; 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 8490b7e235818..99892a1296be4 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 eb09a7d3b2114..e55aeeac6e069 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::visit::Visitor; 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 0f08d920c5e0e..f735d08fca573 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -87,23 +87,23 @@ use std::borrow::Cow; 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}; @@ -576,7 +576,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { } value.offset(Size::ZERO, to, &self.ecx).ok()? } - CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize) => { + CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) => { let src = self.evaluated[value].as_ref()?; let to = self.ecx.layout_of(to).ok()?; let dest = self.ecx.allocate(to, MemoryKind::Stack).ok()?; @@ -593,7 +593,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { let ret = self.ecx.ptr_to_ptr(&src, to).ok()?; ret.into() } - CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer) => { + CastKind::PointerCoercion(ty::adjustment::PointerCoercion::UnsafeFnPointer, _) => { let src = self.evaluated[value].as_ref()?; let src = self.ecx.read_immediate(src).ok()?; let to = self.ecx.layout_of(to).ok()?; @@ -1138,7 +1138,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { ( UnOp::PtrMetadata, Value::Cast { - kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize), + kind: CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _), from, to, .. @@ -1333,8 +1333,8 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { 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)?; @@ -1342,7 +1342,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { return Some(value); } - if let CastKind::PointerCoercion(ReifyFnPointer | ClosureFnPointer(_)) = kind { + if let CastKind::PointerCoercion(ReifyFnPointer | ClosureFnPointer(_), _) = kind { // Each reification of a generic fn may get a different pointer. // Do not try to merge them. return self.new_opaque(); @@ -1429,7 +1429,7 @@ impl<'body, 'tcx> VnState<'body, 'tcx> { // We have an unsizing cast, which assigns the length to fat pointer metadata. if let Value::Cast { kind, from, to, .. } = self.get(inner) - && let CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize) = kind + && let CastKind::PointerCoercion(ty::adjustment::PointerCoercion::Unsize, _) = kind && let Some(from) = from.builtin_deref(true) && let ty::Array(_, len) = from.kind() && let Some(to) = to.builtin_deref(true) diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 2de75e2ef50fc..c9f24764cc2a1 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -6,8 +6,8 @@ use std::ops::{Range, RangeFrom}; 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 @@ impl<'tcx> Inliner<'tcx> { }); if let Some(block) = return_block { - caller_body[block].statements.insert( - 0, - Statement { - source_info: callsite.source_info, - kind: StatementKind::StorageDead(local), - }, - ); + caller_body[block].statements.insert(0, Statement { + source_info: callsite.source_info, + kind: StatementKind::StorageDead(local), + }); } local diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index 5c8958924fbff..8bcc91b448858 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -5,7 +5,7 @@ use rustc_hir::LangItem; 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 1810569bc8ea8..9d85b5ba5a71c 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_arena::DroplessArena; 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 f123f39bf4244..783e7aabe8543 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 std::fmt::Debug; 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 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { let source_info = self.body.source_info(location); if let Some(lint_root) = self.lint_root(*source_info) { let span = source_info.span; - self.tcx.emit_node_span_lint( - lint_kind.lint(), - lint_root, + 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 0868f4b3d882a..56268c1d201d6 100644 --- a/compiler/rustc_mir_transform/src/lib.rs +++ b/compiler/rustc_mir_transform/src/lib.rs @@ -26,14 +26,14 @@ use rustc_hir::def_id::LocalDefId; 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/mentioned_items.rs b/compiler/rustc_mir_transform/src/mentioned_items.rs index f24de609e6b29..cf5c5f85a9ff6 100644 --- a/compiler/rustc_mir_transform/src/mentioned_items.rs +++ b/compiler/rustc_mir_transform/src/mentioned_items.rs @@ -70,11 +70,11 @@ impl<'tcx> Visitor<'tcx> for MentionedItemsVisitor<'_, 'tcx> { match *rvalue { // We need to detect unsizing casts that required vtables. mir::Rvalue::Cast( - mir::CastKind::PointerCoercion(PointerCoercion::Unsize), + mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) + | mir::CastKind::PointerCoercion(PointerCoercion::DynStar, _), ref operand, target_ty, - ) - | mir::Rvalue::Cast(mir::CastKind::DynStar, ref operand, target_ty) => { + ) => { // This isn't monomorphized yet so we can't tell what the actual types are -- just // add everything that may involve a vtable. let source_ty = operand.ty(self.body, self.tcx); @@ -96,7 +96,7 @@ impl<'tcx> Visitor<'tcx> for MentionedItemsVisitor<'_, 'tcx> { } // Similarly, record closures that are turned into function pointers. mir::Rvalue::Cast( - mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_)), + mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _), ref operand, _, ) => { @@ -106,7 +106,7 @@ impl<'tcx> Visitor<'tcx> for MentionedItemsVisitor<'_, 'tcx> { } // And finally, function pointer reification casts. mir::Rvalue::Cast( - mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer), + mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _), ref operand, _, ) => { diff --git a/compiler/rustc_mir_transform/src/promote_consts.rs b/compiler/rustc_mir_transform/src/promote_consts.rs index 59df99f858dcf..d963ca5c48502 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::cell::Cell; 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::visit::{MutVisitor, MutatingUseContext, PlaceContext, Vis 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 @@ impl<'a, 'tcx> Promoter<'a, 'tcx> { self.extra_statements.push((loc, promoted_ref_statement)); ( - Rvalue::Ref( - tcx.lifetimes.re_erased, - *borrow_kind, - Place { - local: mem::replace(&mut place.local, promoted_ref), - projection: List::empty(), - }, - ), + Rvalue::Ref(tcx.lifetimes.re_erased, *borrow_kind, Place { + local: mem::replace(&mut place.local, promoted_ref), + projection: List::empty(), + }), promoted_operand, ) }; assert_eq!(self.new_block(), START_BLOCK); - self.visit_rvalue( - &mut rvalue, - Location { block: START_BLOCK, statement_index: usize::MAX }, - ); + self.visit_rvalue(&mut rvalue, Location { + block: START_BLOCK, + statement_index: usize::MAX, + }); let span = self.promoted.span; self.assign(RETURN_PLACE, rvalue, span); diff --git a/compiler/rustc_mir_transform/src/ref_prop.rs b/compiler/rustc_mir_transform/src/ref_prop.rs index 4c3a99b79d4f2..a62a892716fbf 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 d80a4edecdf37..e6647edf3f50d 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::mir::{Body, TerminatorKind}; 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 99d1cd6f63ecf..b418ede42f06f 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 47d04d8a00bf0..e872878a751ed 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -14,8 +14,8 @@ use rustc_middle::ty::{ 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 c88953a1d1a20..71723f040b3b6 100644 --- a/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs +++ b/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs @@ -7,9 +7,10 @@ use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; 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, + BasicBlock, BasicBlockData, Body, CallSource, CastKind, CoercionSource, Const, ConstOperand, + ConstValue, Local, 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}; @@ -329,7 +330,7 @@ impl<'tcx> AsyncDestructorCtorShimBuilder<'tcx> { fn put_array_as_slice(&mut self, elem_ty: Ty<'tcx>) { let slice_ptr_ty = Ty::new_mut_ptr(self.tcx, Ty::new_slice(self.tcx, elem_ty)); self.put_temp_rvalue(Rvalue::Cast( - CastKind::PointerCoercion(PointerCoercion::Unsize), + CastKind::PointerCoercion(PointerCoercion::Unsize, CoercionSource::Implicit), Operand::Copy(Self::SELF_PTR.into()), slice_ptr_ty, )) @@ -452,19 +453,17 @@ impl<'tcx> AsyncDestructorCtorShimBuilder<'tcx> { } fn combine_sync_surface(&mut self) -> Ty<'tcx> { - self.apply_combinator( - 1, - LangItem::AsyncDropSurfaceDropInPlace, - &[self.self_ty.unwrap().into()], - ) + self.apply_combinator(1, LangItem::AsyncDropSurfaceDropInPlace, &[self + .self_ty + .unwrap() + .into()]) } fn combine_deferred_drop_in_place(&mut self) -> Ty<'tcx> { - self.apply_combinator( - 1, - LangItem::AsyncDropDeferredDropInPlace, - &[self.self_ty.unwrap().into()], - ) + self.apply_combinator(1, LangItem::AsyncDropDeferredDropInPlace, &[self + .self_ty + .unwrap() + .into()]) } fn combine_fuse(&mut self, inner_future_ty: Ty<'tcx>) -> Ty<'tcx> { @@ -484,11 +483,11 @@ impl<'tcx> AsyncDestructorCtorShimBuilder<'tcx> { } fn combine_either(&mut self, other: Ty<'tcx>, matched: Ty<'tcx>) -> Ty<'tcx> { - self.apply_combinator( - 4, - LangItem::AsyncDropEither, - &[other.into(), matched.into(), self.self_ty.unwrap().into()], - ) + self.apply_combinator(4, LangItem::AsyncDropEither, &[ + other.into(), + matched.into(), + self.self_ty.unwrap().into(), + ]) } fn return_(mut self) -> Body<'tcx> { diff --git a/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs b/compiler/rustc_mir_transform/src/simplify_comparison_integral.rs index e8d8335b136b5..26496b7f3fe19 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 @@ impl<'tcx> crate::MirPass<'tcx> for SimplifyComparisonIntegral { // if we have StorageDeads to remove then make sure to insert them at the top of // each target for bb_idx in new_targets.all_targets() { - storage_deads_to_insert.push(( - *bb_idx, - Statement { - source_info: terminator.source_info, - kind: StatementKind::StorageDead(opt.to_switch_on.local), - }, - )); + storage_deads_to_insert.push((*bb_idx, Statement { + source_info: terminator.source_info, + kind: StatementKind::StorageDead(opt.to_switch_on.local), + })); } } diff --git a/compiler/rustc_mir_transform/src/single_use_consts.rs b/compiler/rustc_mir_transform/src/single_use_consts.rs index 26059268c37d4..9884b6dd1c35e 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 e6dd2cfd862d8..2de0059bc7fd7 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 ba64216f9e1ca..84df666e34a72 100644 --- a/compiler/rustc_mir_transform/src/ssa.rs +++ b/compiler/rustc_mir_transform/src/ssa.rs @@ -159,11 +159,10 @@ impl SsaLocals { ) { for &local in &self.assignment_order { match self.assignments[local] { - Set1::One(DefLocation::Argument) => f( - local, - AssignedValue::Arg, - Location { block: START_BLOCK, statement_index: 0 }, - ), + Set1::One(DefLocation::Argument) => f(local, AssignedValue::Arg, Location { + block: START_BLOCK, + statement_index: 0, + }), Set1::One(DefLocation::Assignment(loc)) => { let bb = &mut basic_blocks[loc.block]; // `loc` must point to a direct assignment to `local`. diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index e5837b1b475ad..eda0b8c75f322 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 @@ use rustc_middle::ty::{ 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}; @@ -1128,12 +1128,9 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { Rvalue::Cast(kind, operand, target_type) => { let op_ty = operand.ty(self.body, self.tcx); match kind { - CastKind::DynStar => { - // FIXME(dyn-star): make sure nothing needs to be done here. - } // FIXME: Add Checks for these CastKind::PointerWithExposedProvenance | CastKind::PointerExposeProvenance => {} - CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer) => { + CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _) => { // FIXME: check signature compatibility. check_kinds!( op_ty, @@ -1146,7 +1143,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ty::FnPtr(..) ); } - CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer) => { + CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => { // FIXME: check safety and signature compatibility. check_kinds!( op_ty, @@ -1159,7 +1156,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ty::FnPtr(..) ); } - CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(..)) => { + CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(..), _) => { // FIXME: check safety, captures, and signature compatibility. check_kinds!( op_ty, @@ -1172,7 +1169,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { ty::FnPtr(..) ); } - CastKind::PointerCoercion(PointerCoercion::MutToConstPointer) => { + CastKind::PointerCoercion(PointerCoercion::MutToConstPointer, _) => { // FIXME: check same pointee? check_kinds!( op_ty, @@ -1188,7 +1185,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { self.fail(location, format!("After borrowck, MIR disallows {kind:?}")); } } - CastKind::PointerCoercion(PointerCoercion::ArrayToPointer) => { + CastKind::PointerCoercion(PointerCoercion::ArrayToPointer, _) => { // FIXME: Check pointee types check_kinds!( op_ty, @@ -1204,10 +1201,13 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { self.fail(location, format!("After borrowck, MIR disallows {kind:?}")); } } - CastKind::PointerCoercion(PointerCoercion::Unsize) => { + CastKind::PointerCoercion(PointerCoercion::Unsize, _) => { // This is used for all `CoerceUnsized` types, // not just pointers/references, so is hard to check. } + CastKind::PointerCoercion(PointerCoercion::DynStar, _) => { + // FIXME(dyn-star): make sure nothing needs to be done here. + } CastKind::IntToInt | CastKind::IntToFloat => { let input_valid = op_ty.is_integral() || op_ty.is_char() || op_ty.is_bool(); let target_valid = target_type.is_numeric() || target_type.is_char(); diff --git a/compiler/rustc_monomorphize/src/collector.rs b/compiler/rustc_monomorphize/src/collector.rs index c3f228962005b..276098a840079 100644 --- a/compiler/rustc_monomorphize/src/collector.rs +++ b/compiler/rustc_monomorphize/src/collector.rs @@ -210,7 +210,7 @@ mod move_check; 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::middle::codegen_fn_attrs::CodegenFnAttrFlags; 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::ty::{ }; 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}; @@ -665,11 +665,11 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { // have to instantiate all methods of the trait being cast to, so we // can build the appropriate vtable. mir::Rvalue::Cast( - mir::CastKind::PointerCoercion(PointerCoercion::Unsize), + mir::CastKind::PointerCoercion(PointerCoercion::Unsize, _) + | mir::CastKind::PointerCoercion(PointerCoercion::DynStar, _), ref operand, target_ty, - ) - | mir::Rvalue::Cast(mir::CastKind::DynStar, ref operand, target_ty) => { + ) => { let source_ty = operand.ty(self.body, self.tcx); // *Before* monomorphizing, record that we already handled this mention. self.used_mentioned_items @@ -694,7 +694,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { } } mir::Rvalue::Cast( - mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer), + mir::CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer, _), ref operand, _, ) => { @@ -705,7 +705,7 @@ impl<'a, 'tcx> MirVisitor<'tcx> for MirUsedCollector<'a, 'tcx> { visit_fn_use(self.tcx, fn_ty, false, span, self.used_items); } mir::Rvalue::Cast( - mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_)), + mir::CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(_), _), ref operand, _, ) => { @@ -1175,15 +1175,15 @@ fn collect_alloc<'tcx>(tcx: TyCtxt<'tcx>, alloc_id: AllocId, output: &mut MonoIt output.push(create_fn_mono_item(tcx, instance, DUMMY_SP)); } } - GlobalAlloc::VTable(ty, trait_ref) => { - let alloc_id = tcx.vtable_allocation((ty, trait_ref)); + GlobalAlloc::VTable(ty, dyn_ty) => { + let alloc_id = tcx.vtable_allocation((ty, dyn_ty.principal())); collect_alloc(tcx, alloc_id, output) } } } fn assoc_fn_of_type<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, fn_ident: Ident) -> Option { - for impl_def_id in tcx.inherent_impls(def_id).ok()? { + for impl_def_id in tcx.inherent_impls(def_id) { if let Some(new) = tcx.associated_items(impl_def_id).find_by_name_and_kind( tcx, fn_ident, diff --git a/compiler/rustc_monomorphize/src/collector/move_check.rs b/compiler/rustc_monomorphize/src/collector/move_check.rs index 851f86e86b8e8..b86ef1e737328 100644 --- a/compiler/rustc_monomorphize/src/collector/move_check.rs +++ b/compiler/rustc_monomorphize/src/collector/move_check.rs @@ -132,12 +132,11 @@ impl<'a, 'tcx> MirUsedCollector<'a, 'tcx> { // but correct span? This would make the lint at least accept crate-level lint attributes. return; }; - self.tcx.emit_node_span_lint( - LARGE_ASSIGNMENTS, - lint_root, + 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 2d9dbdbaec23f..1c1e6164f2eb0 100644 --- a/compiler/rustc_monomorphize/src/partitioning.rs +++ b/compiler/rustc_monomorphize/src/partitioning.rs @@ -101,10 +101,10 @@ use std::path::{Path, PathBuf}; 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::print::{characteristic_def_id_of_type, with_no_trimmed_pat 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 @@ where } let size_estimate = mono_item.size_estimate(cx.tcx); - cgu.items_mut() - .insert(mono_item, MonoItemData { inlined: false, linkage, visibility, size_estimate }); + cgu.items_mut().insert(mono_item, MonoItemData { + inlined: false, + linkage, + visibility, + size_estimate, + }); // Get all inlined items that are reachable from `mono_item` without // going via another root item. This includes drop-glue, functions from diff --git a/compiler/rustc_monomorphize/src/polymorphize.rs b/compiler/rustc_monomorphize/src/polymorphize.rs index c65ad9fa67e53..e049fe996645a 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 6c9a6011144cd..520afbeb645c2 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::fold::TypeFoldable; 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 a57338acaab29..5c1a7852dc0b4 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::data_structures::HashMap; 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 4d743c0519022..252a9ed1a2e79 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::delegate::SolverDelegate; 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 15b123ebdf934..12ad0724b5cb1 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::delegate::SolverDelegate; 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 @@ where // Replace the goal with an unconstrained infer var, so the // RHS does not affect projection candidate assembly. let unconstrained_rhs = self.next_term_infer_of_kind(goal.predicate.term); - let unconstrained_goal = goal.with( - cx, - ty::NormalizesTo { alias: goal.predicate.alias, term: unconstrained_rhs }, - ); + let unconstrained_goal = goal.with(cx, ty::NormalizesTo { + alias: goal.predicate.alias, + term: unconstrained_rhs, + }); let (NestedNormalizationGoals(nested_goals), _, certainty) = self.evaluate_goal_raw( GoalEvaluationKind::Nested, diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/probe.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/probe.rs index e459d5cbe5889..be69a6e84ea13 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 tracing::instrument; 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 742d45de7d3de..85474bf37b448 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 rustc_type_ir::{self as ty, Interner}; 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 17b6ec7e2bb2c..fc9c634942b70 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 @@ where let pred = tupled_inputs_and_output .map_bound(|(inputs, output)| ty::ProjectionPredicate { - projection_term: ty::AliasTerm::new( - cx, - goal.predicate.def_id(), - [goal.predicate.self_ty(), inputs], - ), + projection_term: ty::AliasTerm::new(cx, goal.predicate.def_id(), [ + goal.predicate.self_ty(), + inputs, + ]), term: output.into(), }) .upcast(cx); @@ -396,26 +395,21 @@ where .is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CallOnceFuture) { ( - ty::AliasTerm::new( - cx, - goal.predicate.def_id(), - [goal.predicate.self_ty(), tupled_inputs_ty], - ), + ty::AliasTerm::new(cx, goal.predicate.def_id(), [ + goal.predicate.self_ty(), + tupled_inputs_ty, + ]), output_coroutine_ty.into(), ) } else if cx .is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CallRefFuture) { ( - ty::AliasTerm::new( - cx, - goal.predicate.def_id(), - [ - I::GenericArg::from(goal.predicate.self_ty()), - tupled_inputs_ty.into(), - env_region.into(), - ], - ), + ty::AliasTerm::new(cx, goal.predicate.def_id(), [ + I::GenericArg::from(goal.predicate.self_ty()), + tupled_inputs_ty.into(), + env_region.into(), + ]), output_coroutine_ty.into(), ) } else if cx.is_lang_item( @@ -423,14 +417,10 @@ where TraitSolverLangItem::AsyncFnOnceOutput, ) { ( - ty::AliasTerm::new( - cx, - goal.predicate.def_id(), - [ - I::GenericArg::from(goal.predicate.self_ty()), - tupled_inputs_ty.into(), - ], - ), + ty::AliasTerm::new(cx, goal.predicate.def_id(), [ + I::GenericArg::from(goal.predicate.self_ty()), + tupled_inputs_ty.into(), + ]), coroutine_return_ty.into(), ) } else { @@ -556,11 +546,10 @@ where // and opaque types: If the `self_ty` is `Sized`, then the metadata is `()`. // FIXME(ptr_metadata): This impl overlaps with the other impls and shouldn't // exist. Instead, `Pointee` should be a supertrait of `Sized`. - let sized_predicate = ty::TraitRef::new( - cx, - cx.require_lang_item(TraitSolverLangItem::Sized), - [I::GenericArg::from(goal.predicate.self_ty())], - ); + let sized_predicate = + ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Sized), [ + I::GenericArg::from(goal.predicate.self_ty()), + ]); // FIXME(-Znext-solver=coinductive): Should this be `GoalSource::ImplWhereBound`? ecx.add_goal(GoalSource::Misc, goal.with(cx, sized_predicate)); Ty::new_unit(cx) @@ -731,11 +720,10 @@ where CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, ty::ProjectionPredicate { - projection_term: ty::AliasTerm::new( - ecx.cx(), - goal.predicate.def_id(), - [self_ty, coroutine.resume_ty()], - ), + projection_term: ty::AliasTerm::new(ecx.cx(), goal.predicate.def_id(), [ + self_ty, + coroutine.resume_ty(), + ]), term, } .upcast(cx), diff --git a/compiler/rustc_next_trait_solver/src/solve/search_graph.rs b/compiler/rustc_next_trait_solver/src/solve/search_graph.rs index 81c89fad8e8a0..e47cc03f5adf9 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 73d9b5e8a4ee7..781ca127e151e 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::fast_reject::DeepRejectCtxt; 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 @@ where )?; 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 @@ where GoalSource::ImplWhereBound, goal.with( cx, - ty::TraitRef::new( - cx, - cx.require_lang_item(TraitSolverLangItem::Unsize), - [a_tail_ty, b_tail_ty], - ), + ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Unsize), [ + a_tail_ty, b_tail_ty, + ]), ), ); self.probe_builtin_trait_candidate(BuiltinImplSource::Misc) @@ -1069,11 +1064,9 @@ where GoalSource::ImplWhereBound, goal.with( cx, - ty::TraitRef::new( - cx, - cx.require_lang_item(TraitSolverLangItem::Unsize), - [a_last_ty, b_last_ty], - ), + ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Unsize), [ + a_last_ty, b_last_ty, + ]), ), ); self.probe_builtin_trait_candidate(BuiltinImplSource::TupleUnsizing) diff --git a/compiler/rustc_parse/src/errors.rs b/compiler/rustc_parse/src/errors.rs index e9fe2e6c1dd12..20bcefd4fe1e7 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 4d5d1ce099ec4..41108c91f2ebe 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 898c4779b08ae..3e46fc93fa49d 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -8,10 +8,10 @@ use rustc_errors::codes::*; 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 @@ impl<'psess, 'src> StringReader<'psess, 'src> { } 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 c83d8bf4021ee..d35c9c7bae7d6 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -5,7 +5,7 @@ use rustc_errors::{Applicability, PErr}; 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 efa53f0962b78..2e066f0179c3f 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 788bb732ef722..f7a8b8780edc4 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -18,7 +18,7 @@ use std::path::Path; 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 @@ pub const MACRO_ARGUMENTS: Option<&str> = Some("macro arguments"); #[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 6a241be0a1560..8bd615e6d7913 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_ast::{self as ast, AttrVec, Attribute, HasAttrs, HasTokens}; 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 @@ impl<'a> Parser<'a> { 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 @@ impl<'a> Parser<'a> { // 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 @@ impl<'a> Parser<'a> { /// 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 @@ fn make_attr_token_stream( for flat_token in iter { match flat_token { FlatToken::Token((Token { kind: TokenKind::OpenDelim(delim), span }, spacing)) => { - stack_rest.push(mem::replace( - &mut stack_top, - FrameData { open_delim_sp: Some((delim, span, spacing)), inner: vec![] }, - )); + stack_rest.push(mem::replace(&mut stack_top, FrameData { + open_delim_sp: Some((delim, span, spacing)), + inner: vec![], + })); } FlatToken::Token((Token { kind: TokenKind::CloseDelim(delim), span }, spacing)) => { let frame_data = mem::replace(&mut stack_top, stack_rest.pop().unwrap()); @@ -513,18 +516,17 @@ fn make_attr_token_stream( } } - 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 fd488cf1d317a..f32307f6ed4d8 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -15,15 +15,15 @@ use rustc_ast::{ 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 @@ impl<'a> Parser<'a> { let span = self.token.span.with_lo(pos).with_hi(pos); err.span_suggestion_verbose( span, - format!( - "add a space before {} to write a regular comment", - match (kind, style) { - (token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`", - (token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`", - (token::CommentKind::Line, ast::AttrStyle::Outer) => "the last `/`", - (token::CommentKind::Block, ast::AttrStyle::Outer) => "the last `*`", - }, - ), + format!("add a space before {} to write a regular comment", match (kind, style) { + (token::CommentKind::Line, ast::AttrStyle::Inner) => "`!`", + (token::CommentKind::Block, ast::AttrStyle::Inner) => "`!`", + (token::CommentKind::Line, ast::AttrStyle::Outer) => "the last `/`", + (token::CommentKind::Block, ast::AttrStyle::Outer) => "the last `*`", + },), " ".to_string(), Applicability::MachineApplicable, ); @@ -1936,14 +1933,13 @@ impl<'a> Parser<'a> { (token::Eof, None) => (self.prev_token.span, self.token.span), _ => (self.prev_token.span.shrink_to_hi(), self.token.span), }; - let msg = format!( - "expected `{}`, found {}", - token_str, - match (&self.token.kind, self.subparser_name) { - (token::Eof, Some(origin)) => format!("end of {origin}"), - _ => this_token_str, - }, - ); + let msg = format!("expected `{}`, found {}", token_str, match ( + &self.token.kind, + self.subparser_name + ) { + (token::Eof, Some(origin)) => format!("end of {origin}"), + _ => this_token_str, + },); let mut err = self.dcx().struct_span_err(sp, msg); let label_exp = format!("expected `{token_str}`"); let sm = self.psess.source_map(); @@ -2864,27 +2860,25 @@ impl<'a> Parser<'a> { PatKind::Ident(BindingMode::NONE, ident, None) => { match &first_pat.kind { PatKind::Ident(_, old_ident, _) => { - let path = PatKind::Path( - None, - Path { - span: new_span, - segments: thin_vec![ - PathSegment::from_ident(*old_ident), - PathSegment::from_ident(*ident), - ], - tokens: None, - }, - ); + let path = PatKind::Path(None, Path { + span: new_span, + segments: thin_vec![ + PathSegment::from_ident(*old_ident), + PathSegment::from_ident(*ident), + ], + tokens: None, + }); first_pat = self.mk_pat(new_span, path); show_sugg = true; } PatKind::Path(old_qself, old_path) => { let mut segments = old_path.segments.clone(); segments.push(PathSegment::from_ident(*ident)); - let path = PatKind::Path( - old_qself.clone(), - Path { span: new_span, segments, tokens: None }, - ); + let path = PatKind::Path(old_qself.clone(), Path { + span: new_span, + segments, + tokens: None, + }); first_pat = self.mk_pat(new_span, path); show_sugg = true; } diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index f19cba4c1bf59..0ac6133e8289f 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -10,25 +10,25 @@ use rustc_ast::ptr::P; 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 @@ impl<'a> Parser<'a> { // Check if an illegal postfix operator has been added after the cast. // If the resulting expression is not a cast, it is an illegal postfix operator. if !matches!(with_postfix.kind, ExprKind::Cast(_, _)) { - let msg = format!( - "cast cannot be followed by {}", - match with_postfix.kind { - ExprKind::Index(..) => "indexing", - ExprKind::Try(_) => "`?`", - ExprKind::Field(_, _) => "a field access", - ExprKind::MethodCall(_) => "a method call", - ExprKind::Call(_, _) => "a function call", - ExprKind::Await(_, _) => "`.await`", - ExprKind::Match(_, _, MatchKind::Postfix) => "a postfix match", - ExprKind::Err(_) => return Ok(with_postfix), - _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"), - } - ); + let msg = format!("cast cannot be followed by {}", match with_postfix.kind { + ExprKind::Index(..) => "indexing", + ExprKind::Try(_) => "`?`", + ExprKind::Field(_, _) => "a field access", + ExprKind::MethodCall(_) => "a method call", + ExprKind::Call(_, _) => "a function call", + ExprKind::Await(_, _) => "`.await`", + ExprKind::Match(_, _, MatchKind::Postfix) => "a postfix match", + ExprKind::Err(_) => return Ok(with_postfix), + _ => unreachable!("parse_dot_or_call_expr_with_ shouldn't produce this"), + }); let mut err = self.dcx().struct_span_err(span, msg); let suggest_parens = |err: &mut Diag<'_>| { @@ -2844,10 +2841,13 @@ impl<'a> Parser<'a> { .emit_err(errors::MissingExpressionInForLoop { span: expr.span.shrink_to_lo() }); let err_expr = self.mk_expr(expr.span, ExprKind::Err(guar)); let block = self.mk_block(thin_vec![], BlockCheckMode::Default, self.prev_token.span); - return Ok(self.mk_expr( - lo.to(self.prev_token.span), - ExprKind::ForLoop { pat, iter: err_expr, body: block, label: opt_label, kind }, - )); + return Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::ForLoop { + pat, + iter: err_expr, + body: block, + label: opt_label, + kind, + })); } let (attrs, loop_block) = self.parse_inner_attrs_and_block()?; diff --git a/compiler/rustc_parse/src/parser/generics.rs b/compiler/rustc_parse/src/parser/generics.rs index af3b6f740e3d7..b9256daa72525 100644 --- a/compiler/rustc_parse/src/parser/generics.rs +++ b/compiler/rustc_parse/src/parser/generics.rs @@ -1,10 +1,10 @@ use ast::token::Delimiter; use rustc_ast::{ - self as ast, token, AttrVec, GenericBounds, GenericParam, GenericParamKind, TyKind, WhereClause, + self as ast, AttrVec, GenericBounds, GenericParam, GenericParamKind, TyKind, WhereClause, token, }; use rustc_errors::{Applicability, PResult}; -use rustc_span::symbol::{kw, Ident}; use rustc_span::Span; +use rustc_span::symbol::{Ident, kw}; use thin_vec::ThinVec; use super::{ForceCollect, Parser, Trailing, UsePreAttrPos}; diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index afd9871a635ec..9fc82d84225cc 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -10,15 +10,15 @@ use rustc_ast::util::case::Case; use rustc_ast::{self as ast}; use rustc_ast_pretty::pprust; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, Applicability, PResult, StashKey}; +use rustc_errors::{Applicability, PResult, StashKey, struct_span_code_err}; use rustc_span::edit_distance::edit_distance; use rustc_span::edition::Edition; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{source_map, ErrorGuaranteed, Span, DUMMY_SP}; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, source_map}; +use thin_vec::{ThinVec, thin_vec}; use tracing::debug; -use super::diagnostics::{dummy_arg, ConsumeClosingDelim}; +use super::diagnostics::{ConsumeClosingDelim, dummy_arg}; use super::ty::{AllowPlus, RecoverQPath, RecoverReturnSign}; use super::{ AttrWrapper, FollowedByType, ForceCollect, Parser, PathStyle, Trailing, UsePreAttrPos, @@ -1897,10 +1897,10 @@ impl<'a> Parser<'a> { // Try to recover extra trailing angle brackets if let TyKind::Path(_, Path { segments, .. }) = &a_var.ty.kind { if let Some(last_segment) = segments.last() { - let guar = self.check_trailing_angle_brackets( - last_segment, - &[&token::Comma, &token::CloseDelim(Delimiter::Brace)], - ); + let guar = self.check_trailing_angle_brackets(last_segment, &[ + &token::Comma, + &token::CloseDelim(Delimiter::Brace), + ]); if let Some(_guar) = guar { // Handle a case like `Vec>,` where we can continue parsing fields // after the comma diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 3b58b2337f36e..77ad4fdeeb17b 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -27,9 +27,9 @@ use rustc_ast::tokenstream::{ }; use rustc_ast::util::case::Case; use rustc_ast::{ - self as ast, AnonConst, AttrArgs, AttrArgsEq, AttrId, ByRef, Const, CoroutineKind, DelimArgs, - Expr, ExprKind, Extern, HasAttrs, HasTokens, Mutability, Recovered, Safety, StrLit, Visibility, - VisibilityKind, DUMMY_NODE_ID, + self as ast, AnonConst, AttrArgs, AttrArgsEq, AttrId, ByRef, Const, CoroutineKind, + DUMMY_NODE_ID, DelimArgs, Expr, ExprKind, Extern, HasAttrs, HasTokens, Mutability, Recovered, + Safety, StrLit, Visibility, VisibilityKind, }; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashMap; @@ -37,8 +37,8 @@ use rustc_data_structures::sync::Lrc; use rustc_errors::{Applicability, Diag, FatalError, MultiSpan, PResult}; use rustc_index::interval::IntervalSet; use rustc_session::parse::ParseSess; -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 thin_vec::ThinVec; use tracing::debug; @@ -146,21 +146,25 @@ pub struct Parser<'a> { token_cursor: TokenCursor, // The number of calls to `bump`, i.e. the position in the token stream. num_bump_calls: u32, - // During parsing we may sometimes need to 'unglue' a glued token into two - // component tokens (e.g. '>>' into '>' and '>), so the parser can consume - // them one at a time. This process bypasses the normal capturing mechanism - // (e.g. `num_bump_calls` will not be incremented), since the 'unglued' - // tokens due not exist in the original `TokenStream`. + // During parsing we may sometimes need to "unglue" a glued token into two + // or three component tokens (e.g. `>>` into `>` and `>`, or `>>=` into `>` + // and `>` and `=`), so the parser can consume them one at a time. This + // process bypasses the normal capturing mechanism (e.g. `num_bump_calls` + // will not be incremented), since the "unglued" tokens due not exist in + // the original `TokenStream`. // - // If we end up consuming both unglued tokens, this is not an issue. We'll - // end up capturing the single 'glued' token. + // If we end up consuming all the component tokens, this is not an issue, + // because we'll end up capturing the single "glued" token. // - // However, sometimes we may want to capture just the first 'unglued' + // However, sometimes we may want to capture not all of the original // token. For example, capturing the `Vec` in `Option>` // requires us to unglue the trailing `>>` token. The `break_last_token` - // field is used to track this token. It gets appended to the captured + // field is used to track these tokens. They get appended to the captured // stream when we evaluate a `LazyAttrTokenStream`. - break_last_token: bool, + // + // This value is always 0, 1, or 2. It can only reach 2 when splitting + // `>>=` or `<<=`. + break_last_token: u32, /// This field is used to keep track of how many left angle brackets we have seen. This is /// required in order to detect extra leading left angle brackets (`<` characters) and error /// appropriately. @@ -453,7 +457,7 @@ impl<'a> Parser<'a> { expected_tokens: Vec::new(), token_cursor: TokenCursor { tree_cursor: stream.into_trees(), stack: Vec::new() }, num_bump_calls: 0, - break_last_token: false, + break_last_token: 0, unmatched_angle_bracket_count: 0, angle_bracket_nesting: 0, last_unexpected_token_span: None, @@ -773,7 +777,7 @@ impl<'a> Parser<'a> { self.bump(); return true; } - match self.token.kind.break_two_token_op() { + match self.token.kind.break_two_token_op(1) { Some((first, second)) if first == expected => { let first_span = self.psess.source_map().start_point(self.token.span); let second_span = self.token.span.with_lo(first_span.hi()); @@ -783,8 +787,8 @@ impl<'a> Parser<'a> { // // If we consume any additional tokens, then this token // is not needed (we'll capture the entire 'glued' token), - // and `bump` will set this field to `None` - self.break_last_token = true; + // and `bump` will set this field to 0. + self.break_last_token += 1; // Use the spacing of the glued token as the spacing of the // unglued second token. self.bump_with((Token::new(second, second_span), self.token_spacing)); @@ -1148,10 +1152,9 @@ impl<'a> Parser<'a> { // than `.0`/`.1` access. let mut next = self.token_cursor.inlined_next(); self.num_bump_calls += 1; - // We've retrieved an token from the underlying - // cursor, so we no longer need to worry about - // an unglued token. See `break_and_eat` for more details - self.break_last_token = false; + // We got a token from the underlying cursor and no longer need to + // worry about an unglued token. See `break_and_eat` for more details. + self.break_last_token = 0; if next.0.span.is_dummy() { // Tweak the location for better diagnostics, but keep syntactic context intact. let fallback_span = self.token.span; diff --git a/compiler/rustc_parse/src/parser/nonterminal.rs b/compiler/rustc_parse/src/parser/nonterminal.rs index 44b169c881e12..43c3de90d9d99 100644 --- a/compiler/rustc_parse/src/parser/nonterminal.rs +++ b/compiler/rustc_parse/src/parser/nonterminal.rs @@ -1,13 +1,13 @@ +use rustc_ast::HasTokens; use rustc_ast::ptr::P; use rustc_ast::token::Nonterminal::*; use rustc_ast::token::NtExprKind::*; use rustc_ast::token::NtPatKind::*; use rustc_ast::token::{self, Delimiter, NonterminalKind, Token}; -use rustc_ast::HasTokens; use rustc_ast_pretty::pprust; use rustc_data_structures::sync::Lrc; use rustc_errors::PResult; -use rustc_span::symbol::{kw, Ident}; +use rustc_span::symbol::{Ident, kw}; use crate::errors::UnexpectedNonterminal; use crate::parser::pat::{CommaRecoveryMode, RecoverColon, RecoverComma}; diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 647df25c82ef7..bd2ffaa0a892a 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -10,10 +10,10 @@ use rustc_ast::{ use rustc_ast_pretty::pprust; use rustc_errors::{Applicability, Diag, DiagArgValue, PResult, StashKey}; use rustc_session::errors::ExprParenthesesNeeded; -use rustc_span::source_map::{respan, Spanned}; -use rustc_span::symbol::{kw, sym, Ident}; +use rustc_span::source_map::{Spanned, respan}; +use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{BytePos, ErrorGuaranteed, Span}; -use thin_vec::{thin_vec, ThinVec}; +use thin_vec::{ThinVec, thin_vec}; use super::{ForceCollect, Parser, PathStyle, Restrictions, Trailing, UsePreAttrPos}; use crate::errors::{ @@ -27,7 +27,7 @@ use crate::errors::{ UnexpectedLifetimeInPattern, UnexpectedParenInRangePat, UnexpectedParenInRangePatSugg, UnexpectedVertVertBeforeFunctionParam, UnexpectedVertVertInPattern, WrapInParens, }; -use crate::parser::expr::{could_be_unclosed_char_literal, DestructuredFloat}; +use crate::parser::expr::{DestructuredFloat, could_be_unclosed_char_literal}; use crate::{maybe_recover_from_interpolated_ty_qpath, maybe_whole}; #[derive(PartialEq, Copy, Clone)] diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 961679b1f562f..162ff3b94de52 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -9,7 +9,7 @@ use rustc_ast::{ Path, PathSegment, QSelf, }; use rustc_errors::{Applicability, Diag, PResult}; -use rustc_span::symbol::{kw, sym, Ident}; +use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{BytePos, Span}; use thin_vec::ThinVec; use tracing::debug; @@ -107,10 +107,11 @@ impl<'a> Parser<'a> { self.parse_path_segments(&mut path.segments, style, None)?; } - Ok(( - qself, - Path { segments: path.segments, span: lo.to(self.prev_token.span), tokens: None }, - )) + Ok((qself, Path { + segments: path.segments, + span: lo.to(self.prev_token.span), + tokens: None, + })) } /// Recover from an invalid single colon, when the user likely meant a qualified path. @@ -487,16 +488,13 @@ impl<'a> Parser<'a> { error.span_suggestion_verbose( prev_token_before_parsing.span, - format!( - "consider removing the `::` here to {}", - match style { - PathStyle::Expr => "call the expression", - PathStyle::Pat => "turn this into a tuple struct pattern", - _ => { - return; - } + format!("consider removing the `::` here to {}", match style { + PathStyle::Expr => "call the expression", + PathStyle::Pat => "turn this into a tuple struct pattern", + _ => { + return; } - ), + }), "", Applicability::MaybeIncorrect, ); diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 92fba89d28a1f..b7cdae3e3e123 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -7,13 +7,13 @@ use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter, TokenKind}; use rustc_ast::util::classify::{self, TrailingBrace}; use rustc_ast::{ - AttrStyle, AttrVec, Block, BlockCheckMode, Expr, ExprKind, HasAttrs, Local, LocalKind, MacCall, - MacCallStmt, MacStmtStyle, Recovered, Stmt, StmtKind, DUMMY_NODE_ID, + AttrStyle, AttrVec, Block, BlockCheckMode, DUMMY_NODE_ID, Expr, ExprKind, HasAttrs, Local, + LocalKind, MacCall, MacCallStmt, MacStmtStyle, Recovered, Stmt, StmtKind, }; use rustc_errors::{Applicability, Diag, PResult}; -use rustc_span::symbol::{kw, sym, Ident}; +use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{BytePos, ErrorGuaranteed, Span}; -use thin_vec::{thin_vec, ThinVec}; +use thin_vec::{ThinVec, thin_vec}; use super::attr::InnerAttrForbiddenReason; use super::diagnostics::AttemptLocalParseRecovery; @@ -417,20 +417,14 @@ impl<'a> Parser<'a> { fn check_let_else_init_trailing_brace(&self, init: &ast::Expr) { if let Some(trailing) = classify::expr_trailing_brace(init) { let (span, sugg) = match trailing { - TrailingBrace::MacCall(mac) => ( - mac.span(), - errors::WrapInParentheses::MacroArgs { - left: mac.args.dspan.open, - right: mac.args.dspan.close, - }, - ), - TrailingBrace::Expr(expr) => ( - expr.span, - errors::WrapInParentheses::Expression { - left: expr.span.shrink_to_lo(), - right: expr.span.shrink_to_hi(), - }, - ), + TrailingBrace::MacCall(mac) => (mac.span(), errors::WrapInParentheses::MacroArgs { + left: mac.args.dspan.open, + right: mac.args.dspan.close, + }), + TrailingBrace::Expr(expr) => (expr.span, errors::WrapInParentheses::Expression { + left: expr.span.shrink_to_lo(), + right: expr.span.shrink_to_hi(), + }), }; self.dcx().emit_err(errors::InvalidCurlyInLetElse { span: span.with_lo(span.hi() - BytePos(1)), diff --git a/compiler/rustc_parse/src/parser/tests.rs b/compiler/rustc_parse/src/parser/tests.rs index cb8e8d309887b..92684505ab0ba 100644 --- a/compiler/rustc_parse/src/parser/tests.rs +++ b/compiler/rustc_parse/src/parser/tests.rs @@ -9,15 +9,15 @@ use ast::token::IdentIsRaw; use rustc_ast::ptr::P; use rustc_ast::token::{self, Delimiter, Token}; use rustc_ast::tokenstream::{DelimSpacing, DelimSpan, Spacing, TokenStream, TokenTree}; -use rustc_ast::{self as ast, visit, PatKind}; +use rustc_ast::{self as ast, PatKind, visit}; use rustc_ast_pretty::pprust::item_to_string; use rustc_data_structures::sync::Lrc; use rustc_errors::emitter::HumanEmitter; use rustc_errors::{DiagCtxt, MultiSpan, PResult}; use rustc_session::parse::ParseSess; use rustc_span::source_map::{FilePathMapping, SourceMap}; -use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_span::{create_default_session_globals_then, BytePos, FileName, Pos, Span}; +use rustc_span::symbol::{Symbol, kw, sym}; +use rustc_span::{BytePos, FileName, Pos, Span, create_default_session_globals_then}; use termcolor::WriteColor; use crate::parser::{ForceCollect, Parser}; diff --git a/compiler/rustc_parse/src/parser/tokenstream/tests.rs b/compiler/rustc_parse/src/parser/tokenstream/tests.rs index d518dfee2b26e..efe266f529057 100644 --- a/compiler/rustc_parse/src/parser/tokenstream/tests.rs +++ b/compiler/rustc_parse/src/parser/tokenstream/tests.rs @@ -1,6 +1,6 @@ use rustc_ast::token::{self, IdentIsRaw}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; -use rustc_span::{create_default_session_globals_then, BytePos, Span, Symbol}; +use rustc_span::{BytePos, Span, Symbol, create_default_session_globals_then}; use crate::parser::tests::string_to_stream; diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index 66019ffbc0ab9..a8ed8b5df9c00 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -2,14 +2,14 @@ use rustc_ast::ptr::P; use rustc_ast::token::{self, BinOpToken, Delimiter, IdentIsRaw, Token, TokenKind}; use rustc_ast::util::case::Case; use rustc_ast::{ - self as ast, BareFnTy, BoundAsyncness, BoundConstness, BoundPolarity, FnRetTy, GenericBound, - GenericBounds, GenericParam, Generics, Lifetime, MacCall, MutTy, Mutability, PolyTraitRef, - PreciseCapturingArg, TraitBoundModifiers, TraitObjectSyntax, Ty, TyKind, DUMMY_NODE_ID, + self as ast, BareFnTy, BoundAsyncness, BoundConstness, BoundPolarity, DUMMY_NODE_ID, FnRetTy, + GenericBound, GenericBounds, GenericParam, Generics, Lifetime, MacCall, MutTy, Mutability, + PolyTraitRef, PreciseCapturingArg, TraitBoundModifiers, TraitObjectSyntax, Ty, TyKind, }; use rustc_errors::{Applicability, PResult}; -use rustc_span::symbol::{kw, sym, Ident}; +use rustc_span::symbol::{Ident, kw, sym}; use rustc_span::{ErrorGuaranteed, Span, Symbol}; -use thin_vec::{thin_vec, ThinVec}; +use thin_vec::{ThinVec, thin_vec}; use super::{Parser, PathStyle, SeqSep, TokenType, Trailing}; use crate::errors::{ diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index f2121c3243aa4..b15d1edf79cda 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -7,12 +7,12 @@ use rustc_ast::{ NestedMetaItem, Safety, }; use rustc_errors::{Applicability, FatalError, PResult}; -use rustc_feature::{AttributeSafety, AttributeTemplate, BuiltinAttribute, BUILTIN_ATTRIBUTE_MAP}; +use rustc_feature::{AttributeSafety, AttributeTemplate, BUILTIN_ATTRIBUTE_MAP, BuiltinAttribute}; use rustc_session::errors::report_lit_error; -use rustc_session::lint::builtin::{ILL_FORMED_ATTRIBUTE_INPUT, UNSAFE_ATTR_OUTSIDE_UNSAFE}; use rustc_session::lint::BuiltinLintDiag; +use rustc_session::lint::builtin::{ILL_FORMED_ATTRIBUTE_INPUT, UNSAFE_ATTR_OUTSIDE_UNSAFE}; use rustc_session::parse::ParseSess; -use rustc_span::{sym, BytePos, Span, Symbol}; +use rustc_span::{BytePos, Span, Symbol, sym}; use crate::{errors, parse_in}; diff --git a/compiler/rustc_parse_format/src/lib.rs b/compiler/rustc_parse_format/src/lib.rs index 51084ef4441d7..e7ef4385baf4f 100644 --- a/compiler/rustc_parse_format/src/lib.rs +++ b/compiler/rustc_parse_format/src/lib.rs @@ -18,11 +18,11 @@ use std::{iter, str, string}; -use rustc_lexer::unescape; pub use Alignment::*; pub use Count::*; pub use Piece::*; pub use Position::*; +use rustc_lexer::unescape; // Note: copied from rustc_span /// Range inside of a `Span` used for diagnostics when we only have access to relative positions. @@ -870,34 +870,28 @@ impl<'a> Parser<'a> { if let (Some(pos), Some(_)) = (self.consume_pos('?'), self.consume_pos(':')) { let word = self.word(); let pos = self.to_span_index(pos); - self.errors.insert( - 0, - ParseError { - description: "expected format parameter to occur after `:`".to_owned(), - note: Some(format!("`?` comes after `:`, try `{}:{}` instead", word, "?")), - label: "expected `?` to occur after `:`".to_owned(), - span: pos.to(pos), - secondary_label: None, - suggestion: Suggestion::None, - }, - ); + self.errors.insert(0, ParseError { + description: "expected format parameter to occur after `:`".to_owned(), + note: Some(format!("`?` comes after `:`, try `{}:{}` instead", word, "?")), + label: "expected `?` to occur after `:`".to_owned(), + span: pos.to(pos), + secondary_label: None, + suggestion: Suggestion::None, + }); } } fn suggest_format_align(&mut self, alignment: char) { if let Some(pos) = self.consume_pos(alignment) { let pos = self.to_span_index(pos); - self.errors.insert( - 0, - ParseError { - description: "expected format parameter to occur after `:`".to_owned(), - note: None, - label: format!("expected `{}` to occur after `:`", alignment), - span: pos.to(pos), - secondary_label: None, - suggestion: Suggestion::None, - }, - ); + self.errors.insert(0, ParseError { + description: "expected format parameter to occur after `:`".to_owned(), + note: None, + label: format!("expected `{}` to occur after `:`", alignment), + span: pos.to(pos), + secondary_label: None, + suggestion: Suggestion::None, + }); } } @@ -914,36 +908,24 @@ impl<'a> Parser<'a> { if let ArgumentNamed(_) = arg.position { match field.position { ArgumentNamed(_) => { - self.errors.insert( - 0, - ParseError { - description: "field access isn't supported".to_string(), - note: None, - label: "not supported".to_string(), - span: InnerSpan::new( - arg.position_span.start, - field.position_span.end, - ), - secondary_label: None, - suggestion: Suggestion::UsePositional, - }, - ); + self.errors.insert(0, ParseError { + description: "field access isn't supported".to_string(), + note: None, + label: "not supported".to_string(), + span: InnerSpan::new(arg.position_span.start, field.position_span.end), + secondary_label: None, + suggestion: Suggestion::UsePositional, + }); } ArgumentIs(_) => { - self.errors.insert( - 0, - ParseError { - description: "tuple index access isn't supported".to_string(), - note: None, - label: "not supported".to_string(), - span: InnerSpan::new( - arg.position_span.start, - field.position_span.end, - ), - secondary_label: None, - suggestion: Suggestion::UsePositional, - }, - ); + self.errors.insert(0, ParseError { + description: "tuple index access isn't supported".to_string(), + note: None, + label: "not supported".to_string(), + span: InnerSpan::new(arg.position_span.start, field.position_span.end), + secondary_label: None, + suggestion: Suggestion::UsePositional, + }); } _ => {} }; diff --git a/compiler/rustc_parse_format/src/tests.rs b/compiler/rustc_parse_format/src/tests.rs index 0c594f9104cc5..81e5bca0ba9fa 100644 --- a/compiler/rustc_parse_format/src/tests.rs +++ b/compiler/rustc_parse_format/src/tests.rs @@ -78,311 +78,307 @@ fn invalid_precision() { #[test] fn format_nothing() { - same( - "{}", - &[NextArgument(Box::new(Argument { - position: ArgumentImplicitlyIs(0), - position_span: InnerSpan { start: 2, end: 2 }, - format: fmtdflt(), - }))], - ); + same("{}", &[NextArgument(Box::new(Argument { + position: ArgumentImplicitlyIs(0), + position_span: InnerSpan { start: 2, end: 2 }, + format: fmtdflt(), + }))]); } #[test] fn format_position() { - same( - "{3}", - &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: fmtdflt(), - }))], - ); + same("{3}", &[NextArgument(Box::new(Argument { + position: ArgumentIs(3), + position_span: InnerSpan { start: 2, end: 3 }, + format: fmtdflt(), + }))]); } #[test] fn format_position_nothing_else() { - same( - "{3:}", - &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: fmtdflt(), - }))], - ); + same("{3:}", &[NextArgument(Box::new(Argument { + position: ArgumentIs(3), + position_span: InnerSpan { start: 2, end: 3 }, + format: fmtdflt(), + }))]); } #[test] fn format_named() { - same( - "{name}", - &[NextArgument(Box::new(Argument { - position: ArgumentNamed("name"), - position_span: InnerSpan { start: 2, end: 6 }, - format: fmtdflt(), - }))], - ) + same("{name}", &[NextArgument(Box::new(Argument { + position: ArgumentNamed("name"), + position_span: InnerSpan { start: 2, end: 6 }, + format: fmtdflt(), + }))]) } #[test] fn format_type() { - same( - "{3:x}", - &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: FormatSpec { - fill: None, - fill_span: None, - align: AlignUnknown, - sign: None, - alternate: false, - zero_pad: false, - debug_hex: None, - precision: CountImplied, - width: CountImplied, - precision_span: None, - width_span: None, - ty: "x", - ty_span: None, - }, - }))], - ); + same("{3:x}", &[NextArgument(Box::new(Argument { + position: ArgumentIs(3), + position_span: InnerSpan { start: 2, end: 3 }, + format: FormatSpec { + fill: None, + fill_span: None, + align: AlignUnknown, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, + precision: CountImplied, + width: CountImplied, + precision_span: None, + width_span: None, + ty: "x", + ty_span: None, + }, + }))]); } #[test] fn format_align_fill() { - same( - "{3:>}", - &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: FormatSpec { - fill: None, - fill_span: None, - align: AlignRight, - sign: None, - alternate: false, - zero_pad: false, - debug_hex: None, - precision: CountImplied, - width: CountImplied, - precision_span: None, - width_span: None, - ty: "", - ty_span: None, - }, - }))], - ); - same( - "{3:0<}", - &[NextArgument(Box::new(Argument { - position: ArgumentIs(3), - position_span: InnerSpan { start: 2, end: 3 }, - format: FormatSpec { - fill: Some('0'), - fill_span: Some(InnerSpan::new(4, 5)), - align: AlignLeft, - sign: None, - alternate: false, - zero_pad: false, - debug_hex: None, - precision: CountImplied, - width: CountImplied, - precision_span: None, - width_span: None, - ty: "", - ty_span: None, - }, - }))], - ); - same( - "{3:*}", &[NextArgument(Box::new(Argument { + position: ArgumentIs(3), + position_span: InnerSpan { start: 2, end: 3 }, + format: FormatSpec { + fill: None, + fill_span: None, + align: AlignRight, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, + precision: CountImplied, + width: CountImplied, + precision_span: None, + width_span: None, + ty: "", + ty_span: None, + }, + }))]); + same("{3:0<}", &[NextArgument(Box::new(Argument { + position: ArgumentIs(3), + position_span: InnerSpan { start: 2, end: 3 }, + format: FormatSpec { + fill: Some('0'), + fill_span: Some(InnerSpan::new(4, 5)), + align: AlignLeft, + sign: None, + alternate: false, + zero_pad: false, + debug_hex: None, + precision: CountImplied, + width: CountImplied, + precision_span: None, + width_span: None, + ty: "", + ty_span: None, + }, + }))]); + same("{3:* CheckAttrVisitor<'tcx> { } fn inline_attr_str_error_without_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) { - self.tcx.emit_node_span_lint( - UNUSED_ATTRIBUTES, - hir_id, - attr.span, - errors::IgnoredAttr { sym }, - ); + self.tcx + .emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::IgnoredAttr { sym }); } /// Checks if `#[diagnostic::do_not_recommend]` is applied on a trait impl. @@ -1396,12 +1392,10 @@ impl<'tcx> CheckAttrVisitor<'tcx> { _ => { // FIXME: #[cold] was previously allowed on non-functions and some crates used // this, so only emit a warning. - self.tcx.emit_node_span_lint( - UNUSED_ATTRIBUTES, - hir_id, - attr.span, - errors::Cold { span, on_crate: hir_id == CRATE_HIR_ID }, - ); + self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::Cold { + span, + on_crate: hir_id == CRATE_HIR_ID, + }); } } } @@ -1416,12 +1410,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { return; } - self.tcx.emit_node_span_lint( - UNUSED_ATTRIBUTES, - hir_id, - attr.span, - errors::Link { span: (target != Target::ForeignMod).then_some(span) }, - ); + self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::Link { + span: (target != Target::ForeignMod).then_some(span), + }); } /// Checks if `#[link_name]` is applied to an item other than a foreign function or static. @@ -2210,12 +2201,10 @@ impl<'tcx> CheckAttrVisitor<'tcx> { return; }; - self.tcx.emit_node_span_lint( - UNUSED_ATTRIBUTES, - hir_id, - attr.span, - errors::Unused { attr_span: attr.span, note }, - ); + self.tcx.emit_node_span_lint(UNUSED_ATTRIBUTES, hir_id, attr.span, errors::Unused { + attr_span: attr.span, + note, + }); } /// A best effort attempt to create an error for a mismatching proc macro signature. diff --git a/compiler/rustc_passes/src/check_const.rs b/compiler/rustc_passes/src/check_const.rs index be6449ea8520a..0dad94a9939f2 100644 --- a/compiler/rustc_passes/src/check_const.rs +++ b/compiler/rustc_passes/src/check_const.rs @@ -14,7 +14,7 @@ use rustc_middle::query::Providers; use rustc_middle::span_bug; use rustc_middle::ty::TyCtxt; use rustc_session::parse::feature_err; -use rustc_span::{sym, Span, Symbol}; +use rustc_span::{Span, Symbol, sym}; use {rustc_attr as attr, rustc_hir as hir}; use crate::errors::SkippingConstChecks; diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index ef534c645a461..aa329fc546ecb 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -5,8 +5,8 @@ use std::mem; -use hir::def_id::{LocalDefIdMap, LocalDefIdSet}; use hir::ItemKind; +use hir::def_id::{LocalDefIdMap, LocalDefIdSet}; use rustc_data_structures::unord::UnordSet; use rustc_errors::MultiSpan; use rustc_hir as hir; @@ -21,7 +21,7 @@ use rustc_middle::ty::{self, TyCtxt}; use rustc_middle::{bug, span_bug}; use rustc_session::lint; use rustc_session::lint::builtin::DEAD_CODE; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; use rustc_target::abi::FieldIdx; use crate::errors::{ diff --git a/compiler/rustc_passes/src/diagnostic_items.rs b/compiler/rustc_passes/src/diagnostic_items.rs index 425e203f2b02c..1c3d3bf3dea0a 100644 --- a/compiler/rustc_passes/src/diagnostic_items.rs +++ b/compiler/rustc_passes/src/diagnostic_items.rs @@ -10,12 +10,12 @@ //! * Compiler internal types like `Ty` and `TyCtxt` use rustc_ast as ast; -use rustc_hir::diagnostic_items::DiagnosticItems; use rustc_hir::OwnerId; +use rustc_hir::diagnostic_items::DiagnosticItems; use rustc_middle::query::{LocalCrate, Providers}; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::{DefId, LOCAL_CRATE}; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; use crate::errors::DuplicateDiagnosticItemInCrate; diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index ecb345bb51a49..690808e75271d 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -2,12 +2,12 @@ use rustc_ast::attr; use rustc_ast::entry::EntryPointType; use rustc_errors::codes::*; use rustc_hir::def::DefKind; -use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; -use rustc_hir::{ItemId, Node, CRATE_HIR_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId}; +use rustc_hir::{CRATE_HIR_ID, ItemId, Node}; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; -use rustc_session::config::{sigpipe, CrateType, EntryFnType, RemapPathScopeComponents}; use rustc_session::RemapFileNameExt; +use rustc_session::config::{CrateType, EntryFnType, RemapPathScopeComponents, sigpipe}; use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; diff --git a/compiler/rustc_passes/src/errors.rs b/compiler/rustc_passes/src/errors.rs index 01052c60e94fd..29a087bf75975 100644 --- a/compiler/rustc_passes/src/errors.rs +++ b/compiler/rustc_passes/src/errors.rs @@ -10,7 +10,7 @@ use rustc_errors::{ use rustc_hir::{self as hir, ExprKind, Target}; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_middle::ty::{MainDefinition, Ty}; -use rustc_span::{Span, Symbol, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span, Symbol}; use crate::check_attr::ProcMacroKind; use crate::fluent_generated as fluent; @@ -1337,15 +1337,11 @@ pub(crate) struct DuplicateLangItem { impl Diagnostic<'_, G> for DuplicateLangItem { #[track_caller] fn into_diag(self, dcx: DiagCtxtHandle<'_>, level: Level) -> Diag<'_, G> { - let mut diag = Diag::new( - dcx, - level, - match self.duplicate { - Duplicate::Plain => fluent::passes_duplicate_lang_item, - Duplicate::Crate => fluent::passes_duplicate_lang_item_crate, - Duplicate::CrateDepends => fluent::passes_duplicate_lang_item_crate_depends, - }, - ); + let mut diag = Diag::new(dcx, level, match self.duplicate { + Duplicate::Plain => fluent::passes_duplicate_lang_item, + Duplicate::Crate => fluent::passes_duplicate_lang_item_crate, + Duplicate::CrateDepends => fluent::passes_duplicate_lang_item_crate_depends, + }); diag.code(E0152); diag.arg("lang_item_name", self.lang_item_name); diag.arg("crate_name", self.crate_name); diff --git a/compiler/rustc_passes/src/hir_id_validator.rs b/compiler/rustc_passes/src/hir_id_validator.rs index 51a69809c7a57..f6b70d9389bb9 100644 --- a/compiler/rustc_passes/src/hir_id_validator.rs +++ b/compiler/rustc_passes/src/hir_id_validator.rs @@ -1,7 +1,7 @@ use rustc_data_structures::sync::Lock; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; -use rustc_hir::{intravisit, HirId, ItemLocalId}; +use rustc_hir::{HirId, ItemLocalId, intravisit}; use rustc_index::bit_set::GrowableBitSet; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; diff --git a/compiler/rustc_passes/src/hir_stats.rs b/compiler/rustc_passes/src/hir_stats.rs index 38e8c3cd12de4..903fb1147440c 100644 --- a/compiler/rustc_passes/src/hir_stats.rs +++ b/compiler/rustc_passes/src/hir_stats.rs @@ -3,15 +3,15 @@ // completely accurate (some things might be counted twice, others missed). use rustc_ast::visit::BoundKind; -use rustc_ast::{self as ast, visit as ast_visit, AttrId, NodeId}; +use rustc_ast::{self as ast, AttrId, NodeId, visit as ast_visit}; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; -use rustc_hir::{intravisit as hir_visit, HirId}; +use rustc_hir::{HirId, intravisit as hir_visit}; use rustc_middle::hir::map::Map; use rustc_middle::ty::TyCtxt; use rustc_middle::util::common::to_readable_str; -use rustc_span::def_id::LocalDefId; use rustc_span::Span; +use rustc_span::def_id::LocalDefId; #[derive(Copy, Clone, PartialEq, Eq, Hash)] enum Id { @@ -219,28 +219,25 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_item(&mut self, i: &'v hir::Item<'v>) { - record_variants!( - (self, i, i.kind, Id::Node(i.hir_id()), hir, Item, ItemKind), - [ - ExternCrate, - Use, - Static, - Const, - Fn, - Macro, - Mod, - ForeignMod, - GlobalAsm, - TyAlias, - OpaqueTy, - Enum, - Struct, - Union, - Trait, - TraitAlias, - Impl - ] - ); + record_variants!((self, i, i.kind, Id::Node(i.hir_id()), hir, Item, ItemKind), [ + ExternCrate, + Use, + Static, + Const, + Fn, + Macro, + Mod, + ForeignMod, + GlobalAsm, + TyAlias, + OpaqueTy, + Enum, + Struct, + Union, + Trait, + TraitAlias, + Impl + ]); hir_visit::walk_item(self, i) } @@ -273,10 +270,9 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) { - record_variants!( - (self, s, s.kind, Id::Node(s.hir_id), hir, Stmt, StmtKind), - [Let, Item, Expr, Semi] - ); + record_variants!((self, s, s.kind, Id::Node(s.hir_id), hir, Stmt, StmtKind), [ + Let, Item, Expr, Semi + ]); hir_visit::walk_stmt(self, s) } @@ -286,26 +282,23 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_pat(&mut self, p: &'v hir::Pat<'v>) { - record_variants!( - (self, p, p.kind, Id::Node(p.hir_id), hir, Pat, PatKind), - [ - Wild, - Binding, - Struct, - TupleStruct, - Or, - Never, - Path, - Tuple, - Box, - Deref, - Ref, - Lit, - Range, - Slice, - Err - ] - ); + record_variants!((self, p, p.kind, Id::Node(p.hir_id), hir, Pat, PatKind), [ + Wild, + Binding, + Struct, + TupleStruct, + Or, + Never, + Path, + Tuple, + Box, + Deref, + Ref, + Lit, + Range, + Slice, + Err + ]); hir_visit::walk_pat(self, p) } @@ -315,15 +308,11 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_expr(&mut self, e: &'v hir::Expr<'v>) { - record_variants!( - (self, e, e.kind, Id::Node(e.hir_id), hir, Expr, ExprKind), - [ - ConstBlock, Array, Call, MethodCall, Tup, Binary, Unary, Lit, Cast, Type, - DropTemps, Let, If, Loop, Match, Closure, Block, Assign, AssignOp, Field, Index, - Path, AddrOf, Break, Continue, Ret, Become, InlineAsm, OffsetOf, Struct, Repeat, - Yield, Err - ] - ); + record_variants!((self, e, e.kind, Id::Node(e.hir_id), hir, Expr, ExprKind), [ + ConstBlock, Array, Call, MethodCall, Tup, Binary, Unary, Lit, Cast, Type, DropTemps, + Let, If, Loop, Match, Closure, Block, Assign, AssignOp, Field, Index, Path, AddrOf, + Break, Continue, Ret, Become, InlineAsm, OffsetOf, Struct, Repeat, Yield, Err + ]); hir_visit::walk_expr(self, e) } @@ -333,27 +322,24 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_ty(&mut self, t: &'v hir::Ty<'v>) { - record_variants!( - (self, t, t.kind, Id::Node(t.hir_id), hir, Ty, TyKind), - [ - InferDelegation, - Slice, - Array, - Ptr, - Ref, - BareFn, - Never, - Tup, - AnonAdt, - Path, - OpaqueDef, - TraitObject, - Typeof, - Infer, - Pat, - Err - ] - ); + record_variants!((self, t, t.kind, Id::Node(t.hir_id), hir, Ty, TyKind), [ + InferDelegation, + Slice, + Array, + Ptr, + Ref, + BareFn, + Never, + Tup, + AnonAdt, + Path, + OpaqueDef, + TraitObject, + Typeof, + Infer, + Pat, + Err + ]); hir_visit::walk_ty(self, t) } @@ -368,10 +354,11 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_where_predicate(&mut self, p: &'v hir::WherePredicate<'v>) { - record_variants!( - (self, p, p, Id::None, hir, WherePredicate, WherePredicate), - [BoundPredicate, RegionPredicate, EqPredicate] - ); + record_variants!((self, p, p, Id::None, hir, WherePredicate, WherePredicate), [ + BoundPredicate, + RegionPredicate, + EqPredicate + ]); hir_visit::walk_where_predicate(self, p) } @@ -425,10 +412,9 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_param_bound(&mut self, b: &'v hir::GenericBound<'v>) { - record_variants!( - (self, b, b, Id::None, hir, GenericBound, GenericBound), - [Trait, Outlives, Use] - ); + record_variants!((self, b, b, Id::None, hir, GenericBound, GenericBound), [ + Trait, Outlives, Use + ]); hir_visit::walk_param_bound(self, b) } @@ -443,10 +429,9 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { } fn visit_generic_arg(&mut self, ga: &'v hir::GenericArg<'v>) { - record_variants!( - (self, ga, ga, Id::Node(ga.hir_id()), hir, GenericArg, GenericArg), - [Lifetime, Type, Const, Infer] - ); + record_variants!((self, ga, ga, Id::Node(ga.hir_id()), hir, GenericArg, GenericArg), [ + Lifetime, Type, Const, Infer + ]); match ga { hir::GenericArg::Lifetime(lt) => self.visit_lifetime(lt), hir::GenericArg::Type(ty) => self.visit_ty(ty), @@ -492,38 +477,34 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> { impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { fn visit_foreign_item(&mut self, i: &'v ast::ForeignItem) { - record_variants!( - (self, i, i.kind, Id::None, ast, ForeignItem, ForeignItemKind), - [Static, Fn, TyAlias, MacCall] - ); + record_variants!((self, i, i.kind, Id::None, ast, ForeignItem, ForeignItemKind), [ + Static, Fn, TyAlias, MacCall + ]); ast_visit::walk_item(self, i) } fn visit_item(&mut self, i: &'v ast::Item) { - record_variants!( - (self, i, i.kind, Id::None, ast, Item, ItemKind), - [ - ExternCrate, - Use, - Static, - Const, - Fn, - Mod, - ForeignMod, - GlobalAsm, - TyAlias, - Enum, - Struct, - Union, - Trait, - TraitAlias, - Impl, - MacCall, - MacroDef, - Delegation, - DelegationMac - ] - ); + record_variants!((self, i, i.kind, Id::None, ast, Item, ItemKind), [ + ExternCrate, + Use, + Static, + Const, + Fn, + Mod, + ForeignMod, + GlobalAsm, + TyAlias, + Enum, + Struct, + Union, + Trait, + TraitAlias, + Impl, + MacCall, + MacroDef, + Delegation, + DelegationMac + ]); ast_visit::walk_item(self, i) } @@ -538,10 +519,9 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_stmt(&mut self, s: &'v ast::Stmt) { - record_variants!( - (self, s, s.kind, Id::None, ast, Stmt, StmtKind), - [Let, Item, Expr, Semi, Empty, MacCall] - ); + record_variants!((self, s, s.kind, Id::None, ast, Stmt, StmtKind), [ + Let, Item, Expr, Semi, Empty, MacCall + ]); ast_visit::walk_stmt(self, s) } @@ -556,29 +536,26 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_pat(&mut self, p: &'v ast::Pat) { - record_variants!( - (self, p, p.kind, Id::None, ast, Pat, PatKind), - [ - Wild, - Ident, - Struct, - TupleStruct, - Or, - Path, - Tuple, - Box, - Deref, - Ref, - Lit, - Range, - Slice, - Rest, - Never, - Paren, - MacCall, - Err - ] - ); + record_variants!((self, p, p.kind, Id::None, ast, Pat, PatKind), [ + Wild, + Ident, + Struct, + TupleStruct, + Or, + Path, + Tuple, + Box, + Deref, + Ref, + Lit, + Range, + Slice, + Rest, + Never, + Paren, + MacCall, + Err + ]); ast_visit::walk_pat(self, p) } @@ -598,32 +575,29 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_ty(&mut self, t: &'v ast::Ty) { - record_variants!( - (self, t, t.kind, Id::None, ast, Ty, TyKind), - [ - Slice, - Array, - Ptr, - Ref, - BareFn, - Never, - Tup, - AnonStruct, - AnonUnion, - Path, - Pat, - TraitObject, - ImplTrait, - Paren, - Typeof, - Infer, - ImplicitSelf, - MacCall, - CVarArgs, - Dummy, - Err - ] - ); + record_variants!((self, t, t.kind, Id::None, ast, Ty, TyKind), [ + Slice, + Array, + Ptr, + Ref, + BareFn, + Never, + Tup, + AnonStruct, + AnonUnion, + Path, + Pat, + TraitObject, + ImplTrait, + Paren, + Typeof, + Infer, + ImplicitSelf, + MacCall, + CVarArgs, + Dummy, + Err + ]); ast_visit::walk_ty(self, t) } @@ -634,10 +608,11 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_where_predicate(&mut self, p: &'v ast::WherePredicate) { - record_variants!( - (self, p, p, Id::None, ast, WherePredicate, WherePredicate), - [BoundPredicate, RegionPredicate, EqPredicate] - ); + record_variants!((self, p, p, Id::None, ast, WherePredicate, WherePredicate), [ + BoundPredicate, + RegionPredicate, + EqPredicate + ]); ast_visit::walk_where_predicate(self, p) } @@ -647,18 +622,21 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { } fn visit_assoc_item(&mut self, i: &'v ast::AssocItem, ctxt: ast_visit::AssocCtxt) { - record_variants!( - (self, i, i.kind, Id::None, ast, AssocItem, AssocItemKind), - [Const, Fn, Type, MacCall, Delegation, DelegationMac] - ); + record_variants!((self, i, i.kind, Id::None, ast, AssocItem, AssocItemKind), [ + Const, + Fn, + Type, + MacCall, + Delegation, + DelegationMac + ]); ast_visit::walk_assoc_item(self, i, ctxt); } fn visit_param_bound(&mut self, b: &'v ast::GenericBound, _ctxt: BoundKind) { - record_variants!( - (self, b, b, Id::None, ast, GenericBound, GenericBound), - [Trait, Outlives, Use] - ); + record_variants!((self, b, b, Id::None, ast, GenericBound, GenericBound), [ + Trait, Outlives, Use + ]); ast_visit::walk_param_bound(self, b) } @@ -691,18 +669,18 @@ impl<'v> ast_visit::Visitor<'v> for StatCollector<'v> { // common, so we implement `visit_generic_args` and tolerate the double // counting in the former case. fn visit_generic_args(&mut self, g: &'v ast::GenericArgs) { - record_variants!( - (self, g, g, Id::None, ast, GenericArgs, GenericArgs), - [AngleBracketed, Parenthesized, ParenthesizedElided] - ); + record_variants!((self, g, g, Id::None, ast, GenericArgs, GenericArgs), [ + AngleBracketed, + Parenthesized, + ParenthesizedElided + ]); ast_visit::walk_generic_args(self, g) } fn visit_attribute(&mut self, attr: &'v ast::Attribute) { - record_variants!( - (self, attr, attr.kind, Id::None, ast, Attribute, AttrKind), - [Normal, DocComment] - ); + record_variants!((self, attr, attr.kind, Id::None, ast, Attribute, AttrKind), [ + Normal, DocComment + ]); ast_visit::walk_attribute(self, attr) } diff --git a/compiler/rustc_passes/src/lang_items.rs b/compiler/rustc_passes/src/lang_items.rs index 8038afb955e28..19f00aa3c1b3b 100644 --- a/compiler/rustc_passes/src/lang_items.rs +++ b/compiler/rustc_passes/src/lang_items.rs @@ -11,13 +11,13 @@ use rustc_ast as ast; use rustc_ast::visit; use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::{DefId, LocalDefId}; -use rustc_hir::lang_items::{extract, GenericRequirement}; +use rustc_hir::lang_items::{GenericRequirement, extract}; use rustc_hir::{LangItem, LanguageItems, MethodKind, Target}; use rustc_middle::query::Providers; use rustc_middle::ty::{ResolverAstLowering, TyCtxt}; use rustc_session::cstore::ExternCrate; -use rustc_span::symbol::kw::Empty; use rustc_span::Span; +use rustc_span::symbol::kw::Empty; use crate::errors::{ DuplicateLangItem, IncorrectTarget, LangItemOnIncorrectTarget, UnknownLangItem, diff --git a/compiler/rustc_passes/src/layout_test.rs b/compiler/rustc_passes/src/layout_test.rs index 4fe11589907f3..3aef88e771f51 100644 --- a/compiler/rustc_passes/src/layout_test.rs +++ b/compiler/rustc_passes/src/layout_test.rs @@ -4,9 +4,9 @@ use rustc_hir::def_id::LocalDefId; use rustc_middle::span_bug; use rustc_middle::ty::layout::{HasParamEnv, HasTyCtxt, LayoutError, LayoutOfHelpers}; use rustc_middle::ty::{self, ParamEnv, Ty, TyCtxt}; +use rustc_span::Span; use rustc_span::source_map::Spanned; use rustc_span::symbol::sym; -use rustc_span::Span; use rustc_target::abi::{HasDataLayout, TargetDataLayout}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::infer::TyCtxtInferExt; diff --git a/compiler/rustc_passes/src/lib_features.rs b/compiler/rustc_passes/src/lib_features.rs index 9d5766865c72f..91ba2fa7548f7 100644 --- a/compiler/rustc_passes/src/lib_features.rs +++ b/compiler/rustc_passes/src/lib_features.rs @@ -12,7 +12,7 @@ use rustc_middle::middle::lib_features::{FeatureStability, LibFeatures}; use rustc_middle::query::{LocalCrate, Providers}; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::Symbol; -use rustc_span::{sym, Span}; +use rustc_span::{Span, sym}; use crate::errors::{FeaturePreviouslyDeclared, FeatureStableTwice}; diff --git a/compiler/rustc_passes/src/liveness.rs b/compiler/rustc_passes/src/liveness.rs index 959b7ad147b5f..366f7dd293c44 100644 --- a/compiler/rustc_passes/src/liveness.rs +++ b/compiler/rustc_passes/src/liveness.rs @@ -96,7 +96,7 @@ use rustc_middle::query::Providers; use rustc_middle::span_bug; use rustc_middle::ty::{self, RootVariableMinCaptureList, Ty, TyCtxt}; use rustc_session::lint; -use rustc_span::symbol::{kw, sym, Symbol}; +use rustc_span::symbol::{Symbol, kw, sym}; use rustc_span::{BytePos, Span}; use tracing::{debug, instrument}; diff --git a/compiler/rustc_passes/src/loops.rs b/compiler/rustc_passes/src/loops.rs index af932bd69abc3..6eef0b926a130 100644 --- a/compiler/rustc_passes/src/loops.rs +++ b/compiler/rustc_passes/src/loops.rs @@ -1,6 +1,7 @@ use std::collections::BTreeMap; use std::fmt; +use Context::*; use rustc_hir as hir; use rustc_hir::def_id::{LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, Visitor}; @@ -11,7 +12,6 @@ use rustc_middle::span_bug; use rustc_middle::ty::TyCtxt; use rustc_span::hygiene::DesugaringKind; use rustc_span::{BytePos, Span}; -use Context::*; use crate::errors::{ BreakInsideClosure, BreakInsideCoroutine, BreakNonLoop, ContinueLabeledBlock, OutsideLoop, diff --git a/compiler/rustc_passes/src/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index ab6385dd7d738..8d3f7e0231f78 100644 --- a/compiler/rustc_passes/src/naked_functions.rs +++ b/compiler/rustc_passes/src/naked_functions.rs @@ -10,8 +10,8 @@ use rustc_middle::hir::nested_filter::OnlyBodies; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::lint::builtin::UNDEFINED_NAKED_FUNCTION_ABI; -use rustc_span::symbol::sym; use rustc_span::Span; +use rustc_span::symbol::sym; use rustc_target::spec::abi::Abi; use crate::errors::{ diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index 8d9e00b9f3c8f..925ee26202283 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -25,10 +25,10 @@ use hir::def_id::LocalDefIdSet; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hir as hir; +use rustc_hir::Node; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; -use rustc_hir::Node; use rustc_middle::bug; use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs}; use rustc_middle::middle::privacy::{self, Level}; @@ -318,10 +318,10 @@ impl<'tcx> ReachableContext<'tcx> { )); self.visit(instance.args); } - GlobalAlloc::VTable(ty, trait_ref) => { + GlobalAlloc::VTable(ty, dyn_ty) => { self.visit(ty); // Manually visit to actually see the trait's `DefId`. Type visitors won't see it - if let Some(trait_ref) = trait_ref { + if let Some(trait_ref) = dyn_ty.principal() { let ExistentialTraitRef { def_id, args } = trait_ref.skip_binder(); self.visit_def_id(def_id, "", &""); self.visit(args); diff --git a/compiler/rustc_passes/src/stability.rs b/compiler/rustc_passes/src/stability.rs index e2c9067c0b966..46b67e930d5e9 100644 --- a/compiler/rustc_passes/src/stability.rs +++ b/compiler/rustc_passes/src/stability.rs @@ -12,7 +12,7 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::unord::{ExtendUnord, UnordMap, UnordSet}; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{LocalDefId, LocalModDefId, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE, LocalDefId, LocalModDefId}; use rustc_hir::hir_id::CRATE_HIR_ID; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{FieldDef, Item, ItemKind, TraitRef, Ty, TyKind, Variant}; @@ -24,8 +24,8 @@ use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; use rustc_session::lint; use rustc_session::lint::builtin::{INEFFECTIVE_UNSTABLE_TRAIT_IMPL, USELESS_DEPRECATED}; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, sym}; use rustc_target::spec::abi::Abi; use tracing::{debug, info}; diff --git a/compiler/rustc_pattern_analysis/src/constructor.rs b/compiler/rustc_pattern_analysis/src/constructor.rs index e4edd7befb76f..3cb7576154fc1 100644 --- a/compiler/rustc_pattern_analysis/src/constructor.rs +++ b/compiler/rustc_pattern_analysis/src/constructor.rs @@ -176,13 +176,13 @@ //! we assume they never cover each other. In order to respect the invariants of //! [`SplitConstructorSet`], we give each `Opaque` constructor a unique id so we can recognize it. -use std::cmp::{self, max, min, Ordering}; +use std::cmp::{self, Ordering, max, min}; use std::fmt; use std::iter::once; use rustc_apfloat::ieee::{DoubleS, HalfS, IeeeFloat, QuadS, SingleS}; -use rustc_index::bit_set::{BitSet, GrowableBitSet}; use rustc_index::IndexVec; +use rustc_index::bit_set::{BitSet, GrowableBitSet}; use smallvec::SmallVec; use self::Constructor::*; diff --git a/compiler/rustc_pattern_analysis/src/lints.rs b/compiler/rustc_pattern_analysis/src/lints.rs index 6bcef0ec879dd..585cda1d24b7f 100644 --- a/compiler/rustc_pattern_analysis/src/lints.rs +++ b/compiler/rustc_pattern_analysis/src/lints.rs @@ -2,11 +2,11 @@ use rustc_session::lint::builtin::NON_EXHAUSTIVE_OMITTED_PATTERNS; use rustc_span::ErrorGuaranteed; use tracing::instrument; +use crate::MatchArm; use crate::constructor::Constructor; use crate::errors::{NonExhaustiveOmittedPattern, NonExhaustiveOmittedPatternLintOnArm, Uncovered}; use crate::pat_column::PatternColumn; use crate::rustc::{RevealedTy, RustcPatCtxt, WitnessPat}; -use crate::MatchArm; /// Traverse the patterns to collect any variants of a non_exhaustive enum that fail to be mentioned /// in a given column. diff --git a/compiler/rustc_pattern_analysis/src/pat.rs b/compiler/rustc_pattern_analysis/src/pat.rs index d91deab160c50..901b72e53995e 100644 --- a/compiler/rustc_pattern_analysis/src/pat.rs +++ b/compiler/rustc_pattern_analysis/src/pat.rs @@ -3,7 +3,7 @@ use std::fmt; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use self::Constructor::*; use crate::constructor::{Constructor, Slice, SliceKind}; diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 6c09f97bfe731..72737fb98cbf7 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -2,8 +2,8 @@ use std::fmt; use std::iter::once; use rustc_arena::DroplessArena; -use rustc_hir::def_id::DefId; use rustc_hir::HirId; +use rustc_hir::def_id::DefId; use rustc_index::{Idx, IndexVec}; use rustc_middle::middle::stability::EvalResult; use rustc_middle::mir::{self, Const}; @@ -14,8 +14,8 @@ use rustc_middle::ty::{ }; use rustc_middle::{bug, span_bug}; use rustc_session::lint; -use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; -use rustc_target::abi::{FieldIdx, Integer, VariantIdx, FIRST_VARIANT}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; +use rustc_target::abi::{FIRST_VARIANT, FieldIdx, Integer, VariantIdx}; use crate::constructor::Constructor::*; use crate::constructor::{ @@ -24,8 +24,8 @@ use crate::constructor::{ use crate::lints::lint_nonexhaustive_missing_variants; use crate::pat_column::PatternColumn; use crate::rustc::print::EnumInfo; -use crate::usefulness::{compute_match_usefulness, PlaceValidity}; -use crate::{errors, Captures, PatCx, PrivateUninhabitedField}; +use crate::usefulness::{PlaceValidity, compute_match_usefulness}; +use crate::{Captures, PatCx, PrivateUninhabitedField, errors}; mod print; @@ -352,7 +352,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { ty::Array(sub_ty, len) => { // We treat arrays of a constant but unknown length like slices. ConstructorSet::Slice { - array_len: len.try_eval_target_usize(cx.tcx, cx.param_env).map(|l| l as usize), + array_len: len.try_to_target_usize(cx.tcx).map(|l| l as usize), subtype_is_empty: cx.is_uninhabited(*sub_ty), } } @@ -685,9 +685,12 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { } PatKind::Array { prefix, slice, suffix } | PatKind::Slice { prefix, slice, suffix } => { let array_len = match ty.kind() { - ty::Array(_, length) => { - Some(length.eval_target_usize(cx.tcx, cx.param_env) as usize) - } + ty::Array(_, length) => Some( + length + .try_to_target_usize(cx.tcx) + .expect("expected len of array pat to be definite") + as usize, + ), ty::Slice(_) => None, _ => span_bug!(pat.span, "bad ty {} for slice pattern", ty.inner()), }; diff --git a/compiler/rustc_pattern_analysis/src/usefulness.rs b/compiler/rustc_pattern_analysis/src/usefulness.rs index 814559a66c568..99261eaa95cc1 100644 --- a/compiler/rustc_pattern_analysis/src/usefulness.rs +++ b/compiler/rustc_pattern_analysis/src/usefulness.rs @@ -713,7 +713,7 @@ use std::fmt; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_hash::{FxHashMap, FxHashSet}; use rustc_index::bit_set::BitSet; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument}; use self::PlaceValidity::*; diff --git a/compiler/rustc_pattern_analysis/tests/common/mod.rs b/compiler/rustc_pattern_analysis/tests/common/mod.rs index ec0bcd43ad24d..cd697632d1b18 100644 --- a/compiler/rustc_pattern_analysis/tests/common/mod.rs +++ b/compiler/rustc_pattern_analysis/tests/common/mod.rs @@ -6,9 +6,9 @@ use rustc_pattern_analysis::{Captures, MatchArm, PatCx, PrivateUninhabitedField} /// Sets up `tracing` for easier debugging. Tries to look like the `rustc` setup. pub fn init_tracing() { + use tracing_subscriber::Layer; use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::util::SubscriberInitExt; - use tracing_subscriber::Layer; let _ = tracing_tree::HierarchicalLayer::default() .with_writer(std::io::stderr) .with_ansi(true) diff --git a/compiler/rustc_pattern_analysis/tests/complexity.rs b/compiler/rustc_pattern_analysis/tests/complexity.rs index 3a9b9e9f07588..43b585bc533a8 100644 --- a/compiler/rustc_pattern_analysis/tests/complexity.rs +++ b/compiler/rustc_pattern_analysis/tests/complexity.rs @@ -1,9 +1,9 @@ //! Test the pattern complexity limit. use common::*; +use rustc_pattern_analysis::MatchArm; use rustc_pattern_analysis::pat::DeconstructedPat; use rustc_pattern_analysis::usefulness::PlaceValidity; -use rustc_pattern_analysis::MatchArm; #[macro_use] mod common; diff --git a/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs b/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs index af093db782cde..0d80042a850fd 100644 --- a/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs +++ b/compiler/rustc_pattern_analysis/tests/exhaustiveness.rs @@ -1,9 +1,9 @@ //! Test exhaustiveness checking. use common::*; +use rustc_pattern_analysis::MatchArm; use rustc_pattern_analysis::pat::{DeconstructedPat, WitnessPat}; use rustc_pattern_analysis::usefulness::PlaceValidity; -use rustc_pattern_analysis::MatchArm; #[macro_use] mod common; diff --git a/compiler/rustc_pattern_analysis/tests/intersection.rs b/compiler/rustc_pattern_analysis/tests/intersection.rs index 1c26e179f2ec7..a852056b6a6c2 100644 --- a/compiler/rustc_pattern_analysis/tests/intersection.rs +++ b/compiler/rustc_pattern_analysis/tests/intersection.rs @@ -1,9 +1,9 @@ //! Test the computation of arm intersections. use common::*; +use rustc_pattern_analysis::MatchArm; use rustc_pattern_analysis::pat::DeconstructedPat; use rustc_pattern_analysis::usefulness::PlaceValidity; -use rustc_pattern_analysis::MatchArm; #[macro_use] mod common; diff --git a/compiler/rustc_privacy/src/errors.rs b/compiler/rustc_privacy/src/errors.rs index 34553c2b90ab8..f5e641eb64243 100644 --- a/compiler/rustc_privacy/src/errors.rs +++ b/compiler/rustc_privacy/src/errors.rs @@ -1,5 +1,5 @@ -use rustc_errors::codes::*; use rustc_errors::DiagArgFromDisplay; +use rustc_errors::codes::*; use rustc_macros::{Diagnostic, LintDiagnostic, Subdiagnostic}; use rustc_span::{Span, Symbol}; diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index c7078e1a27a02..9094b00fbfb44 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -20,12 +20,12 @@ use errors::{ ItemIsPrivate, PrivateInterfacesOrBoundsLint, ReportEffectiveVisibility, UnnameableTypesLint, UnnamedItemIsPrivate, }; -use rustc_ast::visit::{try_visit, VisitorResult}; use rustc_ast::MacroDef; +use rustc_ast::visit::{VisitorResult, try_visit}; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::intern::Interned; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{DefId, LocalDefId, LocalModDefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{AssocItemKind, ForeignItemKind, ItemId, ItemKind, PatKind}; use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level}; @@ -37,9 +37,9 @@ use rustc_middle::ty::{ }; use rustc_middle::{bug, span_bug}; use rustc_session::lint; -use rustc_span::hygiene::Transparency; -use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; +use rustc_span::hygiene::Transparency; +use rustc_span::symbol::{Ident, kw, sym}; use tracing::debug; use {rustc_attr as attr, rustc_hir as hir}; diff --git a/compiler/rustc_query_impl/src/lib.rs b/compiler/rustc_query_impl/src/lib.rs index a6c863a6b7b76..69742bb49b1e8 100644 --- a/compiler/rustc_query_impl/src/lib.rs +++ b/compiler/rustc_query_impl/src/lib.rs @@ -16,19 +16,19 @@ use rustc_data_structures::stable_hasher::HashStable; use rustc_data_structures::sync::AtomicU64; use rustc_middle::arena::Arena; use rustc_middle::dep_graph::{self, DepKind, DepKindStruct, DepNodeIndex}; -use rustc_middle::query::erase::{erase, restore, Erase}; +use rustc_middle::query::erase::{Erase, erase, restore}; use rustc_middle::query::on_disk_cache::{CacheEncoder, EncodedDepNodeIndex, OnDiskCache}; use rustc_middle::query::plumbing::{DynamicQuery, QuerySystem, QuerySystemFns}; use rustc_middle::query::{ - queries, AsLocalKey, DynamicQueries, ExternProviders, Providers, QueryCaches, QueryEngine, - QueryStates, + AsLocalKey, DynamicQueries, ExternProviders, Providers, QueryCaches, QueryEngine, QueryStates, + queries, }; use rustc_middle::ty::TyCtxt; use rustc_query_system::dep_graph::SerializedDepNodeIndex; use rustc_query_system::ich::StableHashingContext; use rustc_query_system::query::{ - get_query_incr, get_query_non_incr, CycleError, HashResult, QueryCache, QueryConfig, QueryMap, - QueryMode, QueryState, + CycleError, HashResult, QueryCache, QueryConfig, QueryMap, QueryMode, QueryState, + get_query_incr, get_query_non_incr, }; use rustc_query_system::{HandleCycleError, Value}; use rustc_span::{ErrorGuaranteed, Span}; @@ -38,7 +38,7 @@ use crate::profiling_support::QueryKeyStringCache; #[macro_use] mod plumbing; -pub use crate::plumbing::{query_key_hash_verify_all, QueryCtxt}; +pub use crate::plumbing::{QueryCtxt, query_key_hash_verify_all}; mod profiling_support; pub use self::profiling_support::alloc_self_profile_query_strings; diff --git a/compiler/rustc_query_impl/src/plumbing.rs b/compiler/rustc_query_impl/src/plumbing.rs index 6a6698b019caa..f72f656b2f8f9 100644 --- a/compiler/rustc_query_impl/src/plumbing.rs +++ b/compiler/rustc_query_impl/src/plumbing.rs @@ -11,21 +11,21 @@ use rustc_errors::DiagInner; use rustc_index::Idx; use rustc_middle::bug; use rustc_middle::dep_graph::{ - self, dep_kinds, DepContext, DepKind, DepKindStruct, DepNode, DepNodeIndex, - SerializedDepNodeIndex, + self, DepContext, DepKind, DepKindStruct, DepNode, DepNodeIndex, SerializedDepNodeIndex, + dep_kinds, }; +use rustc_middle::query::Key; use rustc_middle::query::on_disk_cache::{ AbsoluteBytePos, CacheDecoder, CacheEncoder, EncodedDepNodeIndex, }; -use rustc_middle::query::Key; use rustc_middle::ty::print::with_reduced_queries; use rustc_middle::ty::tls::{self, ImplicitCtxt}; use rustc_middle::ty::{self, TyCtxt, TyEncoder}; use rustc_query_system::dep_graph::{DepNodeParams, HasDepContext}; use rustc_query_system::ich::StableHashingContext; use rustc_query_system::query::{ - force_query, QueryCache, QueryConfig, QueryContext, QueryJobId, QueryMap, QuerySideEffects, - QueryStackFrame, + QueryCache, QueryConfig, QueryContext, QueryJobId, QueryMap, QuerySideEffects, QueryStackFrame, + force_query, }; use rustc_query_system::{LayoutOfDepth, QueryOverflow}; use rustc_serialize::{Decodable, Encodable}; diff --git a/compiler/rustc_query_impl/src/profiling_support.rs b/compiler/rustc_query_impl/src/profiling_support.rs index 536044298f0b8..5f989b264aa63 100644 --- a/compiler/rustc_query_impl/src/profiling_support.rs +++ b/compiler/rustc_query_impl/src/profiling_support.rs @@ -4,7 +4,7 @@ use std::io::Write; use measureme::{StringComponent, StringId}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::profiling::SelfProfiler; -use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{CrateNum, DefId, DefIndex, LOCAL_CRATE, LocalDefId}; use rustc_hir::definitions::DefPathData; use rustc_middle::ty::TyCtxt; use rustc_query_system::query::QueryCache; diff --git a/compiler/rustc_query_system/src/dep_graph/dep_node.rs b/compiler/rustc_query_system/src/dep_graph/dep_node.rs index dfd0527252d60..2902d17d68730 100644 --- a/compiler/rustc_query_system/src/dep_graph/dep_node.rs +++ b/compiler/rustc_query_system/src/dep_graph/dep_node.rs @@ -45,9 +45,9 @@ use std::fmt; use std::hash::Hash; +use rustc_data_structures::AtomicRef; use rustc_data_structures::fingerprint::{Fingerprint, PackedFingerprint}; use rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableOrd, ToStableHashKey}; -use rustc_data_structures::AtomicRef; use rustc_hir::definitions::DefPathHash; use rustc_macros::{Decodable, Encodable}; diff --git a/compiler/rustc_query_system/src/dep_graph/graph.rs b/compiler/rustc_query_system/src/dep_graph/graph.rs index eb3eddf34aa3e..cd7725d2d70df 100644 --- a/compiler/rustc_query_system/src/dep_graph/graph.rs +++ b/compiler/rustc_query_system/src/dep_graph/graph.rs @@ -3,8 +3,8 @@ use std::collections::hash_map::Entry; use std::fmt::Debug; use std::hash::Hash; use std::marker::PhantomData; -use std::sync::atomic::Ordering; use std::sync::Arc; +use std::sync::atomic::Ordering; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; diff --git a/compiler/rustc_query_system/src/dep_graph/mod.rs b/compiler/rustc_query_system/src/dep_graph/mod.rs index 291f275ef3c6f..e564ae0cec7a8 100644 --- a/compiler/rustc_query_system/src/dep_graph/mod.rs +++ b/compiler/rustc_query_system/src/dep_graph/mod.rs @@ -9,14 +9,14 @@ use std::panic; pub use dep_node::{DepKind, DepKindStruct, DepNode, DepNodeParams, WorkProductId}; pub(crate) use graph::DepGraphData; -pub use graph::{hash_result, DepGraph, DepNodeIndex, TaskDepsRef, WorkProduct, WorkProductMap}; +pub use graph::{DepGraph, DepNodeIndex, TaskDepsRef, WorkProduct, WorkProductMap, hash_result}; pub use query::DepGraphQuery; use rustc_data_structures::profiling::SelfProfilerRef; use rustc_session::Session; pub use serialized::{SerializedDepGraph, SerializedDepNodeIndex}; use tracing::instrument; -use self::graph::{print_markframe_trace, MarkFrame}; +use self::graph::{MarkFrame, print_markframe_trace}; use crate::ich::StableHashingContext; pub trait DepContext: Copy { diff --git a/compiler/rustc_query_system/src/dep_graph/query.rs b/compiler/rustc_query_system/src/dep_graph/query.rs index 5969e5fbe98f4..624f4e4578edf 100644 --- a/compiler/rustc_query_system/src/dep_graph/query.rs +++ b/compiler/rustc_query_system/src/dep_graph/query.rs @@ -1,5 +1,5 @@ use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::graph::implementation::{Direction, Graph, NodeIndex, INCOMING}; +use rustc_data_structures::graph::implementation::{Direction, Graph, INCOMING, NodeIndex}; use rustc_index::IndexVec; use super::{DepNode, DepNodeIndex}; diff --git a/compiler/rustc_query_system/src/ich/hcx.rs b/compiler/rustc_query_system/src/ich/hcx.rs index 756ad3b1a2dda..ad4b194eb50cd 100644 --- a/compiler/rustc_query_system/src/ich/hcx.rs +++ b/compiler/rustc_query_system/src/ich/hcx.rs @@ -3,11 +3,11 @@ use rustc_data_structures::stable_hasher::{HashStable, HashingControls, StableHa use rustc_data_structures::sync::Lrc; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::definitions::DefPathHash; -use rustc_session::cstore::Untracked; use rustc_session::Session; +use rustc_session::cstore::Untracked; use rustc_span::source_map::SourceMap; use rustc_span::symbol::Symbol; -use rustc_span::{BytePos, CachingSourceMapView, SourceFile, Span, SpanData, DUMMY_SP}; +use rustc_span::{BytePos, CachingSourceMapView, DUMMY_SP, SourceFile, Span, SpanData}; use crate::ich; diff --git a/compiler/rustc_query_system/src/ich/mod.rs b/compiler/rustc_query_system/src/ich/mod.rs index bae768851419a..8f28b1d4c8086 100644 --- a/compiler/rustc_query_system/src/ich/mod.rs +++ b/compiler/rustc_query_system/src/ich/mod.rs @@ -1,6 +1,6 @@ //! ICH - Incremental Compilation Hash -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; pub use self::hcx::StableHashingContext; diff --git a/compiler/rustc_query_system/src/query/mod.rs b/compiler/rustc_query_system/src/query/mod.rs index db00c26515996..3e35fdb77b396 100644 --- a/compiler/rustc_query_system/src/query/mod.rs +++ b/compiler/rustc_query_system/src/query/mod.rs @@ -5,7 +5,7 @@ mod job; #[cfg(parallel_compiler)] pub use self::job::break_query_cycles; pub use self::job::{ - print_query_stack, report_cycle, QueryInfo, QueryJob, QueryJobId, QueryJobInfo, QueryMap, + QueryInfo, QueryJob, QueryJobId, QueryJobInfo, QueryMap, print_query_stack, report_cycle, }; mod caches; @@ -17,8 +17,8 @@ use rustc_data_structures::sync::Lock; use rustc_errors::DiagInner; use rustc_hir::def::DefKind; use rustc_macros::{Decodable, Encodable}; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; use thin_vec::ThinVec; pub use self::config::{HashResult, QueryConfig}; diff --git a/compiler/rustc_query_system/src/query/plumbing.rs b/compiler/rustc_query_system/src/query/plumbing.rs index 6dbd6e89fe98a..17486be04dcde 100644 --- a/compiler/rustc_query_system/src/query/plumbing.rs +++ b/compiler/rustc_query_system/src/query/plumbing.rs @@ -16,21 +16,21 @@ use rustc_data_structures::sync::Lock; #[cfg(parallel_compiler)] use rustc_data_structures::{outline, sync}; use rustc_errors::{Diag, FatalError, StashKey}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use thin_vec::ThinVec; use tracing::instrument; use super::QueryConfig; +use crate::HandleCycleError; use crate::dep_graph::{DepContext, DepGraphData, DepNode, DepNodeIndex, DepNodeParams}; use crate::ich::StableHashingContext; use crate::query::caches::QueryCache; #[cfg(parallel_compiler)] use crate::query::job::QueryLatch; -use crate::query::job::{report_cycle, QueryInfo, QueryJob, QueryJobId, QueryJobInfo}; +use crate::query::job::{QueryInfo, QueryJob, QueryJobId, QueryJobInfo, report_cycle}; use crate::query::{ QueryContext, QueryMap, QuerySideEffects, QueryStackFrame, SerializedDepNodeIndex, }; -use crate::HandleCycleError; pub struct QueryState { active: Sharded>, diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index f87f3cdde4cf0..a9ea268e51a9d 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -17,24 +17,25 @@ use rustc_data_structures::sync::Lrc; use rustc_expand::base::ResolverExpand; use rustc_expand::expand::AstFragment; use rustc_hir::def::{self, *}; -use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_metadata::creader::LoadedMacro; use rustc_middle::metadata::ModChild; use rustc_middle::ty::Feed; use rustc_middle::{bug, ty}; -use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; +use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use tracing::debug; +use crate::Namespace::{MacroNS, TypeNS, ValueNS}; use crate::def_collector::collect_definitions; use crate::imports::{ImportData, ImportKind}; use crate::macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; -use crate::Namespace::{MacroNS, TypeNS, ValueNS}; use crate::{ - errors, BindingKey, Determinacy, ExternPreludeEntry, Finalize, MacroData, Module, ModuleKind, + BindingKey, Determinacy, ExternPreludeEntry, Finalize, MacroData, Module, ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingData, NameBindingKind, ParentScope, PathResult, ResolutionError, Resolver, ResolverArenas, Segment, ToNameBinding, Used, VisResolutionError, + errors, }; type Res = def::Res; @@ -565,13 +566,10 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> { Some(rename) => source.ident.span.to(rename.span), None => source.ident.span, }; - self.r.report_error( - span, - ResolutionError::SelfImportsOnlyAllowedWithin { - root: parent.is_none(), - span_with_rename, - }, - ); + self.r.report_error(span, ResolutionError::SelfImportsOnlyAllowedWithin { + root: parent.is_none(), + span_with_rename, + }); // Error recovery: replace `use foo::self;` with `use foo;` if let Some(parent) = module_path.pop() { diff --git a/compiler/rustc_resolve/src/check_unused.rs b/compiler/rustc_resolve/src/check_unused.rs index 8c434007f2c86..3080a0c9892dd 100644 --- a/compiler/rustc_resolve/src/check_unused.rs +++ b/compiler/rustc_resolve/src/check_unused.rs @@ -29,15 +29,15 @@ use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; use rustc_data_structures::unord::UnordSet; use rustc_errors::MultiSpan; use rustc_hir::def::{DefKind, Res}; +use rustc_session::lint::BuiltinLintDiag; use rustc_session::lint::builtin::{ MACRO_USE_EXTERN_CRATE, UNUSED_EXTERN_CRATES, UNUSED_IMPORTS, UNUSED_QUALIFICATIONS, }; -use rustc_session::lint::BuiltinLintDiag; -use rustc_span::symbol::{kw, Ident}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, kw}; +use rustc_span::{DUMMY_SP, Span}; use crate::imports::{Import, ImportKind}; -use crate::{module_to_string, LexicalScopeBinding, NameBindingKind, Resolver}; +use crate::{LexicalScopeBinding, NameBindingKind, Resolver, module_to_string}; struct UnusedImport { use_tree: ast::UseTree, diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index fc9d8f998dc27..98662385434c3 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -7,9 +7,9 @@ use rustc_expand::expand::AstFragment; use rustc_hir as hir; use rustc_hir::def::{CtorKind, CtorOf, DefKind}; use rustc_hir::def_id::LocalDefId; -use rustc_span::hygiene::LocalExpnId; -use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; +use rustc_span::hygiene::LocalExpnId; +use rustc_span::symbol::{Symbol, kw, sym}; use tracing::debug; use crate::{ImplTraitContext, InvocationParent, PendingAnonConstInfo, Resolver}; @@ -127,15 +127,12 @@ impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> { fn visit_macro_invoc(&mut self, id: NodeId) { let id = id.placeholder_to_expn_id(); let pending_anon_const_info = self.pending_anon_const_info.take(); - let old_parent = self.resolver.invocation_parents.insert( - id, - InvocationParent { - parent_def: self.parent_def, - pending_anon_const_info, - impl_trait_context: self.impl_trait_context, - in_attr: self.in_attr, - }, - ); + let old_parent = self.resolver.invocation_parents.insert(id, InvocationParent { + parent_def: self.parent_def, + pending_anon_const_info, + impl_trait_context: self.impl_trait_context, + in_attr: self.in_attr, + }); assert!(old_parent.is_none(), "parent `LocalDefId` is reset for an invocation"); } diff --git a/compiler/rustc_resolve/src/diagnostics.rs b/compiler/rustc_resolve/src/diagnostics.rs index 3b69ecee35712..46e30c614ab4d 100644 --- a/compiler/rustc_resolve/src/diagnostics.rs +++ b/compiler/rustc_resolve/src/diagnostics.rs @@ -2,36 +2,36 @@ use rustc_ast::expand::StrippedCfgItem; use rustc_ast::ptr::P; use rustc_ast::visit::{self, Visitor}; use rustc_ast::{ - self as ast, Crate, ItemKind, MetaItemKind, ModKind, NestedMetaItem, NodeId, Path, - CRATE_NODE_ID, + self as ast, CRATE_NODE_ID, Crate, ItemKind, MetaItemKind, ModKind, NestedMetaItem, NodeId, + Path, }; use rustc_ast_pretty::pprust; use rustc_data_structures::fx::FxHashSet; use rustc_errors::codes::*; use rustc_errors::{ - report_ambiguity_error, struct_span_code_err, Applicability, Diag, DiagCtxtHandle, - ErrorGuaranteed, MultiSpan, SuggestionStyle, + Applicability, Diag, DiagCtxtHandle, ErrorGuaranteed, MultiSpan, SuggestionStyle, + report_ambiguity_error, struct_span_code_err, }; use rustc_feature::BUILTIN_ATTRIBUTES; +use rustc_hir::PrimTy; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, CtorOf, DefKind, NonMacroAttrKind, PerNS}; -use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; -use rustc_hir::PrimTy; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; use rustc_middle::bug; use rustc_middle::ty::TyCtxt; +use rustc_session::Session; use rustc_session::lint::builtin::{ ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, AMBIGUOUS_GLOB_IMPORTS, MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS, }; use rustc_session::lint::{AmbiguityErrorDiag, BuiltinLintDiag}; -use rustc_session::Session; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::edition::Edition; use rustc_span::hygiene::MacroKind; use rustc_span::source_map::SourceMap; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use rustc_span::{BytePos, Span, SyntaxContext}; -use thin_vec::{thin_vec, ThinVec}; +use thin_vec::{ThinVec, thin_vec}; use tracing::debug; use crate::errors::{ @@ -41,11 +41,11 @@ use crate::errors::{ use crate::imports::{Import, ImportKind}; use crate::late::{PatternSource, Rib}; use crate::{ - errors as errs, path_names_to_string, AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, - BindingError, BindingKey, Finalize, HasGenericParams, LexicalScopeBinding, MacroRulesScope, - Module, ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult, - PrivacyError, ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used, - VisResolutionError, + AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, BindingKey, Finalize, + HasGenericParams, LexicalScopeBinding, MacroRulesScope, Module, ModuleKind, + ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, + ResolutionError, Resolver, Scope, ScopeSet, Segment, UseError, Used, VisResolutionError, + errors as errs, path_names_to_string, }; type Res = def::Res; @@ -1002,10 +1002,14 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { VisResolutionError::AncestorOnly(span) => { self.dcx().create_err(errs::AncestorOnly(span)) } - VisResolutionError::FailedToResolve(span, label, suggestion) => self.into_struct_error( - span, - ResolutionError::FailedToResolve { segment: None, label, suggestion, module: None }, - ), + VisResolutionError::FailedToResolve(span, label, suggestion) => { + self.into_struct_error(span, ResolutionError::FailedToResolve { + segment: None, + label, + suggestion, + module: None, + }) + } VisResolutionError::ExpectedFound(span, path_str, res) => { self.dcx().create_err(errs::ExpectedModuleFound { span, res, path_str }) } diff --git a/compiler/rustc_resolve/src/effective_visibilities.rs b/compiler/rustc_resolve/src/effective_visibilities.rs index c91eed0e39b36..e279d14704e05 100644 --- a/compiler/rustc_resolve/src/effective_visibilities.rs +++ b/compiler/rustc_resolve/src/effective_visibilities.rs @@ -1,9 +1,9 @@ use std::mem; use rustc_ast::visit::Visitor; -use rustc_ast::{ast, visit, Crate, EnumDef}; +use rustc_ast::{Crate, EnumDef, ast, visit}; use rustc_data_structures::fx::FxHashSet; -use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; use rustc_middle::middle::privacy::{EffectiveVisibilities, EffectiveVisibility, Level}; use rustc_middle::ty::Visibility; use tracing::info; diff --git a/compiler/rustc_resolve/src/errors.rs b/compiler/rustc_resolve/src/errors.rs index 58834d0a2b3a6..f605b7096f0c2 100644 --- a/compiler/rustc_resolve/src/errors.rs +++ b/compiler/rustc_resolve/src/errors.rs @@ -1,11 +1,11 @@ use rustc_errors::codes::*; use rustc_errors::{Applicability, ElidedLifetimeInPathSubdiag, MultiSpan}; use rustc_macros::{Diagnostic, Subdiagnostic}; -use rustc_span::symbol::{Ident, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Ident, Symbol}; -use crate::late::PatternSource; use crate::Res; +use crate::late::PatternSource; #[derive(Diagnostic)] #[diag(resolve_generic_params_from_outer_item, code = E0401)] diff --git a/compiler/rustc_resolve/src/ident.rs b/compiler/rustc_resolve/src/ident.rs index 61df051ec1e46..8ae77902bce60 100644 --- a/compiler/rustc_resolve/src/ident.rs +++ b/compiler/rustc_resolve/src/ident.rs @@ -1,27 +1,27 @@ +use Determinacy::*; +use Namespace::*; use rustc_ast::{self as ast, NodeId}; use rustc_errors::ErrorGuaranteed; use rustc_hir::def::{DefKind, Namespace, NonMacroAttrKind, PartialRes, PerNS}; use rustc_middle::{bug, ty}; -use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK; use rustc_session::lint::BuiltinLintDiag; +use rustc_session::lint::builtin::PROC_MACRO_DERIVE_RESOLUTION_FALLBACK; use rustc_session::parse::feature_err; use rustc_span::def_id::LocalDefId; use rustc_span::hygiene::{ExpnId, ExpnKind, LocalExpnId, MacroKind, SyntaxContext}; -use rustc_span::symbol::{kw, Ident}; -use rustc_span::{sym, Span}; +use rustc_span::symbol::{Ident, kw}; +use rustc_span::{Span, sym}; use tracing::{debug, instrument}; -use Determinacy::*; -use Namespace::*; use crate::errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst}; use crate::imports::Import; use crate::late::{ConstantHasGenerics, NoConstantGenericsReason, PathSource, Rib, RibKind}; -use crate::macros::{sub_namespace_match, MacroRulesScope}; +use crate::macros::{MacroRulesScope, sub_namespace_match}; use crate::{ - errors, AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingKey, Determinacy, Finalize, + AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingKey, Determinacy, Finalize, ImportKind, LexicalScopeBinding, Module, ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, Res, ResolutionError, Resolver, Scope, - ScopeSet, Segment, ToNameBinding, Used, Weak, + ScopeSet, Segment, ToNameBinding, Used, Weak, errors, }; type Visibility = ty::Visibility; @@ -1218,25 +1218,21 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } Some(_) => None, }; - ( - rib_ident.span, - AttemptToUseNonConstantValueInConstant { - ident: original_rib_ident_def, - suggestion: "const", - current: "let", - type_span, - }, - ) + (rib_ident.span, AttemptToUseNonConstantValueInConstant { + ident: original_rib_ident_def, + suggestion: "const", + current: "let", + type_span, + }) } - Some((ident, kind)) => ( - span, - AttemptToUseNonConstantValueInConstant { + Some((ident, kind)) => { + (span, AttemptToUseNonConstantValueInConstant { ident, suggestion: "let", current: kind.as_str(), type_span: None, - }, - ), + }) + } }; self.report_error(span, resolution_error); } @@ -1244,13 +1240,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } RibKind::ConstParamTy => { if let Some(span) = finalize { - self.report_error( - span, - ParamInTyOfConstParam { - name: rib_ident.name, - param_kind: None, - }, - ); + self.report_error(span, ParamInTyOfConstParam { + name: rib_ident.name, + param_kind: None, + }); } return Res::Err; } @@ -1331,13 +1324,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } RibKind::ConstParamTy => { if let Some(span) = finalize { - self.report_error( - span, - ResolutionError::ParamInTyOfConstParam { - name: rib_ident.name, - param_kind: Some(errors::ParamKindInTyOfConstParam::Type), - }, - ); + self.report_error(span, ResolutionError::ParamInTyOfConstParam { + name: rib_ident.name, + param_kind: Some(errors::ParamKindInTyOfConstParam::Type), + }); } return Res::Err; } @@ -1400,13 +1390,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } RibKind::ConstParamTy => { if let Some(span) = finalize { - self.report_error( - span, - ResolutionError::ParamInTyOfConstParam { - name: rib_ident.name, - param_kind: Some(errors::ParamKindInTyOfConstParam::Const), - }, - ); + self.report_error(span, ResolutionError::ParamInTyOfConstParam { + name: rib_ident.name, + param_kind: Some(errors::ParamKindInTyOfConstParam::Const), + }); } return Res::Err; } diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 67ee377fd5492..51fbcb8ebb805 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -7,36 +7,36 @@ use rustc_ast::NodeId; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::intern::Interned; 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::def::{self, DefKind, PartialRes}; use rustc_hir::def_id::DefId; use rustc_middle::metadata::{ModChild, Reexport}; use rustc_middle::{span_bug, ty}; +use rustc_session::lint::BuiltinLintDiag; use rustc_session::lint::builtin::{ AMBIGUOUS_GLOB_REEXPORTS, HIDDEN_GLOB_REEXPORTS, PUB_USE_OF_PRIVATE_EXTERN_CRATE, REDUNDANT_IMPORTS, UNUSED_IMPORTS, }; -use rustc_session::lint::BuiltinLintDiag; +use rustc_span::Span; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::hygiene::LocalExpnId; -use rustc_span::symbol::{kw, Ident, Symbol}; -use rustc_span::Span; +use rustc_span::symbol::{Ident, Symbol, kw}; use smallvec::SmallVec; use tracing::debug; -use crate::diagnostics::{import_candidates, DiagMode, Suggestion}; +use crate::Determinacy::{self, *}; +use crate::Namespace::*; +use crate::diagnostics::{DiagMode, Suggestion, import_candidates}; use crate::errors::{ CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate, CannotBeReexportedPrivateNS, CannotDetermineImportResolution, CannotGlobImportAllCrates, ConsiderAddingMacroExport, ConsiderMarkingAsPub, IsNotDirectlyImportable, ItemsInTraitsAreNotImportable, }; -use crate::Determinacy::{self, *}; -use crate::Namespace::*; use crate::{ - module_to_string, names_to_string, AmbiguityError, AmbiguityKind, BindingKey, Finalize, - ImportSuggestion, Module, ModuleOrUniformRoot, NameBinding, NameBindingData, NameBindingKind, - ParentScope, PathResult, PerNS, ResolutionError, Resolver, ScopeSet, Segment, Used, + AmbiguityError, AmbiguityKind, BindingKey, Finalize, ImportSuggestion, Module, + ModuleOrUniformRoot, NameBinding, NameBindingData, NameBindingKind, ParentScope, PathResult, + PerNS, ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string, names_to_string, }; type Res = def::Res; @@ -901,15 +901,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { } => { if no_ambiguity { assert!(import.imported_module.get().is_none()); - self.report_error( - span, - ResolutionError::FailedToResolve { - segment: Some(segment_name), - label, - suggestion, - module, - }, - ); + self.report_error(span, ResolutionError::FailedToResolve { + segment: Some(segment_name), + label, + suggestion, + module, + }); } return None; } diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 4c84e3621dc41..66c1ff93ce1ce 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -8,19 +8,19 @@ use std::assert_matches::debug_assert_matches; use std::borrow::Cow; -use std::collections::hash_map::Entry; use std::collections::BTreeSet; +use std::collections::hash_map::Entry; use std::mem::{replace, swap, take}; use rustc_ast::ptr::P; -use rustc_ast::visit::{visit_opt, walk_list, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor}; +use rustc_ast::visit::{AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor, visit_opt, walk_list}; use rustc_ast::*; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_errors::codes::*; use rustc_errors::{Applicability, DiagArgValue, IntoDiagArg, StashKey, Suggestions}; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS}; -use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::{MissingLifetimeKind, PrimTy, TraitCandidate}; use rustc_middle::middle::resolve_bound_vars::Set1; use rustc_middle::ty::DelegationFnSig; @@ -28,16 +28,16 @@ use rustc_middle::{bug, span_bug}; use rustc_session::config::{CrateType, ResolveDocLinks}; use rustc_session::lint::{self, BuiltinLintDiag}; use rustc_session::parse::feature_err; -use rustc_span::source_map::{respan, Spanned}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; +use rustc_span::source_map::{Spanned, respan}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use rustc_span::{BytePos, Span, SyntaxContext}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use tracing::{debug, instrument, trace}; use crate::{ - errors, path_names_to_string, rustdoc, BindingError, BindingKey, Finalize, LexicalScopeBinding, - Module, ModuleOrUniformRoot, NameBinding, ParentScope, PathResult, ResolutionError, Resolver, - Segment, TyCtxt, UseError, Used, + BindingError, BindingKey, Finalize, LexicalScopeBinding, Module, ModuleOrUniformRoot, + NameBinding, ParentScope, PathResult, ResolutionError, Resolver, Segment, TyCtxt, UseError, + Used, errors, path_names_to_string, rustdoc, }; mod diagnostics; @@ -1801,11 +1801,9 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { && Some(true) == self.diag_metadata.in_non_gat_assoc_type && let crate::ModuleKind::Def(DefKind::Trait, trait_id, _) = module.kind { - if def_id_matches_path( - self.r.tcx, - trait_id, - &["core", "iter", "traits", "iterator", "Iterator"], - ) { + if def_id_matches_path(self.r.tcx, trait_id, &[ + "core", "iter", "traits", "iterator", "Iterator", + ]) { self.r.dcx().emit_err(errors::LendingIteratorReportError { lifetime: lifetime.ident.span, ty: ty.span, @@ -3412,14 +3410,11 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { match seen_trait_items.entry(id_in_trait) { Entry::Occupied(entry) => { - self.report_error( - span, - ResolutionError::TraitImplDuplicate { - name: ident.name, - old_span: *entry.get(), - trait_item_span: binding.span, - }, - ); + self.report_error(span, ResolutionError::TraitImplDuplicate { + name: ident.name, + old_span: *entry.get(), + trait_item_span: binding.span, + }); return; } Entry::Vacant(entry) => { @@ -3450,16 +3445,13 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { } }; let trait_path = path_names_to_string(path); - self.report_error( - span, - ResolutionError::TraitImplMismatch { - name: ident.name, - kind, - code, - trait_path, - trait_item_span: binding.span, - }, - ); + self.report_error(span, ResolutionError::TraitImplMismatch { + name: ident.name, + kind, + code, + trait_path, + trait_item_span: binding.span, + }); } fn resolve_const_body(&mut self, expr: &'ast Expr, item: Option<(Ident, ConstantItemKind)>) { @@ -4447,15 +4439,12 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> { module, segment_name, } => { - return Err(respan( - span, - ResolutionError::FailedToResolve { - segment: Some(segment_name), - label, - suggestion, - module, - }, - )); + return Err(respan(span, ResolutionError::FailedToResolve { + segment: Some(segment_name), + label, + suggestion, + module, + })); } PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None), PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"), diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index b5974e001aa90..35d166e8b4ab3 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -5,30 +5,30 @@ use std::iter; use std::ops::Deref; use rustc_ast::ptr::P; -use rustc_ast::visit::{walk_ty, FnCtxt, FnKind, LifetimeCtxt, Visitor}; +use rustc_ast::visit::{FnCtxt, FnKind, LifetimeCtxt, Visitor, walk_ty}; use rustc_ast::{ - self as ast, AssocItemKind, Expr, ExprKind, GenericParam, GenericParamKind, Item, ItemKind, - MethodCall, NodeId, Path, Ty, TyKind, DUMMY_NODE_ID, + self as ast, AssocItemKind, DUMMY_NODE_ID, Expr, ExprKind, GenericParam, GenericParamKind, + Item, ItemKind, MethodCall, NodeId, Path, Ty, TyKind, }; use rustc_ast_pretty::pprust::where_bound_predicate_to_string; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_errors::codes::*; use rustc_errors::{ - pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, - SuggestionStyle, + Applicability, Diag, ErrorGuaranteed, MultiSpan, SuggestionStyle, pluralize, + struct_span_code_err, }; use rustc_hir as hir; use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{self, CtorKind, CtorOf, DefKind}; -use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; use rustc_hir::{MissingLifetimeKind, PrimTy}; use rustc_middle::ty; -use rustc_session::{lint, Session}; +use rustc_session::{Session, lint}; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::edition::Edition; use rustc_span::hygiene::MacroKind; -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 thin_vec::ThinVec; use tracing::debug; @@ -40,8 +40,8 @@ use crate::late::{ }; use crate::ty::fast_reject::SimplifiedType; use crate::{ - errors, path_names_to_string, Module, ModuleKind, ModuleOrUniformRoot, PathResult, PathSource, - Segment, + Module, ModuleKind, ModuleOrUniformRoot, PathResult, PathSource, Segment, errors, + path_names_to_string, }; type Res = def::Res; @@ -1017,15 +1017,12 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { debug!("smart_resolve_path_fragment: E0424, source={:?}", source); err.code(E0424); - err.span_label( - span, - match source { - PathSource::Pat => { - "`self` value is a keyword and may not be bound to variables or shadowed" - } - _ => "`self` value is a keyword only available in methods with a `self` parameter", - }, - ); + err.span_label(span, match source { + PathSource::Pat => { + "`self` value is a keyword and may not be bound to variables or shadowed" + } + _ => "`self` value is a keyword only available in methods with a `self` parameter", + }); let is_assoc_fn = self.self_type_is_available(); let self_from_macro = "a `self` parameter, but a macro invocation can only \ access identifiers it receives from parameters"; @@ -1828,10 +1825,12 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { // Doing analysis on local `DefId`s would cause infinite recursion. return; } - let Ok(impls) = self.r.tcx.inherent_impls(def_id) else { return }; // Look at all the associated functions without receivers in the type's // inherent impls to look for builders that return `Self` - let mut items = impls + let mut items = self + .r + .tcx + .inherent_impls(def_id) .iter() .flat_map(|i| self.r.tcx.associated_items(i).in_definition_order()) // Only assoc fn with no receivers. @@ -2309,18 +2308,15 @@ impl<'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> { if module_def_id == def_id { let path = Path { span: name_binding.span, segments: path_segments, tokens: None }; - result = Some(( - module, - ImportSuggestion { - did: Some(def_id), - descr: "module", - path, - accessible: true, - doc_visible, - note: None, - via_import: false, - }, - )); + result = Some((module, ImportSuggestion { + did: Some(def_id), + descr: "module", + path, + accessible: true, + doc_visible, + note: None, + via_import: false, + })); } else { // add the module to the lookup if seen_modules.insert(module_def_id) { diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 3bb1f6b52a76a..b84408cd0cb7a 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -40,8 +40,8 @@ use rustc_arena::{DroplessArena, TypedArena}; use rustc_ast::expand::StrippedCfgItem; use rustc_ast::node_id::NodeMap; use rustc_ast::{ - self as ast, attr, AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, - NodeId, Path, CRATE_NODE_ID, + self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs, + LitKind, NodeId, Path, attr, }; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::intern::Interned; @@ -54,7 +54,7 @@ use rustc_hir::def::Namespace::{self, *}; use rustc_hir::def::{ self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, NonMacroAttrKind, PartialRes, PerNS, }; -use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LocalDefIdMap, CRATE_DEF_ID, LOCAL_CRATE}; +use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap}; use rustc_hir::{PrimTy, TraitCandidate}; use rustc_index::IndexVec; use rustc_metadata::creader::{CStore, CrateLoader}; @@ -70,9 +70,9 @@ use rustc_query_system::ich::StableHashingContext; use rustc_session::lint::builtin::PRIVATE_MACRO_USE; use rustc_session::lint::{BuiltinLintDiag, LintBuffer}; use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{Span, DUMMY_SP}; -use smallvec::{smallvec, SmallVec}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, Span}; +use smallvec::{SmallVec, smallvec}; use tracing::debug; type Res = def::Res; diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index b4f277c4244c8..21924437a4a46 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -5,7 +5,7 @@ use std::cell::Cell; use std::mem; use rustc_ast::expand::StrippedCfgItem; -use rustc_ast::{self as ast, attr, Crate, Inline, ItemKind, ModKind, NodeId}; +use rustc_ast::{self as ast, Crate, Inline, ItemKind, ModKind, NodeId, attr}; use rustc_ast_pretty::pprust; use rustc_attr::StabilityLevel; use rustc_data_structures::intern::Interned; @@ -23,24 +23,24 @@ use rustc_hir::def::{self, DefKind, Namespace, NonMacroAttrKind}; use rustc_hir::def_id::{CrateNum, DefId, LocalDefId}; use rustc_middle::middle::stability; use rustc_middle::ty::{RegisteredTools, TyCtxt, Visibility}; +use rustc_session::lint::BuiltinLintDiag; use rustc_session::lint::builtin::{ LEGACY_DERIVE_HELPERS, OUT_OF_SCOPE_MACRO_CALLS, SOFT_UNSTABLE, - UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, UNUSED_MACROS, UNUSED_MACRO_RULES, + UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, UNUSED_MACRO_RULES, UNUSED_MACROS, }; -use rustc_session::lint::BuiltinLintDiag; use rustc_session::parse::feature_err; use rustc_span::edit_distance::edit_distance; use rustc_span::edition::Edition; use rustc_span::hygiene::{self, AstPass, ExpnData, ExpnKind, LocalExpnId, MacroKind}; -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 crate::Namespace::*; use crate::errors::{ self, AddAsNonDerive, CannotDetermineMacroResolution, CannotFindIdentInThisScope, MacroExpectedFound, RemoveSurroundingDerive, }; use crate::imports::Import; -use crate::Namespace::*; use crate::{ BindingKey, BuiltinMacroState, DeriveData, Determinacy, Finalize, InvocationParent, MacroData, ModuleKind, ModuleOrUniformRoot, NameBinding, NameBindingKind, ParentScope, PathResult, @@ -914,15 +914,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> { None, ) }; - self.report_error( - span, - ResolutionError::FailedToResolve { - segment: path.last().map(|segment| segment.ident.name), - label, - suggestion, - module, - }, - ); + self.report_error(span, ResolutionError::FailedToResolve { + segment: path.last().map(|segment| segment.ident.name), + label, + suggestion, + module, + }); } PathResult::Module(..) | PathResult::Indeterminate => unreachable!(), } diff --git a/compiler/rustc_resolve/src/rustdoc.rs b/compiler/rustc_resolve/src/rustdoc.rs index bed3baa30fb26..d1c1b6c882eaa 100644 --- a/compiler/rustc_resolve/src/rustdoc.rs +++ b/compiler/rustc_resolve/src/rustdoc.rs @@ -9,8 +9,8 @@ use rustc_ast::util::comments::beautify_doc_string; use rustc_data_structures::fx::FxHashMap; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::DefId; -use rustc_span::symbol::{kw, sym, Symbol}; -use rustc_span::{InnerSpan, Span, DUMMY_SP}; +use rustc_span::symbol::{Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, InnerSpan, Span}; use tracing::{debug, trace}; #[derive(Clone, Copy, PartialEq, Eq, Debug)] diff --git a/compiler/rustc_sanitizers/src/cfi/mod.rs b/compiler/rustc_sanitizers/src/cfi/mod.rs index 90dab5e0333a1..fa14f3f0c5448 100644 --- a/compiler/rustc_sanitizers/src/cfi/mod.rs +++ b/compiler/rustc_sanitizers/src/cfi/mod.rs @@ -3,4 +3,4 @@ //! For more information about LLVM CFI and cross-language LLVM CFI support for the Rust compiler, //! see design document in the tracking issue #89653. pub mod typeid; -pub use crate::cfi::typeid::{typeid_for_fnabi, typeid_for_instance, TypeIdOptions}; +pub use crate::cfi::typeid::{TypeIdOptions, typeid_for_fnabi, typeid_for_instance}; diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs index 9c2f869f35768..320d66163848f 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs @@ -7,7 +7,7 @@ use std::fmt::Write as _; -use rustc_data_structures::base_n::{ToBaseN, ALPHANUMERIC_ONLY, CASE_INSENSITIVE}; +use rustc_data_structures::base_n::{ALPHANUMERIC_ONLY, CASE_INSENSITIVE, ToBaseN}; use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_middle::bug; @@ -22,8 +22,8 @@ use rustc_target::abi::Integer; use rustc_target::spec::abi::Abi; use tracing::instrument; -use crate::cfi::typeid::itanium_cxx_abi::transform::{TransformTy, TransformTyOptions}; use crate::cfi::typeid::TypeIdOptions; +use crate::cfi::typeid::itanium_cxx_abi::transform::{TransformTy, TransformTyOptions}; /// Options for encode_ty. pub(crate) type EncodeTyOptions = TypeIdOptions; diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/mod.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/mod.rs index cb15c67b895b8..39842763bfec6 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/mod.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/mod.rs @@ -12,11 +12,11 @@ use tracing::instrument; mod encode; mod transform; -use crate::cfi::typeid::itanium_cxx_abi::encode::{encode_ty, DictKey, EncodeTyOptions}; +use crate::cfi::typeid::TypeIdOptions; +use crate::cfi::typeid::itanium_cxx_abi::encode::{DictKey, EncodeTyOptions, encode_ty}; use crate::cfi::typeid::itanium_cxx_abi::transform::{ - transform_instance, TransformTy, TransformTyOptions, + TransformTy, TransformTyOptions, transform_instance, }; -use crate::cfi::typeid::TypeIdOptions; /// Returns a type metadata identifier for the specified FnAbi using the Itanium C++ ABI with vendor /// extended type qualifiers and types for Rust types that are not used at the FFI boundary. diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs index e4231d755067f..80a9ba79c2851 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs @@ -19,8 +19,8 @@ use rustc_span::sym; use rustc_trait_selection::traits; use tracing::{debug, instrument}; -use crate::cfi::typeid::itanium_cxx_abi::encode::EncodeTyOptions; use crate::cfi::typeid::TypeIdOptions; +use crate::cfi::typeid::itanium_cxx_abi::encode::EncodeTyOptions; /// Options for transform_ty. pub(crate) type TransformTyOptions = TypeIdOptions; diff --git a/compiler/rustc_sanitizers/src/kcfi/mod.rs b/compiler/rustc_sanitizers/src/kcfi/mod.rs index a8b632940b040..4e0a7cdf1fb4e 100644 --- a/compiler/rustc_sanitizers/src/kcfi/mod.rs +++ b/compiler/rustc_sanitizers/src/kcfi/mod.rs @@ -4,4 +4,4 @@ //! For more information about LLVM KCFI and cross-language LLVM KCFI support for the Rust compiler, //! see the tracking issue #123479. pub mod typeid; -pub use crate::kcfi::typeid::{typeid_for_fnabi, typeid_for_instance, TypeIdOptions}; +pub use crate::kcfi::typeid::{TypeIdOptions, typeid_for_fnabi, typeid_for_instance}; diff --git a/compiler/rustc_sanitizers/src/kcfi/typeid/mod.rs b/compiler/rustc_sanitizers/src/kcfi/typeid/mod.rs index b47a091ab64d2..5e2e6a2b8ed6e 100644 --- a/compiler/rustc_sanitizers/src/kcfi/typeid/mod.rs +++ b/compiler/rustc_sanitizers/src/kcfi/typeid/mod.rs @@ -10,7 +10,7 @@ use rustc_middle::ty::{Instance, InstanceKind, ReifyReason, Ty, TyCtxt}; use rustc_target::abi::call::FnAbi; use twox_hash::XxHash64; -pub use crate::cfi::typeid::{itanium_cxx_abi, TypeIdOptions}; +pub use crate::cfi::typeid::{TypeIdOptions, itanium_cxx_abi}; /// Returns a KCFI type metadata identifier for the specified FnAbi. pub fn typeid_for_fnabi<'tcx>( diff --git a/compiler/rustc_serialize/tests/leb128.rs b/compiler/rustc_serialize/tests/leb128.rs index b06a28d7c95df..aef55d15e60de 100644 --- a/compiler/rustc_serialize/tests/leb128.rs +++ b/compiler/rustc_serialize/tests/leb128.rs @@ -1,6 +1,6 @@ -use rustc_serialize::leb128::*; -use rustc_serialize::opaque::{MemDecoder, MAGIC_END_BYTES}; use rustc_serialize::Decoder; +use rustc_serialize::leb128::*; +use rustc_serialize::opaque::{MAGIC_END_BYTES, MemDecoder}; macro_rules! impl_test_unsigned_leb128 { ($test_name:ident, $write_fn_name:ident, $read_fn_name:ident, $int_ty:ident) => { diff --git a/compiler/rustc_session/src/code_stats.rs b/compiler/rustc_session/src/code_stats.rs index 3668fe4f0a807..7a32c0c26555e 100644 --- a/compiler/rustc_session/src/code_stats.rs +++ b/compiler/rustc_session/src/code_stats.rs @@ -2,8 +2,8 @@ use std::cmp; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::sync::Lock; -use rustc_span::def_id::DefId; use rustc_span::Symbol; +use rustc_span::def_id::DefId; use rustc_target::abi::{Align, Size}; #[derive(Clone, PartialEq, Eq, Hash, Debug)] diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 1132d0efebf33..b052d8d72c7d8 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -20,10 +20,10 @@ use rustc_errors::emitter::HumanReadableErrorType; use rustc_errors::{ColorConfig, DiagArgValue, DiagCtxtFlags, IntoDiagArg}; use rustc_feature::UnstableFeatures; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_span::edition::{Edition, DEFAULT_EDITION, EDITION_NAME_LIST, LATEST_STABLE_EDITION}; +use rustc_span::edition::{DEFAULT_EDITION, EDITION_NAME_LIST, Edition, LATEST_STABLE_EDITION}; use rustc_span::source_map::FilePathMapping; use rustc_span::{ - sym, FileName, FileNameDisplayPreference, RealFileName, SourceFileHashAlgorithm, Symbol, + FileName, FileNameDisplayPreference, RealFileName, SourceFileHashAlgorithm, Symbol, sym, }; use rustc_target::spec::{ FramePointer, LinkSelfContainedComponents, LinkerFeatures, SplitDebuginfo, Target, TargetTriple, @@ -34,7 +34,7 @@ use crate::errors::FileWriteFail; pub use crate::options::*; use crate::search_paths::SearchPath; use crate::utils::{CanonicalizedPath, NativeLib, NativeLibKind}; -use crate::{filesearch, lint, EarlyDiagCtxt, HashStableContext, Session}; +use crate::{EarlyDiagCtxt, HashStableContext, Session, filesearch, lint}; mod cfg; pub mod sigpipe; @@ -3004,8 +3004,8 @@ pub(crate) mod dep_tracking { use rustc_data_structures::stable_hasher::Hash64; use rustc_errors::LanguageIdentifier; use rustc_feature::UnstableFeatures; - use rustc_span::edition::Edition; use rustc_span::RealFileName; + use rustc_span::edition::Edition; use rustc_target::spec::{ CodeModel, FramePointer, MergeFunctions, OnBrokenPipe, PanicStrategy, RelocModel, RelroLevel, SanitizerSet, SplitDebuginfo, StackProtector, TargetTriple, TlsModel, WasmCAbi, diff --git a/compiler/rustc_session/src/config/cfg.rs b/compiler/rustc_session/src/config/cfg.rs index 0fa776ecb5c18..44b96d92b1995 100644 --- a/compiler/rustc_session/src/config/cfg.rs +++ b/compiler/rustc_session/src/config/cfg.rs @@ -25,14 +25,14 @@ use std::iter; use rustc_ast::ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; -use rustc_lint_defs::builtin::EXPLICIT_BUILTIN_CFGS_IN_FLAGS; use rustc_lint_defs::BuiltinLintDiag; -use rustc_span::symbol::{sym, Symbol}; +use rustc_lint_defs::builtin::EXPLICIT_BUILTIN_CFGS_IN_FLAGS; +use rustc_span::symbol::{Symbol, sym}; use rustc_target::abi::Align; -use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, Target, TargetTriple, TARGETS}; +use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet, TARGETS, Target, TargetTriple}; -use crate::config::{CrateType, FmtDebug}; use crate::Session; +use crate::config::{CrateType, FmtDebug}; /// The parsed `--cfg` options that define the compilation environment of the /// crate, used to drive conditional compilation. diff --git a/compiler/rustc_session/src/cstore.rs b/compiler/rustc_session/src/cstore.rs index da7a82fee94d0..66ad70d8d18be 100644 --- a/compiler/rustc_session/src/cstore.rs +++ b/compiler/rustc_session/src/cstore.rs @@ -8,12 +8,12 @@ use std::path::PathBuf; use rustc_ast as ast; use rustc_data_structures::sync::{self, AppendOnlyIndexVec, FreezeLock}; use rustc_hir::def_id::{ - CrateNum, DefId, LocalDefId, StableCrateId, StableCrateIdMap, LOCAL_CRATE, + CrateNum, DefId, LOCAL_CRATE, LocalDefId, StableCrateId, StableCrateIdMap, }; use rustc_hir::definitions::{DefKey, DefPath, DefPathHash, Definitions}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; -use rustc_span::symbol::Symbol; use rustc_span::Span; +use rustc_span::symbol::Symbol; use rustc_target::spec::abi::Abi; use crate::search_paths::PathKind; diff --git a/compiler/rustc_session/src/filesearch.rs b/compiler/rustc_session/src/filesearch.rs index e72d4face3c87..4aae2649843b6 100644 --- a/compiler/rustc_session/src/filesearch.rs +++ b/compiler/rustc_session/src/filesearch.rs @@ -4,7 +4,7 @@ use std::path::{Path, PathBuf}; use std::{env, fs}; use rustc_fs_util::{fix_windows_verbatim_for_gcc, try_canonicalize}; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use crate::search_paths::{PathKind, SearchPath}; @@ -121,11 +121,11 @@ fn current_dll_path() -> Result { use std::io; use std::os::windows::prelude::*; - use windows::core::PCWSTR; use windows::Win32::Foundation::HMODULE; use windows::Win32::System::LibraryLoader::{ - GetModuleFileNameW, GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GetModuleFileNameW, GetModuleHandleExW, }; + use windows::core::PCWSTR; let mut module = HMODULE::default(); unsafe { diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index 62d3482a7f1c4..aac776d2919aa 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -20,7 +20,7 @@ use rustc_target::spec::{ use crate::config::*; use crate::search_paths::SearchPath; use crate::utils::NativeLib; -use crate::{lint, EarlyDiagCtxt}; +use crate::{EarlyDiagCtxt, lint}; macro_rules! insert { ($opt_name:ident, $opt_expr:expr, $sub_hashes:expr) => { diff --git a/compiler/rustc_session/src/output.rs b/compiler/rustc_session/src/output.rs index c2ca19e563cdd..357d746c1846f 100644 --- a/compiler/rustc_session/src/output.rs +++ b/compiler/rustc_session/src/output.rs @@ -7,12 +7,12 @@ use rustc_errors::FatalError; use rustc_span::symbol::sym; use rustc_span::{Span, Symbol}; +use crate::Session; use crate::config::{self, CrateType, Input, OutFileName, OutputFilenames, OutputType}; use crate::errors::{ self, CrateNameDoesNotMatch, CrateNameEmpty, CrateNameInvalid, FileIsNotWriteable, InvalidCharacterInCrateName, InvalidCrateNameHelp, }; -use crate::Session; pub fn out_filename( sess: &Session, diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 1db31f5b0a775..9781c74652081 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -7,17 +7,18 @@ use rustc_ast::attr::AttrIdGenerator; use rustc_ast::node_id::NodeId; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet}; use rustc_data_structures::sync::{AppendOnlyVec, Lock, Lrc}; -use rustc_errors::emitter::{stderr_destination, HumanEmitter, SilentEmitter}; +use rustc_errors::emitter::{HumanEmitter, SilentEmitter, stderr_destination}; use rustc_errors::{ - fallback_fluent_bundle, ColorConfig, Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, - EmissionGuarantee, MultiSpan, StashKey, + ColorConfig, Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, EmissionGuarantee, MultiSpan, + StashKey, fallback_fluent_bundle, }; -use rustc_feature::{find_feature_issue, GateIssue, UnstableFeatures}; +use rustc_feature::{GateIssue, UnstableFeatures, find_feature_issue}; use rustc_span::edition::Edition; use rustc_span::hygiene::ExpnId; use rustc_span::source_map::{FilePathMapping, SourceMap}; use rustc_span::{Span, Symbol}; +use crate::Session; use crate::config::{Cfg, CheckCfg}; use crate::errors::{ CliFeatureDiagnosticHelp, FeatureDiagnosticForIssue, FeatureDiagnosticHelp, @@ -25,7 +26,6 @@ use crate::errors::{ }; use crate::lint::builtin::UNSTABLE_SYNTAX_PRE_EXPANSION; use crate::lint::{BufferedEarlyLint, BuiltinLintDiag, Lint, LintId}; -use crate::Session; /// Collected spans during parsing for places where a certain feature was /// used and should be feature gated accordingly in `check_crate`. diff --git a/compiler/rustc_session/src/search_paths.rs b/compiler/rustc_session/src/search_paths.rs index b212f6afa1717..ac0d8661115d1 100644 --- a/compiler/rustc_session/src/search_paths.rs +++ b/compiler/rustc_session/src/search_paths.rs @@ -3,8 +3,8 @@ use std::path::{Path, PathBuf}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_target::spec::TargetTriple; -use crate::filesearch::make_target_lib_path; use crate::EarlyDiagCtxt; +use crate::filesearch::make_target_lib_path; #[derive(Clone, Debug)] pub struct SearchPath { diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 2d90177cceab3..adc28e3846254 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -2,9 +2,9 @@ use std::any::Any; use std::ops::{Div, Mul}; use std::path::{Path, PathBuf}; use std::str::FromStr; +use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst; -use std::sync::Arc; use std::{env, fmt, io}; use rustc_data_structures::flock; @@ -16,12 +16,12 @@ use rustc_data_structures::sync::{ }; use rustc_errors::annotate_snippet_emitter_writer::AnnotateSnippetEmitter; use rustc_errors::codes::*; -use rustc_errors::emitter::{stderr_destination, DynEmitter, HumanEmitter, HumanReadableErrorType}; +use rustc_errors::emitter::{DynEmitter, HumanEmitter, HumanReadableErrorType, stderr_destination}; use rustc_errors::json::JsonEmitter; use rustc_errors::registry::Registry; use rustc_errors::{ - fallback_fluent_bundle, Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, - ErrorGuaranteed, FatalAbort, FluentBundle, LazyFallbackBundle, TerminalUrl, + Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, FatalAbort, + FluentBundle, LazyFallbackBundle, TerminalUrl, fallback_fluent_bundle, }; use rustc_macros::HashStable_Generic; pub use rustc_span::def_id::StableCrateId; @@ -41,7 +41,7 @@ use crate::config::{ InstrumentCoverage, OptLevel, OutFileName, OutputType, RemapPathScopeComponents, SwitchWithOptPath, }; -use crate::parse::{add_feature_diagnostics, ParseSess}; +use crate::parse::{ParseSess, add_feature_diagnostics}; use crate::search_paths::{PathKind, SearchPath}; use crate::{errors, filesearch, lint}; diff --git a/compiler/rustc_session/src/version.rs b/compiler/rustc_session/src/version.rs index 79f97fd327ac7..1696eaf902b0d 100644 --- a/compiler/rustc_session/src/version.rs +++ b/compiler/rustc_session/src/version.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use std::fmt::{self, Display}; use rustc_errors::IntoDiagArg; -use rustc_macros::{current_rustc_version, Decodable, Encodable, HashStable_Generic}; +use rustc_macros::{Decodable, Encodable, HashStable_Generic, current_rustc_version}; #[derive(Encodable, Decodable, Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(HashStable_Generic)] diff --git a/compiler/rustc_smir/src/rustc_internal/mod.rs b/compiler/rustc_smir/src/rustc_internal/mod.rs index a3aa589cb643e..55b47817f9af1 100644 --- a/compiler/rustc_smir/src/rustc_internal/mod.rs +++ b/compiler/rustc_smir/src/rustc_internal/mod.rs @@ -13,12 +13,12 @@ use rustc_data_structures::fx::FxIndexMap; use rustc_middle::mir::interpret::AllocId; use rustc_middle::ty; use rustc_middle::ty::TyCtxt; -use rustc_span::def_id::{CrateNum, DefId}; use rustc_span::Span; +use rustc_span::def_id::{CrateNum, DefId}; use scoped_tls::scoped_thread_local; +use stable_mir::Error; use stable_mir::abi::Layout; use stable_mir::ty::IndexedVal; -use stable_mir::Error; use crate::rustc_smir::context::TablesWrapper; use crate::rustc_smir::{Stable, Tables}; diff --git a/compiler/rustc_smir/src/rustc_smir/alloc.rs b/compiler/rustc_smir/src/rustc_smir/alloc.rs index 11fbc005e37da..0d8740ae31f29 100644 --- a/compiler/rustc_smir/src/rustc_smir/alloc.rs +++ b/compiler/rustc_smir/src/rustc_smir/alloc.rs @@ -1,8 +1,8 @@ -use rustc_middle::mir::interpret::{alloc_range, AllocRange, Pointer}; use rustc_middle::mir::ConstValue; +use rustc_middle::mir::interpret::{AllocRange, Pointer, alloc_range}; +use stable_mir::Error; use stable_mir::mir::Mutability; use stable_mir::ty::{Allocation, ProvenanceMap}; -use stable_mir::Error; use crate::rustc_smir::{Stable, Tables}; diff --git a/compiler/rustc_smir/src/rustc_smir/context.rs b/compiler/rustc_smir/src/rustc_smir/context.rs index a4ede374a19dc..ed5d2d1e799e1 100644 --- a/compiler/rustc_smir/src/rustc_smir/context.rs +++ b/compiler/rustc_smir/src/rustc_smir/context.rs @@ -34,7 +34,7 @@ use stable_mir::{Crate, CrateDef, CrateItem, CrateNum, DefId, Error, Filename, I use crate::rustc_internal::RustcInternal; use crate::rustc_smir::builder::BodyBuilder; -use crate::rustc_smir::{alloc, new_item_kind, smir_crate, Stable, Tables}; +use crate::rustc_smir::{Stable, Tables, alloc, new_item_kind, smir_crate}; impl<'tcx> Context for TablesWrapper<'tcx> { fn target_info(&self) -> MachineInfo { diff --git a/compiler/rustc_smir/src/rustc_smir/convert/mir.rs b/compiler/rustc_smir/src/rustc_smir/convert/mir.rs index c442ca861d35b..0dbbc338e738b 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/mir.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/mir.rs @@ -6,9 +6,9 @@ use rustc_middle::{bug, mir}; use stable_mir::mir::alloc::GlobalAlloc; use stable_mir::mir::{ConstOperand, Statement, UserTypeProjection, VarDebugInfoFragment}; use stable_mir::ty::{Allocation, ConstantKind, MirConst}; -use stable_mir::{opaque, Error}; +use stable_mir::{Error, opaque}; -use crate::rustc_smir::{alloc, Stable, Tables}; +use crate::rustc_smir::{Stable, Tables, alloc}; impl<'tcx> Stable<'tcx> for mir::Body<'tcx> { type T = stable_mir::mir::Body; @@ -282,11 +282,12 @@ impl<'tcx> Stable<'tcx> for mir::CastKind { type T = stable_mir::mir::CastKind; fn stable(&self, tables: &mut Tables<'_>) -> Self::T { use rustc_middle::mir::CastKind::*; + use rustc_middle::ty::adjustment::PointerCoercion; match self { PointerExposeProvenance => stable_mir::mir::CastKind::PointerExposeAddress, PointerWithExposedProvenance => stable_mir::mir::CastKind::PointerWithExposedProvenance, - PointerCoercion(c) => stable_mir::mir::CastKind::PointerCoercion(c.stable(tables)), - DynStar => stable_mir::mir::CastKind::DynStar, + PointerCoercion(PointerCoercion::DynStar, _) => stable_mir::mir::CastKind::DynStar, + PointerCoercion(c, _) => stable_mir::mir::CastKind::PointerCoercion(c.stable(tables)), IntToInt => stable_mir::mir::CastKind::IntToInt, FloatToInt => stable_mir::mir::CastKind::FloatToInt, FloatToFloat => stable_mir::mir::CastKind::FloatToFloat, @@ -712,8 +713,9 @@ impl<'tcx> Stable<'tcx> for mir::interpret::GlobalAlloc<'tcx> { mir::interpret::GlobalAlloc::Function { instance, .. } => { GlobalAlloc::Function(instance.stable(tables)) } - mir::interpret::GlobalAlloc::VTable(ty, trait_ref) => { - GlobalAlloc::VTable(ty.stable(tables), trait_ref.stable(tables)) + mir::interpret::GlobalAlloc::VTable(ty, dyn_ty) => { + // FIXME: Should we record the whole vtable? + GlobalAlloc::VTable(ty.stable(tables), dyn_ty.principal().stable(tables)) } mir::interpret::GlobalAlloc::Static(def) => { GlobalAlloc::Static(tables.static_def(*def)) diff --git a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs index 74bdf97ac4458..ac9a023576261 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs @@ -6,7 +6,7 @@ use stable_mir::ty::{ AdtKind, FloatTy, GenericArgs, GenericParamDef, IntTy, Region, RigidTy, TyKind, UintTy, }; -use crate::rustc_smir::{alloc, Stable, Tables}; +use crate::rustc_smir::{Stable, Tables, alloc}; impl<'tcx> Stable<'tcx> for ty::AliasTyKind { type T = stable_mir::ty::AliasKind; @@ -119,6 +119,7 @@ impl<'tcx> Stable<'tcx> for ty::adjustment::PointerCoercion { } PointerCoercion::ArrayToPointer => stable_mir::mir::PointerCoercion::ArrayToPointer, PointerCoercion::Unsize => stable_mir::mir::PointerCoercion::Unsize, + PointerCoercion::DynStar => unreachable!("represented as `CastKind::DynStar` in smir"), } } } @@ -815,10 +816,12 @@ impl<'tcx> Stable<'tcx> for ty::RegionKind<'tcx> { index: early_reg.index, name: early_reg.name.to_string(), }), - ty::ReBound(db_index, bound_reg) => RegionKind::ReBound( - db_index.as_u32(), - BoundRegion { var: bound_reg.var.as_u32(), kind: bound_reg.kind.stable(tables) }, - ), + ty::ReBound(db_index, bound_reg) => { + RegionKind::ReBound(db_index.as_u32(), BoundRegion { + var: bound_reg.var.as_u32(), + kind: bound_reg.kind.stable(tables), + }) + } ty::ReStatic => RegionKind::ReStatic, ty::RePlaceholder(place_holder) => { RegionKind::RePlaceholder(stable_mir::ty::Placeholder { diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index a45b676acae73..f61ce37131eb4 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -1,12 +1,12 @@ use std::fmt; use std::hash::{BuildHasherDefault, Hash, Hasher}; +use rustc_data_structures::AtomicRef; use rustc_data_structures::fingerprint::Fingerprint; use rustc_data_structures::stable_hasher::{ Hash64, HashStable, StableHasher, StableOrd, ToStableHashKey, }; use rustc_data_structures::unhash::Unhasher; -use rustc_data_structures::AtomicRef; use rustc_index::Idx; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_serialize::{Decodable, Encodable}; diff --git a/compiler/rustc_span/src/hygiene.rs b/compiler/rustc_span/src/hygiene.rs index 463e0dbc30ce5..c57d516fcaed1 100644 --- a/compiler/rustc_span/src/hygiene.rs +++ b/compiler/rustc_span/src/hygiene.rs @@ -39,10 +39,10 @@ use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; use tracing::{debug, trace}; -use crate::def_id::{CrateNum, DefId, StableCrateId, CRATE_DEF_ID, LOCAL_CRATE}; +use crate::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, StableCrateId}; use crate::edition::Edition; -use crate::symbol::{kw, sym, Symbol}; -use crate::{with_session_globals, HashStableContext, Span, SpanDecoder, SpanEncoder, DUMMY_SP}; +use crate::symbol::{Symbol, kw, sym}; +use crate::{DUMMY_SP, HashStableContext, Span, SpanDecoder, SpanEncoder, with_session_globals}; /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks". #[derive(Clone, Copy, PartialEq, Eq, Hash)] diff --git a/compiler/rustc_span/src/lib.rs b/compiler/rustc_span/src/lib.rs index c7bd7321f0c5c..9dbdab84a81e1 100644 --- a/compiler/rustc_span/src/lib.rs +++ b/compiler/rustc_span/src/lib.rs @@ -39,7 +39,7 @@ extern crate self as rustc_span; use derive_where::derive_where; -use rustc_data_structures::{outline, AtomicRef}; +use rustc_data_structures::{AtomicRef, outline}; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_serialize::opaque::{FileEncoder, MemDecoder}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; @@ -60,13 +60,13 @@ pub use hygiene::{ }; use rustc_data_structures::stable_hasher::HashingControls; pub mod def_id; -use def_id::{CrateNum, DefId, DefIndex, DefPathHash, LocalDefId, StableCrateId, LOCAL_CRATE}; +use def_id::{CrateNum, DefId, DefIndex, DefPathHash, LOCAL_CRATE, LocalDefId, StableCrateId}; pub mod edit_distance; mod span_encoding; -pub use span_encoding::{Span, DUMMY_SP}; +pub use span_encoding::{DUMMY_SP, Span}; pub mod symbol; -pub use symbol::{sym, Symbol}; +pub use symbol::{Symbol, sym}; mod analyze_source_file; pub mod fatal_error; @@ -83,7 +83,7 @@ use std::{fmt, iter}; use md5::{Digest, Md5}; use rustc_data_structures::fx::FxHashMap; -use rustc_data_structures::stable_hasher::{Hash128, Hash64, HashStable, StableHasher}; +use rustc_data_structures::stable_hasher::{Hash64, Hash128, HashStable, StableHasher}; use rustc_data_structures::sync::{FreezeLock, FreezeWriteGuard, Lock, Lrc}; use sha1::Sha1; use sha2::Sha256; diff --git a/compiler/rustc_span/src/span_encoding.rs b/compiler/rustc_span/src/span_encoding.rs index 3047abfbb5cb0..db8170fa6ae5e 100644 --- a/compiler/rustc_span/src/span_encoding.rs +++ b/compiler/rustc_span/src/span_encoding.rs @@ -5,7 +5,7 @@ use rustc_serialize::int_overflow::DebugStrictAdd; use crate::def_id::{DefIndex, LocalDefId}; use crate::hygiene::SyntaxContext; -use crate::{BytePos, SpanData, SPAN_TRACK}; +use crate::{BytePos, SPAN_TRACK, SpanData}; /// A compressed span. /// diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index de4532bcb9950..8f226b26befda 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -11,9 +11,9 @@ use rustc_data_structures::stable_hasher::{ HashStable, StableCompare, StableHasher, ToStableHashKey, }; use rustc_data_structures::sync::Lock; -use rustc_macros::{symbols, Decodable, Encodable, HashStable_Generic}; +use rustc_macros::{Decodable, Encodable, HashStable_Generic, symbols}; -use crate::{with_session_globals, Edition, Span, DUMMY_SP}; +use crate::{DUMMY_SP, Edition, Span, with_session_globals}; #[cfg(test)] mod tests; @@ -2058,6 +2058,7 @@ symbols! { unmarked_api, unnamed_fields, unpin, + unqualified_local_imports, unreachable, unreachable_2015, unreachable_2015_macro, @@ -2523,10 +2524,10 @@ pub mod kw { /// For example `sym::rustfmt` or `sym::u8`. pub mod sym { // Used from a macro in `librustc_feature/accepted.rs` + use super::Symbol; pub use super::kw::MacroRules as macro_rules; #[doc(inline)] pub use super::sym_generated::*; - use super::Symbol; /// Get the symbol for an integer. /// diff --git a/compiler/rustc_symbol_mangling/src/test.rs b/compiler/rustc_symbol_mangling/src/test.rs index 774d0b5a6125b..8cfb65c1c5097 100644 --- a/compiler/rustc_symbol_mangling/src/test.rs +++ b/compiler/rustc_symbol_mangling/src/test.rs @@ -7,7 +7,7 @@ use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{GenericArgs, Instance, TyCtxt}; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; use crate::errors::{Kind, TestOutput}; diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 79de9bbb351f2..f3da7ff1ca7b0 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -607,45 +607,40 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { let _ = write!(self.out, "{bits:x}_"); } + // Handle `str` as partial support for unsized constants + ty::Str => { + let tcx = self.tcx(); + // HACK(jaic1): hide the `str` type behind a reference + // for the following transformation from valtree to raw bytes + let ref_ty = Ty::new_imm_ref(tcx, tcx.lifetimes.re_static, ct_ty); + let slice = valtree.try_to_raw_bytes(tcx, ref_ty).unwrap_or_else(|| { + bug!("expected to get raw bytes from valtree {:?} for type {:}", valtree, ct_ty) + }); + let s = std::str::from_utf8(slice).expect("non utf8 str from MIR interpreter"); + + // "e" for str as a basic type + self.push("e"); + + // FIXME(eddyb) use a specialized hex-encoding loop. + for byte in s.bytes() { + let _ = write!(self.out, "{byte:02x}"); + } + + self.push("_"); + } + // FIXME(valtrees): Remove the special case for `str` // here and fully support unsized constants. - ty::Ref(_, inner_ty, mutbl) => { + ty::Ref(_, _, mutbl) => { self.push(match mutbl { hir::Mutability::Not => "R", hir::Mutability::Mut => "Q", }); - match inner_ty.kind() { - ty::Str if mutbl.is_not() => { - let slice = - valtree.try_to_raw_bytes(self.tcx(), ct_ty).unwrap_or_else(|| { - bug!( - "expected to get raw bytes from valtree {:?} for type {:}", - valtree, - ct_ty - ) - }); - let s = - std::str::from_utf8(slice).expect("non utf8 str from MIR interpreter"); - - self.push("e"); - - // FIXME(eddyb) use a specialized hex-encoding loop. - for byte in s.bytes() { - let _ = write!(self.out, "{byte:02x}"); - } - - self.push("_"); - } - _ => { - let pointee_ty = ct_ty - .builtin_deref(true) - .expect("tried to dereference on non-ptr type"); - let dereferenced_const = - ty::Const::new_value(self.tcx, valtree, pointee_ty); - dereferenced_const.print(self)?; - } - } + let pointee_ty = + ct_ty.builtin_deref(true).expect("tried to dereference on non-ptr type"); + let dereferenced_const = ty::Const::new_value(self.tcx, valtree, pointee_ty); + dereferenced_const.print(self)?; } ty::Array(..) | ty::Tuple(..) | ty::Adt(..) | ty::Slice(_) => { diff --git a/compiler/rustc_target/src/abi/mod.rs b/compiler/rustc_target/src/abi/mod.rs index 9bd0aff1d3bc4..3eaff65261869 100644 --- a/compiler/rustc_target/src/abi/mod.rs +++ b/compiler/rustc_target/src/abi/mod.rs @@ -1,11 +1,11 @@ use std::fmt; use std::ops::Deref; -use rustc_data_structures::intern::Interned; -use rustc_macros::HashStable_Generic; pub use Float::*; pub use Integer::*; pub use Primitive::*; +use rustc_data_structures::intern::Interned; +use rustc_macros::HashStable_Generic; use crate::json::{Json, ToJson}; diff --git a/compiler/rustc_target/src/asm/arm.rs b/compiler/rustc_target/src/asm/arm.rs index f8d0d40e8a742..ff0cbddecf78b 100644 --- a/compiler/rustc_target/src/asm/arm.rs +++ b/compiler/rustc_target/src/asm/arm.rs @@ -1,7 +1,7 @@ use std::fmt; use rustc_data_structures::fx::FxIndexSet; -use rustc_span::{sym, Symbol}; +use rustc_span::{Symbol, sym}; use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; use crate::spec::{RelocModel, Target}; diff --git a/compiler/rustc_target/src/asm/riscv.rs b/compiler/rustc_target/src/asm/riscv.rs index 2b9d6114930fc..cfd573efbc1c9 100644 --- a/compiler/rustc_target/src/asm/riscv.rs +++ b/compiler/rustc_target/src/asm/riscv.rs @@ -1,7 +1,7 @@ use std::fmt; use rustc_data_structures::fx::FxIndexSet; -use rustc_span::{sym, Symbol}; +use rustc_span::{Symbol, sym}; use super::{InlineAsmArch, InlineAsmType, ModifierInfo}; use crate::spec::{RelocModel, Target}; diff --git a/compiler/rustc_target/src/json.rs b/compiler/rustc_target/src/json.rs index 5fcf5be101fef..2c367defe7ba3 100644 --- a/compiler/rustc_target/src/json.rs +++ b/compiler/rustc_target/src/json.rs @@ -2,7 +2,7 @@ use std::borrow::Cow; use std::collections::BTreeMap; pub use serde_json::Value as Json; -use serde_json::{json, Map, Number}; +use serde_json::{Map, Number, json}; use crate::spec::TargetMetadata; diff --git a/compiler/rustc_target/src/spec/base/aix.rs b/compiler/rustc_target/src/spec/base/aix.rs index e7e9ec663c4c8..1869369b9e3af 100644 --- a/compiler/rustc_target/src/spec/base/aix.rs +++ b/compiler/rustc_target/src/spec/base/aix.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{crt_objects, cvs, Cc, CodeModel, LinkOutputKind, LinkerFlavor, TargetOptions}; +use crate::spec::{Cc, CodeModel, LinkOutputKind, LinkerFlavor, TargetOptions, crt_objects, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/android.rs b/compiler/rustc_target/src/spec/base/android.rs index dfa0e3fe9899a..0426ea44c6a21 100644 --- a/compiler/rustc_target/src/spec/base/android.rs +++ b/compiler/rustc_target/src/spec/base/android.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, TargetOptions, TlsModel}; +use crate::spec::{SanitizerSet, TargetOptions, TlsModel, base}; pub(crate) fn opts() -> TargetOptions { let mut base = base::linux::opts(); diff --git a/compiler/rustc_target/src/spec/base/apple/mod.rs b/compiler/rustc_target/src/spec/base/apple/mod.rs index e78e322211526..fdecd330c2d85 100644 --- a/compiler/rustc_target/src/spec/base/apple/mod.rs +++ b/compiler/rustc_target/src/spec/base/apple/mod.rs @@ -3,8 +3,8 @@ use std::env; use std::num::ParseIntError; use crate::spec::{ - add_link_args, add_link_args_iter, cvs, Cc, DebuginfoKind, FramePointer, LinkArgs, - LinkerFlavor, Lld, SplitDebuginfo, StackProbeType, StaticCow, Target, TargetOptions, + Cc, DebuginfoKind, FramePointer, LinkArgs, LinkerFlavor, Lld, SplitDebuginfo, StackProbeType, + StaticCow, Target, TargetOptions, add_link_args, add_link_args_iter, cvs, }; #[cfg(test)] @@ -190,11 +190,10 @@ fn pre_link_args(os: &'static str, arch: Arch, abi: TargetAbi) -> LinkArgs { // // CC forwards the `-arch` to the linker, so we use the same value // here intentionally. - add_link_args( - &mut args, - LinkerFlavor::Darwin(Cc::Yes, Lld::No), - &["-arch", arch.ld_arch()], - ); + add_link_args(&mut args, LinkerFlavor::Darwin(Cc::Yes, Lld::No), &[ + "-arch", + arch.ld_arch(), + ]); // The presence of `-mmacosx-version-min` makes CC default to macOS, // and it sets the deployment target. let (major, minor, patch) = deployment_target(os, arch, abi); diff --git a/compiler/rustc_target/src/spec/base/apple/tests.rs b/compiler/rustc_target/src/spec/base/apple/tests.rs index d55b44e3c9e0e..9435b9a5bad59 100644 --- a/compiler/rustc_target/src/spec/base/apple/tests.rs +++ b/compiler/rustc_target/src/spec/base/apple/tests.rs @@ -33,14 +33,11 @@ fn macos_link_environment_unmodified() { for target in all_macos_targets { // macOS targets should only remove information for cross-compiling, but never // for the host. - assert_eq!( - target.link_env_remove, - crate::spec::cvs![ - "IPHONEOS_DEPLOYMENT_TARGET", - "TVOS_DEPLOYMENT_TARGET", - "XROS_DEPLOYMENT_TARGET" - ], - ); + assert_eq!(target.link_env_remove, crate::spec::cvs![ + "IPHONEOS_DEPLOYMENT_TARGET", + "TVOS_DEPLOYMENT_TARGET", + "XROS_DEPLOYMENT_TARGET" + ],); } } diff --git a/compiler/rustc_target/src/spec/base/avr_gnu.rs b/compiler/rustc_target/src/spec/base/avr_gnu.rs index dd9fc32b69e6c..fb97738618b28 100644 --- a/compiler/rustc_target/src/spec/base/avr_gnu.rs +++ b/compiler/rustc_target/src/spec/base/avr_gnu.rs @@ -26,10 +26,9 @@ pub(crate) fn target(target_cpu: &'static str, mmcu: &'static str) -> Target { linker: Some("avr-gcc".into()), eh_frame_header: false, pre_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[mmcu]), - late_link_args: TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-lgcc"], - ), + late_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-lgcc", + ]), max_atomic_width: Some(16), atomic_cas: false, relocation_model: RelocModel::Static, diff --git a/compiler/rustc_target/src/spec/base/dragonfly.rs b/compiler/rustc_target/src/spec/base/dragonfly.rs index 5da23f2b8fda1..36c9489fb705f 100644 --- a/compiler/rustc_target/src/spec/base/dragonfly.rs +++ b/compiler/rustc_target/src/spec/base/dragonfly.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, RelroLevel, TargetOptions}; +use crate::spec::{RelroLevel, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/freebsd.rs b/compiler/rustc_target/src/spec/base/freebsd.rs index a016489e52dcd..3602329330273 100644 --- a/compiler/rustc_target/src/spec/base/freebsd.rs +++ b/compiler/rustc_target/src/spec/base/freebsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, RelroLevel, TargetOptions}; +use crate::spec::{RelroLevel, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/fuchsia.rs b/compiler/rustc_target/src/spec/base/fuchsia.rs index fc3d9f6fb9ff6..910ee328368db 100644 --- a/compiler/rustc_target/src/spec/base/fuchsia.rs +++ b/compiler/rustc_target/src/spec/base/fuchsia.rs @@ -1,5 +1,5 @@ use crate::spec::{ - crt_objects, cvs, Cc, FramePointer, LinkOutputKind, LinkerFlavor, Lld, TargetOptions, + Cc, FramePointer, LinkOutputKind, LinkerFlavor, Lld, TargetOptions, crt_objects, cvs, }; pub(crate) fn opts() -> TargetOptions { @@ -8,22 +8,19 @@ pub(crate) fn opts() -> TargetOptions { // so we only list them for ld/lld. // // https://github.com/llvm/llvm-project/blob/db9322b2066c55254e7691efeab863f43bfcc084/clang/lib/Driver/ToolChains/Fuchsia.cpp#L31 - let pre_link_args = TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &[ - "--build-id", - "--hash-style=gnu", - "-z", - "max-page-size=4096", - "-z", - "now", - "-z", - "rodynamic", - "-z", - "separate-loadable-segments", - "--pack-dyn-relocs=relr", - ], - ); + let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "--build-id", + "--hash-style=gnu", + "-z", + "max-page-size=4096", + "-z", + "now", + "-z", + "rodynamic", + "-z", + "separate-loadable-segments", + "--pack-dyn-relocs=relr", + ]); TargetOptions { os: "fuchsia".into(), diff --git a/compiler/rustc_target/src/spec/base/haiku.rs b/compiler/rustc_target/src/spec/base/haiku.rs index d90e4c99f93e3..35e4cd2962ee0 100644 --- a/compiler/rustc_target/src/spec/base/haiku.rs +++ b/compiler/rustc_target/src/spec/base/haiku.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, RelroLevel, TargetOptions}; +use crate::spec::{RelroLevel, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/hurd.rs b/compiler/rustc_target/src/spec/base/hurd.rs index d464d50ecc28c..dcb346ddecca4 100644 --- a/compiler/rustc_target/src/spec/base/hurd.rs +++ b/compiler/rustc_target/src/spec/base/hurd.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, RelroLevel, TargetOptions}; +use crate::spec::{RelroLevel, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/hurd_gnu.rs b/compiler/rustc_target/src/spec/base/hurd_gnu.rs index 70d423217a60c..d33372b41b90f 100644 --- a/compiler/rustc_target/src/spec/base/hurd_gnu.rs +++ b/compiler/rustc_target/src/spec/base/hurd_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, TargetOptions}; +use crate::spec::{TargetOptions, base}; pub(crate) fn opts() -> TargetOptions { TargetOptions { env: "gnu".into(), ..base::hurd::opts() } diff --git a/compiler/rustc_target/src/spec/base/illumos.rs b/compiler/rustc_target/src/spec/base/illumos.rs index fa743a0c66d8d..bb7dfafc53eb3 100644 --- a/compiler/rustc_target/src/spec/base/illumos.rs +++ b/compiler/rustc_target/src/spec/base/illumos.rs @@ -1,28 +1,25 @@ -use crate::spec::{cvs, Cc, FramePointer, LinkerFlavor, TargetOptions}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { - let late_link_args = TargetOptions::link_args( - LinkerFlavor::Unix(Cc::Yes), - &[ - // The illumos libc contains a stack unwinding implementation, as - // does libgcc_s. The latter implementation includes several - // additional symbols that are not always in base libc. To force - // the consistent use of just one unwinder, we ensure libc appears - // after libgcc_s in the NEEDED list for the resultant binary by - // ignoring any attempts to add it as a dynamic dependency until the - // very end. - // FIXME: This should be replaced by a more complete and generic - // mechanism for controlling the order of library arguments passed - // to the linker. - "-lc", - // LLVM will insert calls to the stack protector functions - // "__stack_chk_fail" and "__stack_chk_guard" into code in native - // object files. Some platforms include these symbols directly in - // libc, but at least historically these have been provided in - // libssp.so on illumos and Solaris systems. - "-lssp", - ], - ); + let late_link_args = TargetOptions::link_args(LinkerFlavor::Unix(Cc::Yes), &[ + // The illumos libc contains a stack unwinding implementation, as + // does libgcc_s. The latter implementation includes several + // additional symbols that are not always in base libc. To force + // the consistent use of just one unwinder, we ensure libc appears + // after libgcc_s in the NEEDED list for the resultant binary by + // ignoring any attempts to add it as a dynamic dependency until the + // very end. + // FIXME: This should be replaced by a more complete and generic + // mechanism for controlling the order of library arguments passed + // to the linker. + "-lc", + // LLVM will insert calls to the stack protector functions + // "__stack_chk_fail" and "__stack_chk_guard" into code in native + // object files. Some platforms include these symbols directly in + // libc, but at least historically these have been provided in + // libssp.so on illumos and Solaris systems. + "-lssp", + ]); TargetOptions { os: "illumos".into(), diff --git a/compiler/rustc_target/src/spec/base/l4re.rs b/compiler/rustc_target/src/spec/base/l4re.rs index dbe9e78a193b9..072a6a1001bdc 100644 --- a/compiler/rustc_target/src/spec/base/l4re.rs +++ b/compiler/rustc_target/src/spec/base/l4re.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, PanicStrategy, RelocModel, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, PanicStrategy, RelocModel, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/linux.rs b/compiler/rustc_target/src/spec/base/linux.rs index 2e30364525e6b..9982c254eca52 100644 --- a/compiler/rustc_target/src/spec/base/linux.rs +++ b/compiler/rustc_target/src/spec/base/linux.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use crate::spec::{cvs, RelroLevel, SplitDebuginfo, TargetOptions}; +use crate::spec::{RelroLevel, SplitDebuginfo, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/linux_gnu.rs b/compiler/rustc_target/src/spec/base/linux_gnu.rs index 1200add4fe1e2..e9135b43ebc1f 100644 --- a/compiler/rustc_target/src/spec/base/linux_gnu.rs +++ b/compiler/rustc_target/src/spec/base/linux_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, TargetOptions}; +use crate::spec::{TargetOptions, base}; pub(crate) fn opts() -> TargetOptions { TargetOptions { env: "gnu".into(), ..base::linux::opts() } diff --git a/compiler/rustc_target/src/spec/base/linux_musl.rs b/compiler/rustc_target/src/spec/base/linux_musl.rs index a29635112fffa..e020bb8523804 100644 --- a/compiler/rustc_target/src/spec/base/linux_musl.rs +++ b/compiler/rustc_target/src/spec/base/linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, crt_objects, LinkSelfContainedDefault, TargetOptions}; +use crate::spec::{LinkSelfContainedDefault, TargetOptions, base, crt_objects}; pub(crate) fn opts() -> TargetOptions { let mut base = base::linux::opts(); diff --git a/compiler/rustc_target/src/spec/base/linux_ohos.rs b/compiler/rustc_target/src/spec/base/linux_ohos.rs index 2372bc2c71814..6f4d69a996c34 100644 --- a/compiler/rustc_target/src/spec/base/linux_ohos.rs +++ b/compiler/rustc_target/src/spec/base/linux_ohos.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, TargetOptions, TlsModel}; +use crate::spec::{TargetOptions, TlsModel, base}; pub(crate) fn opts() -> TargetOptions { let mut base = base::linux::opts(); diff --git a/compiler/rustc_target/src/spec/base/linux_uclibc.rs b/compiler/rustc_target/src/spec/base/linux_uclibc.rs index 80a6479bb5f9a..40801b76dca79 100644 --- a/compiler/rustc_target/src/spec/base/linux_uclibc.rs +++ b/compiler/rustc_target/src/spec/base/linux_uclibc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, TargetOptions}; +use crate::spec::{TargetOptions, base}; pub(crate) fn opts() -> TargetOptions { TargetOptions { env: "uclibc".into(), ..base::linux::opts() } diff --git a/compiler/rustc_target/src/spec/base/netbsd.rs b/compiler/rustc_target/src/spec/base/netbsd.rs index 1ae81eb0633ef..b92d8933a27a1 100644 --- a/compiler/rustc_target/src/spec/base/netbsd.rs +++ b/compiler/rustc_target/src/spec/base/netbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, RelroLevel, TargetOptions}; +use crate::spec::{RelroLevel, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/nto_qnx.rs b/compiler/rustc_target/src/spec/base/nto_qnx.rs index 47177415b3942..65475d068d7e9 100644 --- a/compiler/rustc_target/src/spec/base/nto_qnx.rs +++ b/compiler/rustc_target/src/spec/base/nto_qnx.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, RelroLevel, TargetOptions}; +use crate::spec::{RelroLevel, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/openbsd.rs b/compiler/rustc_target/src/spec/base/openbsd.rs index 942ac4a393c5c..481fbdf0b08ed 100644 --- a/compiler/rustc_target/src/spec/base/openbsd.rs +++ b/compiler/rustc_target/src/spec/base/openbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, FramePointer, RelroLevel, TargetOptions, TlsModel}; +use crate::spec::{FramePointer, RelroLevel, TargetOptions, TlsModel, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/redox.rs b/compiler/rustc_target/src/spec/base/redox.rs index 3f13f1f884195..e0a0c20c56d63 100644 --- a/compiler/rustc_target/src/spec/base/redox.rs +++ b/compiler/rustc_target/src/spec/base/redox.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, RelroLevel, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, RelroLevel, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/solaris.rs b/compiler/rustc_target/src/spec/base/solaris.rs index 1529cd65b28c4..22288b86e2ecd 100644 --- a/compiler/rustc_target/src/spec/base/solaris.rs +++ b/compiler/rustc_target/src/spec/base/solaris.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/teeos.rs b/compiler/rustc_target/src/spec/base/teeos.rs index 94eb946dda46b..ecd9752c213ef 100644 --- a/compiler/rustc_target/src/spec/base/teeos.rs +++ b/compiler/rustc_target/src/spec/base/teeos.rs @@ -1,4 +1,4 @@ -use crate::spec::{add_link_args, Cc, LinkerFlavor, Lld, PanicStrategy, RelroLevel, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelroLevel, TargetOptions, add_link_args}; pub(crate) fn opts() -> TargetOptions { let lld_args = &["-zmax-page-size=4096", "-znow", "-ztext", "--execute-only"]; diff --git a/compiler/rustc_target/src/spec/base/uefi_msvc.rs b/compiler/rustc_target/src/spec/base/uefi_msvc.rs index 0020106f40e87..b0232ecbe61e7 100644 --- a/compiler/rustc_target/src/spec/base/uefi_msvc.rs +++ b/compiler/rustc_target/src/spec/base/uefi_msvc.rs @@ -9,30 +9,27 @@ // the timer-interrupt. Device-drivers are required to use polling-based models. Furthermore, all // code runs in the same environment, no process separation is supported. -use crate::spec::{base, LinkerFlavor, Lld, PanicStrategy, StackProbeType, TargetOptions}; +use crate::spec::{LinkerFlavor, Lld, PanicStrategy, StackProbeType, TargetOptions, base}; pub(crate) fn opts() -> TargetOptions { let mut base = base::msvc::opts(); - base.add_pre_link_args( - LinkerFlavor::Msvc(Lld::No), - &[ - // Non-standard subsystems have no default entry-point in PE+ files. We have to define - // one. "efi_main" seems to be a common choice amongst other implementations and the - // spec. - "/entry:efi_main", - // COFF images have a "Subsystem" field in their header, which defines what kind of - // program it is. UEFI has 3 fields reserved, which are EFI_APPLICATION, - // EFI_BOOT_SERVICE_DRIVER, and EFI_RUNTIME_DRIVER. We default to EFI_APPLICATION, - // which is very likely the most common option. Individual projects can override this - // with custom linker flags. - // The subsystem-type only has minor effects on the application. It defines the memory - // regions the application is loaded into (runtime-drivers need to be put into - // reserved areas), as well as whether a return from the entry-point is treated as - // exit (default for applications). - "/subsystem:efi_application", - ], - ); + base.add_pre_link_args(LinkerFlavor::Msvc(Lld::No), &[ + // Non-standard subsystems have no default entry-point in PE+ files. We have to define + // one. "efi_main" seems to be a common choice amongst other implementations and the + // spec. + "/entry:efi_main", + // COFF images have a "Subsystem" field in their header, which defines what kind of + // program it is. UEFI has 3 fields reserved, which are EFI_APPLICATION, + // EFI_BOOT_SERVICE_DRIVER, and EFI_RUNTIME_DRIVER. We default to EFI_APPLICATION, + // which is very likely the most common option. Individual projects can override this + // with custom linker flags. + // The subsystem-type only has minor effects on the application. It defines the memory + // regions the application is loaded into (runtime-drivers need to be put into + // reserved areas), as well as whether a return from the entry-point is treated as + // exit (default for applications). + "/subsystem:efi_application", + ]); TargetOptions { os: "uefi".into(), diff --git a/compiler/rustc_target/src/spec/base/unikraft_linux_musl.rs b/compiler/rustc_target/src/spec/base/unikraft_linux_musl.rs index fd81381572438..319a6182303bf 100644 --- a/compiler/rustc_target/src/spec/base/unikraft_linux_musl.rs +++ b/compiler/rustc_target/src/spec/base/unikraft_linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, PanicStrategy, RelocModel, TargetOptions}; +use crate::spec::{PanicStrategy, RelocModel, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/vxworks.rs b/compiler/rustc_target/src/spec/base/vxworks.rs index 425dd3c8cc232..bb0d00f4a4c0f 100644 --- a/compiler/rustc_target/src/spec/base/vxworks.rs +++ b/compiler/rustc_target/src/spec/base/vxworks.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, TargetOptions}; +use crate::spec::{TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/wasm.rs b/compiler/rustc_target/src/spec/base/wasm.rs index e417137ced1b1..81b96cd39ffac 100644 --- a/compiler/rustc_target/src/spec/base/wasm.rs +++ b/compiler/rustc_target/src/spec/base/wasm.rs @@ -1,6 +1,6 @@ use crate::spec::{ - add_link_args, cvs, Cc, LinkSelfContainedDefault, LinkerFlavor, PanicStrategy, RelocModel, - TargetOptions, TlsModel, + Cc, LinkSelfContainedDefault, LinkerFlavor, PanicStrategy, RelocModel, TargetOptions, TlsModel, + add_link_args, cvs, }; pub(crate) fn options() -> TargetOptions { diff --git a/compiler/rustc_target/src/spec/base/windows_gnu.rs b/compiler/rustc_target/src/spec/base/windows_gnu.rs index 1393b1591842f..e975102e2389a 100644 --- a/compiler/rustc_target/src/spec/base/windows_gnu.rs +++ b/compiler/rustc_target/src/spec/base/windows_gnu.rs @@ -1,31 +1,24 @@ use std::borrow::Cow; use crate::spec::{ - add_link_args, crt_objects, cvs, Cc, DebuginfoKind, LinkSelfContainedDefault, LinkerFlavor, - Lld, SplitDebuginfo, TargetOptions, + Cc, DebuginfoKind, LinkSelfContainedDefault, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions, + add_link_args, crt_objects, cvs, }; pub(crate) fn opts() -> TargetOptions { - let mut pre_link_args = TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &[ - // Enable ASLR - "--dynamicbase", - // ASLR will rebase it anyway so leaving that option enabled only leads to confusion - "--disable-auto-image-base", - ], - ); - add_link_args( - &mut pre_link_args, - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &[ - // Tell GCC to avoid linker plugins, because we are not bundling - // them with Windows installer, and Rust does its own LTO anyways. - "-fno-use-linker-plugin", - "-Wl,--dynamicbase", - "-Wl,--disable-auto-image-base", - ], - ); + let mut pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + // Enable ASLR + "--dynamicbase", + // ASLR will rebase it anyway so leaving that option enabled only leads to confusion + "--disable-auto-image-base", + ]); + add_link_args(&mut pre_link_args, LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + // Tell GCC to avoid linker plugins, because we are not bundling + // them with Windows installer, and Rust does its own LTO anyways. + "-fno-use-linker-plugin", + "-Wl,--dynamicbase", + "-Wl,--disable-auto-image-base", + ]); // Order of `late_link_args*` was found through trial and error to work with various // mingw-w64 versions (not tested on the CI). It's expected to change from time to time. diff --git a/compiler/rustc_target/src/spec/base/windows_gnullvm.rs b/compiler/rustc_target/src/spec/base/windows_gnullvm.rs index 9e89a3c75fead..d5acd37092a0a 100644 --- a/compiler/rustc_target/src/spec/base/windows_gnullvm.rs +++ b/compiler/rustc_target/src/spec/base/windows_gnullvm.rs @@ -1,21 +1,24 @@ use std::borrow::Cow; -use crate::spec::{cvs, Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions}; +use crate::spec::{Cc, DebuginfoKind, LinkerFlavor, Lld, SplitDebuginfo, TargetOptions, cvs}; pub(crate) fn opts() -> TargetOptions { // We cannot use `-nodefaultlibs` because compiler-rt has to be passed // as a path since it's not added to linker search path by the default. // There were attempts to make it behave like libgcc (so one can just use -l) // but LLVM maintainers rejected it: https://reviews.llvm.org/D51440 - let pre_link_args = TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-nolibc", "--unwindlib=none"], - ); + let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-nolibc", + "--unwindlib=none", + ]); // Order of `late_link_args*` does not matter with LLD. - let late_link_args = TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-lmingw32", "-lmingwex", "-lmsvcrt", "-lkernel32", "-luser32"], - ); + let late_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-lmingw32", + "-lmingwex", + "-lmsvcrt", + "-lkernel32", + "-luser32", + ]); TargetOptions { os: "windows".into(), diff --git a/compiler/rustc_target/src/spec/base/windows_msvc.rs b/compiler/rustc_target/src/spec/base/windows_msvc.rs index e68043ca2ee69..066785a1ae41f 100644 --- a/compiler/rustc_target/src/spec/base/windows_msvc.rs +++ b/compiler/rustc_target/src/spec/base/windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, cvs, TargetOptions}; +use crate::spec::{TargetOptions, base, cvs}; pub(crate) fn opts() -> TargetOptions { let base = base::msvc::opts(); diff --git a/compiler/rustc_target/src/spec/base/windows_uwp_gnu.rs b/compiler/rustc_target/src/spec/base/windows_uwp_gnu.rs index 8134b5feade9f..09eb52491f745 100644 --- a/compiler/rustc_target/src/spec/base/windows_uwp_gnu.rs +++ b/compiler/rustc_target/src/spec/base/windows_uwp_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{add_link_args, base, Cc, LinkArgs, LinkerFlavor, Lld, TargetOptions}; +use crate::spec::{Cc, LinkArgs, LinkerFlavor, Lld, TargetOptions, add_link_args, base}; pub(crate) fn opts() -> TargetOptions { let base = base::windows_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/base/windows_uwp_msvc.rs b/compiler/rustc_target/src/spec/base/windows_uwp_msvc.rs index f4f712145047e..374918d38a791 100644 --- a/compiler/rustc_target/src/spec/base/windows_uwp_msvc.rs +++ b/compiler/rustc_target/src/spec/base/windows_uwp_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, LinkerFlavor, Lld, TargetOptions}; +use crate::spec::{LinkerFlavor, Lld, TargetOptions, base}; pub(crate) fn opts() -> TargetOptions { let mut opts = base::windows_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/mod.rs b/compiler/rustc_target/src/spec/mod.rs index ec4f5ef79d1f6..3f0b23a595c03 100644 --- a/compiler/rustc_target/src/spec/mod.rs +++ b/compiler/rustc_target/src/spec/mod.rs @@ -45,7 +45,7 @@ use std::{fmt, io}; use rustc_fs_util::try_canonicalize; use rustc_macros::{Decodable, Encodable, HashStable_Generic}; use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; -use rustc_span::symbol::{kw, sym, Symbol}; +use rustc_span::symbol::{Symbol, kw, sym}; use serde_json::Value; use tracing::debug; @@ -1690,12 +1690,8 @@ supported_targets! { ("x86_64h-apple-darwin", x86_64h_apple_darwin), ("i686-apple-darwin", i686_apple_darwin), - // FIXME(#106649): Remove aarch64-fuchsia in favor of aarch64-unknown-fuchsia - ("aarch64-fuchsia", aarch64_fuchsia), ("aarch64-unknown-fuchsia", aarch64_unknown_fuchsia), ("riscv64gc-unknown-fuchsia", riscv64gc_unknown_fuchsia), - // FIXME(#106649): Remove x86_64-fuchsia in favor of x86_64-unknown-fuchsia - ("x86_64-fuchsia", x86_64_fuchsia), ("x86_64-unknown-fuchsia", x86_64_unknown_fuchsia), ("avr-unknown-gnu-atmega328", avr_unknown_gnu_atmega328), @@ -1886,6 +1882,7 @@ supported_targets! { ("aarch64-unknown-linux-ohos", aarch64_unknown_linux_ohos), ("armv7-unknown-linux-ohos", armv7_unknown_linux_ohos), + ("loongarch64-unknown-linux-ohos", loongarch64_unknown_linux_ohos), ("x86_64-unknown-linux-ohos", x86_64_unknown_linux_ohos), ("x86_64-unknown-linux-none", x86_64_unknown_linux_none), @@ -3389,10 +3386,10 @@ impl Target { // Each field should have been read using `Json::remove` so any keys remaining are unused. let remaining_keys = obj.keys(); - Ok(( - base, - TargetWarnings { unused_fields: remaining_keys.cloned().collect(), incorrect_type }, - )) + Ok((base, TargetWarnings { + unused_fields: remaining_keys.cloned().collect(), + incorrect_type, + })) } /// Load a built-in target diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_darwin.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_darwin.rs index 1061633be175f..e6ce50a005f7d 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_darwin.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_darwin.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("ARM64 macOS (11.0+, Big Sur+)".into()), + description: Some("ARM64 Apple macOS (11.0+, Big Sur+)".into()), tier: Some(1), host_tools: Some(true), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_ios.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_ios.rs index caeb9a121e48b..78441ede3337e 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_ios.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_ios.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("ARM64 iOS".into()), + description: Some("ARM64 Apple iOS".into()), tier: Some(2), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_ios_macabi.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_ios_macabi.rs index eee9eca3bcbeb..857abd21faf68 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_ios_macabi.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_ios_macabi.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("Apple Catalyst on ARM64".into()), + description: Some("ARM64 Apple Mac Catalyst".into()), tier: Some(2), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_ios_sim.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_ios_sim.rs index ee58038301d4a..cbc8b7cd95e45 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_ios_sim.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_ios_sim.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("Apple iOS Simulator on ARM64".into()), + description: Some("ARM64 Apple iOS Simulator".into()), tier: Some(2), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_tvos.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_tvos.rs index baca863d442ba..f5176d35f809f 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_tvos.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_tvos.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("ARM64 tvOS".into()), + description: Some("ARM64 Apple tvOS".into()), tier: Some(3), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_tvos_sim.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_tvos_sim.rs index 1a48f8c5acffb..d673851414560 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_tvos_sim.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_tvos_sim.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("ARM64 tvOS Simulator".into()), + description: Some("ARM64 Apple tvOS Simulator".into()), tier: Some(3), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_visionos.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_visionos.rs index 1424126134d64..dc5dac4fd8f2e 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_visionos.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_visionos.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_visionos_sim.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_visionos_sim.rs index d7226e02ecb56..e9fe786f65ec5 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_visionos_sim.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_visionos_sim.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_watchos.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_watchos.rs index 1940a568b3960..4f5ce2f12e73c 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_watchos.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_watchos.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("ARM64 Apple WatchOS".into()), + description: Some("ARM64 Apple watchOS".into()), tier: Some(3), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/aarch64_apple_watchos_sim.rs b/compiler/rustc_target/src/spec/targets/aarch64_apple_watchos_sim.rs index 6beef11c5041f..952c98c324fa7 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_apple_watchos_sim.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_apple_watchos_sim.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("ARM64 Apple WatchOS Simulator".into()), + description: Some("ARM64 Apple watchOS Simulator".into()), tier: Some(3), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_linux_gnu.rs index 5b8efd6626287..f1854353abd6f 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_linux_gnu.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_linux_gnu_ilp32.rs b/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_linux_gnu_ilp32.rs index c14fa20b6973d..0dc51aaa73d99 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_linux_gnu_ilp32.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_linux_gnu_ilp32.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_netbsd.rs index fe4dadfe8382d..f99e7fe84f581 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_be_unknown_netbsd.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_fuchsia.rs b/compiler/rustc_target/src/spec/targets/aarch64_fuchsia.rs deleted file mode 100644 index 144ac85622eef..0000000000000 --- a/compiler/rustc_target/src/spec/targets/aarch64_fuchsia.rs +++ /dev/null @@ -1 +0,0 @@ -pub(crate) use crate::spec::targets::aarch64_unknown_fuchsia::target; diff --git a/compiler/rustc_target/src/spec/targets/aarch64_kmc_solid_asp3.rs b/compiler/rustc_target/src/spec/targets/aarch64_kmc_solid_asp3.rs index 1d054dad568a8..97ce53b2d8fde 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_kmc_solid_asp3.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_kmc_solid_asp3.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, RelocModel, StackProbeType, Target, TargetOptions}; +use crate::spec::{RelocModel, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let base = base::solid::opts("asp3"); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_linux_android.rs b/compiler/rustc_target/src/spec/targets/aarch64_linux_android.rs index ff0a0762e3c80..a8ef5544a243e 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_linux_android.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_linux_android.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, StackProbeType, Target, TargetOptions}; +use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base}; // See https://developer.android.com/ndk/guides/abis.html#arm64-v8a // for target ABI requirements. diff --git a/compiler/rustc_target/src/spec/targets/aarch64_pc_windows_gnullvm.rs b/compiler/rustc_target/src/spec/targets/aarch64_pc_windows_gnullvm.rs index 9d10358a49f80..7a56809dcfc70 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_pc_windows_gnullvm.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_pc_windows_gnullvm.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_gnullvm::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_pc_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/aarch64_pc_windows_msvc.rs index c3bd2ea6c332b..e1133a4ce051c 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_pc_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_pc_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_freebsd.rs index b993275ff8314..2ca2f403e1773 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, StackProbeType, Target, TargetOptions}; +use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_fuchsia.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_fuchsia.rs index b462739e5617b..26a736a271266 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_fuchsia.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_fuchsia.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, StackProbeType, Target, TargetOptions}; +use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_hermit.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_hermit.rs index e9da6a8f3ceb8..3989cc13fba50 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_hermit.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_hermit.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_illumos.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_illumos.rs index bed9c88fd670b..b76f10b8efdfa 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_illumos.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_illumos.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, SanitizerSet, Target}; +use crate::spec::{Cc, LinkerFlavor, SanitizerSet, Target, base}; pub(crate) fn target() -> Target { let mut base = base::illumos::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_gnu.rs index 56709f788d3eb..96c25af0a7fc0 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, StackProbeType, Target, TargetOptions}; +use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_gnu_ilp32.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_gnu_ilp32.rs index 71b331972cc0d..f33a5873c0941 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_gnu_ilp32.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_gnu_ilp32.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_musl.rs index 1cf71b650409c..197ff2d74e5e5 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, StackProbeType, Target, TargetOptions}; +use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_ohos.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_ohos.rs index 0dbf4cb7a705c..0942f5d896bbc 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_ohos.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_linux_ohos.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, StackProbeType, Target, TargetOptions}; +use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_ohos::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_netbsd.rs index e25beec0a1376..d1769d1476ccf 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_netbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_none.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_none.rs index 54a08853c2860..d124f8a3d2974 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_none.rs @@ -16,10 +16,9 @@ pub(crate) fn target() -> Target { linker_flavor: LinkerFlavor::Gnu(Cc::No, Lld::Yes), linker: Some("rust-lld".into()), // Enable the Cortex-A53 errata 843419 mitigation by default - pre_link_args: TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &["--fix-cortex-a53-843419"], - ), + pre_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "--fix-cortex-a53-843419", + ]), features: "+v8a,+strict-align,+neon,+fp-armv8".into(), supported_sanitizers: SanitizerSet::KCFI | SanitizerSet::KERNELADDRESS, relocation_model: RelocModel::Static, diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_nto_qnx700.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_nto_qnx700.rs index 47a9b91663f84..6c061112b1667 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_nto_qnx700.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_nto_qnx700.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, TargetOptions, base}; pub(crate) fn target() -> Target { // In QNX, libc does not provide a compatible ABI between versions. @@ -27,10 +27,9 @@ pub(crate) fn target() -> Target { options: TargetOptions { features: "+v8a".into(), max_atomic_width: Some(128), - pre_link_args: TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-Vgcc_ntoaarch64le_cxx"], - ), + pre_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-Vgcc_ntoaarch64le_cxx", + ]), env: "nto70".into(), ..base::nto_qnx::opts() }, diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_openbsd.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_openbsd.rs index 8f6215df71a41..31c8daa98b069 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_openbsd.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_openbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_redox.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_redox.rs index 26c1a67109558..6bd8c306abb46 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_redox.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_redox.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, StackProbeType, Target}; +use crate::spec::{StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::redox::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_teeos.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_teeos.rs index 4e3d5ce34bc50..4bffef4758d1b 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_teeos.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_teeos.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, StackProbeType, Target}; +use crate::spec::{StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::teeos::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_unknown_uefi.rs b/compiler/rustc_target/src/spec/targets/aarch64_unknown_uefi.rs index bb580af7c4756..bde1ce95b3f98 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_unknown_uefi.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_unknown_uefi.rs @@ -1,7 +1,7 @@ // This defines the aarch64 target for UEFI systems as described in the UEFI specification. See the // uefi-base module for generic UEFI options. -use crate::spec::{base, LinkerFlavor, Lld, Target}; +use crate::spec::{LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::uefi_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_uwp_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/aarch64_uwp_windows_msvc.rs index 630658efd0675..c916aa6b23cfe 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_uwp_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_uwp_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_uwp_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/aarch64_wrs_vxworks.rs b/compiler/rustc_target/src/spec/targets/aarch64_wrs_vxworks.rs index 3c0f92fa31fef..b74c49f0a0901 100644 --- a/compiler/rustc_target/src/spec/targets/aarch64_wrs_vxworks.rs +++ b/compiler/rustc_target/src/spec/targets/aarch64_wrs_vxworks.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/arm64_32_apple_watchos.rs b/compiler/rustc_target/src/spec/targets/arm64_32_apple_watchos.rs index e9f4d9330d5f2..4f7a1857e76ab 100644 --- a/compiler/rustc_target/src/spec/targets/arm64_32_apple_watchos.rs +++ b/compiler/rustc_target/src/spec/targets/arm64_32_apple_watchos.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("Arm Apple WatchOS 64-bit with 32-bit pointers".into()), + description: Some("ARM64 Apple watchOS with 32-bit pointers".into()), tier: Some(3), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/arm64e_apple_darwin.rs b/compiler/rustc_target/src/spec/targets/arm64e_apple_darwin.rs index 4f7c945b9fe47..04906fb046097 100644 --- a/compiler/rustc_target/src/spec/targets/arm64e_apple_darwin.rs +++ b/compiler/rustc_target/src/spec/targets/arm64e_apple_darwin.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/arm64e_apple_ios.rs b/compiler/rustc_target/src/spec/targets/arm64e_apple_ios.rs index 8f192fe288603..3264669c169f0 100644 --- a/compiler/rustc_target/src/spec/targets/arm64e_apple_ios.rs +++ b/compiler/rustc_target/src/spec/targets/arm64e_apple_ios.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/arm64e_apple_tvos.rs b/compiler/rustc_target/src/spec/targets/arm64e_apple_tvos.rs index d4d66c92857a3..4c231cb519c0e 100644 --- a/compiler/rustc_target/src/spec/targets/arm64e_apple_tvos.rs +++ b/compiler/rustc_target/src/spec/targets/arm64e_apple_tvos.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, Target, TargetOptions}; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/arm64ec_pc_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/arm64ec_pc_windows_msvc.rs index 50c399bf4a88b..a6744b95a3eb7 100644 --- a/compiler/rustc_target/src/spec/targets/arm64ec_pc_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/arm64ec_pc_windows_msvc.rs @@ -1,14 +1,13 @@ -use crate::spec::{add_link_args, base, LinkerFlavor, Lld, Target}; +use crate::spec::{LinkerFlavor, Lld, Target, add_link_args, base}; pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); base.max_atomic_width = Some(128); base.features = "+v8a,+neon,+fp-armv8".into(); - add_link_args( - &mut base.late_link_args, - LinkerFlavor::Msvc(Lld::No), - &["/machine:arm64ec", "softintrin.lib"], - ); + add_link_args(&mut base.late_link_args, LinkerFlavor::Msvc(Lld::No), &[ + "/machine:arm64ec", + "softintrin.lib", + ]); Target { llvm_target: "arm64ec-pc-windows-msvc".into(), diff --git a/compiler/rustc_target/src/spec/targets/arm_linux_androideabi.rs b/compiler/rustc_target/src/spec/targets/arm_linux_androideabi.rs index 350a01b196714..677d0f905b773 100644 --- a/compiler/rustc_target/src/spec/targets/arm_linux_androideabi.rs +++ b/compiler/rustc_target/src/spec/targets/arm_linux_androideabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, Target, TargetOptions}; +use crate::spec::{SanitizerSet, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/arm_unknown_linux_gnueabi.rs b/compiler/rustc_target/src/spec/targets/arm_unknown_linux_gnueabi.rs index 296f9d0b423d7..5948d6b01f098 100644 --- a/compiler/rustc_target/src/spec/targets/arm_unknown_linux_gnueabi.rs +++ b/compiler/rustc_target/src/spec/targets/arm_unknown_linux_gnueabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/arm_unknown_linux_gnueabihf.rs b/compiler/rustc_target/src/spec/targets/arm_unknown_linux_gnueabihf.rs index 5d58055f1af35..1e07a3cf2fda1 100644 --- a/compiler/rustc_target/src/spec/targets/arm_unknown_linux_gnueabihf.rs +++ b/compiler/rustc_target/src/spec/targets/arm_unknown_linux_gnueabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/arm_unknown_linux_musleabi.rs b/compiler/rustc_target/src/spec/targets/arm_unknown_linux_musleabi.rs index 89a80ae8bedd6..b96d8455a5b19 100644 --- a/compiler/rustc_target/src/spec/targets/arm_unknown_linux_musleabi.rs +++ b/compiler/rustc_target/src/spec/targets/arm_unknown_linux_musleabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/arm_unknown_linux_musleabihf.rs b/compiler/rustc_target/src/spec/targets/arm_unknown_linux_musleabihf.rs index 200bb91796484..3418a7090d3a5 100644 --- a/compiler/rustc_target/src/spec/targets/arm_unknown_linux_musleabihf.rs +++ b/compiler/rustc_target/src/spec/targets/arm_unknown_linux_musleabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armeb_unknown_linux_gnueabi.rs b/compiler/rustc_target/src/spec/targets/armeb_unknown_linux_gnueabi.rs index a6ea48817c04f..07382a30863bb 100644 --- a/compiler/rustc_target/src/spec/targets/armeb_unknown_linux_gnueabi.rs +++ b/compiler/rustc_target/src/spec/targets/armeb_unknown_linux_gnueabi.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv4t_none_eabi.rs b/compiler/rustc_target/src/spec/targets/armv4t_none_eabi.rs index 2236e02d006fa..3d525ba403c7d 100644 --- a/compiler/rustc_target/src/spec/targets/armv4t_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv4t_none_eabi.rs @@ -9,7 +9,7 @@ //! The default link script is very likely wrong, so you should use //! `-Clink-arg=-Tmy_script.ld` to override that with a correct linker script. -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv4t_unknown_linux_gnueabi.rs b/compiler/rustc_target/src/spec/targets/armv4t_unknown_linux_gnueabi.rs index d88022ac10a2a..3a2fb753ba147 100644 --- a/compiler/rustc_target/src/spec/targets/armv4t_unknown_linux_gnueabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv4t_unknown_linux_gnueabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv5te_none_eabi.rs b/compiler/rustc_target/src/spec/targets/armv5te_none_eabi.rs index 3d8e75d3ee952..7f0a7791ca660 100644 --- a/compiler/rustc_target/src/spec/targets/armv5te_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv5te_none_eabi.rs @@ -1,6 +1,6 @@ //! Targets the ARMv5TE, with code as `a32` code by default. -use crate::spec::{base, cvs, FramePointer, Target, TargetOptions}; +use crate::spec::{FramePointer, Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_gnueabi.rs b/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_gnueabi.rs index a73d8298ddeed..9e8c81f133388 100644 --- a/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_gnueabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_gnueabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_musleabi.rs b/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_musleabi.rs index 91b0e2039c7f4..1bcd090b9f2a5 100644 --- a/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_musleabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_musleabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_uclibceabi.rs b/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_uclibceabi.rs index 65658ab45fc49..e0bc1936e221c 100644 --- a/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_uclibceabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv5te_unknown_linux_uclibceabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv6_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/armv6_unknown_freebsd.rs index 52617237f207a..ee69f9894aea5 100644 --- a/compiler/rustc_target/src/spec/targets/armv6_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/armv6_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv6_unknown_netbsd_eabihf.rs b/compiler/rustc_target/src/spec/targets/armv6_unknown_netbsd_eabihf.rs index eda1c028aad3a..6ed50df531498 100644 --- a/compiler/rustc_target/src/spec/targets/armv6_unknown_netbsd_eabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv6_unknown_netbsd_eabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv6k_nintendo_3ds.rs b/compiler/rustc_target/src/spec/targets/armv6k_nintendo_3ds.rs index b29ee2dd793b1..d78f62238b4a3 100644 --- a/compiler/rustc_target/src/spec/targets/armv6k_nintendo_3ds.rs +++ b/compiler/rustc_target/src/spec/targets/armv6k_nintendo_3ds.rs @@ -1,14 +1,16 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, RelocModel, Target, TargetOptions, cvs}; /// A base target for Nintendo 3DS devices using the devkitARM toolchain. /// /// Requires the devkitARM toolchain for 3DS targets on the host system. pub(crate) fn target() -> Target { - let pre_link_args = TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-specs=3dsx.specs", "-mtune=mpcore", "-mfloat-abi=hard", "-mtp=soft"], - ); + let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-specs=3dsx.specs", + "-mtune=mpcore", + "-mfloat-abi=hard", + "-mtp=soft", + ]); Target { llvm_target: "armv6k-none-eabihf".into(), diff --git a/compiler/rustc_target/src/spec/targets/armv7_linux_androideabi.rs b/compiler/rustc_target/src/spec/targets/armv7_linux_androideabi.rs index 3bba22f8a1fa7..52a5402775012 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_linux_androideabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_linux_androideabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, SanitizerSet, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, SanitizerSet, Target, TargetOptions, base}; // This target if is for the baseline of the Android v7a ABI // in thumb mode. It's named armv7-* instead of thumbv7-* diff --git a/compiler/rustc_target/src/spec/targets/armv7_rtems_eabihf.rs b/compiler/rustc_target/src/spec/targets/armv7_rtems_eabihf.rs index 1edecac095f6f..4238c4c1c15f1 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_rtems_eabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_rtems_eabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv7_sony_vita_newlibeabihf.rs b/compiler/rustc_target/src/spec/targets/armv7_sony_vita_newlibeabihf.rs index 5f71d325efb0a..18843124d8e15 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_sony_vita_newlibeabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_sony_vita_newlibeabihf.rs @@ -1,15 +1,15 @@ use crate::abi::Endian; -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, RelocModel, Target, TargetOptions, cvs}; /// A base target for PlayStation Vita devices using the VITASDK toolchain (using newlib). /// /// Requires the VITASDK toolchain on the host system. pub(crate) fn target() -> Target { - let pre_link_args = TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-Wl,-q", "-Wl,--pic-veneer"], - ); + let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-Wl,-q", + "-Wl,--pic-veneer", + ]); Target { llvm_target: "thumbv7a-vita-eabihf".into(), diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_freebsd.rs index b955acd0dca97..ed5fc8bcb6454 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_gnueabi.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_gnueabi.rs index 703a9b132b2d9..240edd8a3560b 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_gnueabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_gnueabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; // This target is for glibc Linux on ARMv7 without thumb-mode, NEON or // hardfloat. diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_gnueabihf.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_gnueabihf.rs index db79810b5dd7d..eedaa6b32209c 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_gnueabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_gnueabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; // This target is for glibc Linux on ARMv7 without NEON or // thumb-mode. See the thumbv7neon variant for enabling both. diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_musleabi.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_musleabi.rs index e4e99eab853af..169234973259c 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_musleabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_musleabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; // This target is for musl Linux on ARMv7 without thumb-mode, NEON or // hardfloat. diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_musleabihf.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_musleabihf.rs index 5fc3f7031753d..5adfa0bc2f864 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_musleabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_musleabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; // This target is for musl Linux on ARMv7 without thumb-mode or NEON. diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_ohos.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_ohos.rs index 040a953b12e94..04ea9e3468d2c 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_ohos.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_ohos.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; // This target is for OpenHarmony on ARMv7 Linux with thumb-mode, but no NEON or // hardfloat. diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_uclibceabi.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_uclibceabi.rs index af10d2d90123d..0cc128940211d 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_uclibceabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_uclibceabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; // This target is for uclibc Linux on ARMv7 without NEON, // thumb-mode or hardfloat. diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_uclibceabihf.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_uclibceabihf.rs index 53673daa8129b..abf7f122adf02 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_uclibceabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_linux_uclibceabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; // This target is for uclibc Linux on ARMv7 without NEON or // thumb-mode. See the thumbv7neon variant for enabling both. diff --git a/compiler/rustc_target/src/spec/targets/armv7_unknown_netbsd_eabihf.rs b/compiler/rustc_target/src/spec/targets/armv7_unknown_netbsd_eabihf.rs index 164acd17f21ee..a639bf99d3c4a 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_unknown_netbsd_eabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_unknown_netbsd_eabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv7_wrs_vxworks_eabihf.rs b/compiler/rustc_target/src/spec/targets/armv7_wrs_vxworks_eabihf.rs index f8faec918e4d6..e815a646a4fa6 100644 --- a/compiler/rustc_target/src/spec/targets/armv7_wrs_vxworks_eabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv7_wrs_vxworks_eabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/armv7a_kmc_solid_asp3_eabi.rs b/compiler/rustc_target/src/spec/targets/armv7a_kmc_solid_asp3_eabi.rs index aea897f56b885..7e14c5efe7191 100644 --- a/compiler/rustc_target/src/spec/targets/armv7a_kmc_solid_asp3_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/armv7a_kmc_solid_asp3_eabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, RelocModel, Target, TargetOptions}; +use crate::spec::{RelocModel, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let base = base::solid::opts("asp3"); diff --git a/compiler/rustc_target/src/spec/targets/armv7a_kmc_solid_asp3_eabihf.rs b/compiler/rustc_target/src/spec/targets/armv7a_kmc_solid_asp3_eabihf.rs index be526d6325004..1958f4a7c30a2 100644 --- a/compiler/rustc_target/src/spec/targets/armv7a_kmc_solid_asp3_eabihf.rs +++ b/compiler/rustc_target/src/spec/targets/armv7a_kmc_solid_asp3_eabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, RelocModel, Target, TargetOptions}; +use crate::spec::{RelocModel, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let base = base::solid::opts("asp3"); diff --git a/compiler/rustc_target/src/spec/targets/armv7k_apple_watchos.rs b/compiler/rustc_target/src/spec/targets/armv7k_apple_watchos.rs index 8fe27f60e0af1..e232f54f9b383 100644 --- a/compiler/rustc_target/src/spec/targets/armv7k_apple_watchos.rs +++ b/compiler/rustc_target/src/spec/targets/armv7k_apple_watchos.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{Target, TargetOptions}; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/armv7s_apple_ios.rs b/compiler/rustc_target/src/spec/targets/armv7s_apple_ios.rs index deee6985f1a43..1c3040de06e27 100644 --- a/compiler/rustc_target/src/spec/targets/armv7s_apple_ios.rs +++ b/compiler/rustc_target/src/spec/targets/armv7s_apple_ios.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("Armv7-A Apple-A6 Apple iOS".into()), + description: Some("ARMv7-A Apple-A6 Apple iOS".into()), tier: Some(3), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/avr_unknown_gnu_atmega328.rs b/compiler/rustc_target/src/spec/targets/avr_unknown_gnu_atmega328.rs index 020322b27391d..c3d6fb722733d 100644 --- a/compiler/rustc_target/src/spec/targets/avr_unknown_gnu_atmega328.rs +++ b/compiler/rustc_target/src/spec/targets/avr_unknown_gnu_atmega328.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { base::avr_gnu::target("atmega328", "-mmcu=atmega328") diff --git a/compiler/rustc_target/src/spec/targets/bpfeb_unknown_none.rs b/compiler/rustc_target/src/spec/targets/bpfeb_unknown_none.rs index f4c3a35ced585..df0f29ceab23b 100644 --- a/compiler/rustc_target/src/spec/targets/bpfeb_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/bpfeb_unknown_none.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/bpfel_unknown_none.rs b/compiler/rustc_target/src/spec/targets/bpfel_unknown_none.rs index 6ef72c4021050..691acf89d641f 100644 --- a/compiler/rustc_target/src/spec/targets/bpfel_unknown_none.rs +++ b/compiler/rustc_target/src/spec/targets/bpfel_unknown_none.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/csky_unknown_linux_gnuabiv2.rs b/compiler/rustc_target/src/spec/targets/csky_unknown_linux_gnuabiv2.rs index 61c246fc4cbf8..c90d3bcc6ae98 100644 --- a/compiler/rustc_target/src/spec/targets/csky_unknown_linux_gnuabiv2.rs +++ b/compiler/rustc_target/src/spec/targets/csky_unknown_linux_gnuabiv2.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, TargetOptions, base}; // This target is for glibc Linux on Csky diff --git a/compiler/rustc_target/src/spec/targets/csky_unknown_linux_gnuabiv2hf.rs b/compiler/rustc_target/src/spec/targets/csky_unknown_linux_gnuabiv2hf.rs index 91c33caae3e2a..d0583b7866b94 100644 --- a/compiler/rustc_target/src/spec/targets/csky_unknown_linux_gnuabiv2hf.rs +++ b/compiler/rustc_target/src/spec/targets/csky_unknown_linux_gnuabiv2hf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, TargetOptions, base}; // This target is for glibc Linux on Csky diff --git a/compiler/rustc_target/src/spec/targets/hexagon_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/hexagon_unknown_linux_musl.rs index cddc3a33f9fb3..003600c26cc79 100644 --- a/compiler/rustc_target/src/spec/targets/hexagon_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/hexagon_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Target}; +use crate::spec::{Cc, LinkerFlavor, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i386_apple_ios.rs b/compiler/rustc_target/src/spec/targets/i386_apple_ios.rs index dc14cb3ec767f..41c5fafe34186 100644 --- a/compiler/rustc_target/src/spec/targets/i386_apple_ios.rs +++ b/compiler/rustc_target/src/spec/targets/i386_apple_ios.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -8,7 +8,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("32-bit x86 iOS".into()), + description: Some("x86 Apple iOS Simulator".into()), tier: Some(3), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs b/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs index cf0577d8cb01a..2519b935c03a7 100644 --- a/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs +++ b/compiler/rustc_target/src/spec/targets/i586_pc_nto_qnx700.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { @@ -17,10 +17,9 @@ pub(crate) fn target() -> Target { options: TargetOptions { cpu: "pentium4".into(), max_atomic_width: Some(64), - pre_link_args: TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-Vgcc_ntox86_cxx"], - ), + pre_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-Vgcc_ntox86_cxx", + ]), env: "nto70".into(), stack_probes: StackProbeType::Inline, ..base::nto_qnx::opts() diff --git a/compiler/rustc_target/src/spec/targets/i586_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/i586_unknown_netbsd.rs index 3c5ba157c1ecc..6aa34f157ab43 100644 --- a/compiler/rustc_target/src/spec/targets/i586_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/i586_unknown_netbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::netbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_apple_darwin.rs b/compiler/rustc_target/src/spec/targets/i686_apple_darwin.rs index 3e27f1f899b72..6adf690e0dd8b 100644 --- a/compiler/rustc_target/src/spec/targets/i686_apple_darwin.rs +++ b/compiler/rustc_target/src/spec/targets/i686_apple_darwin.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("32-bit macOS (10.12+, Sierra+)".into()), + description: Some("x86 Apple macOS (10.12+, Sierra+)".into()), tier: Some(3), host_tools: Some(true), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/i686_linux_android.rs b/compiler/rustc_target/src/spec/targets/i686_linux_android.rs index bce41976a9697..dcf9b6b4460f3 100644 --- a/compiler/rustc_target/src/spec/targets/i686_linux_android.rs +++ b/compiler/rustc_target/src/spec/targets/i686_linux_android.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, StackProbeType, Target, TargetOptions}; +use crate::spec::{SanitizerSet, StackProbeType, Target, TargetOptions, base}; // See https://developer.android.com/ndk/guides/abis.html#x86 // for target ABI requirements. diff --git a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs index 7288359f564af..9ef8e120e0de4 100644 --- a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, FramePointer, LinkerFlavor, Lld, Target}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_gnu::opts(); @@ -9,10 +9,11 @@ pub(crate) fn target() -> Target { // Mark all dynamic libraries and executables as compatible with the larger 4GiB address // space available to x86 Windows binaries on x86_64. - base.add_pre_link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &["-m", "i386pe", "--large-address-aware"], - ); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "-m", + "i386pe", + "--large-address-aware", + ]); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-Wl,--large-address-aware"]); Target { diff --git a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs index a38e67b96f0db..13d3c5532ffd4 100644 --- a/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs +++ b/compiler/rustc_target/src/spec/targets/i686_pc_windows_gnullvm.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, FramePointer, LinkerFlavor, Lld, Target}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_gnullvm::opts(); @@ -9,10 +9,11 @@ pub(crate) fn target() -> Target { // Mark all dynamic libraries and executables as compatible with the larger 4GiB address // space available to x86 Windows binaries on x86_64. - base.add_pre_link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &["-m", "i386pe", "--large-address-aware"], - ); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "-m", + "i386pe", + "--large-address-aware", + ]); Target { llvm_target: "i686-pc-windows-gnu".into(), diff --git a/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs index a8e1ad45014ac..aacad26686315 100644 --- a/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/i686_pc_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, LinkerFlavor, Lld, SanitizerSet, Target}; +use crate::spec::{LinkerFlavor, Lld, SanitizerSet, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); @@ -6,18 +6,15 @@ pub(crate) fn target() -> Target { base.max_atomic_width = Some(64); base.supported_sanitizers = SanitizerSet::ADDRESS; - base.add_pre_link_args( - LinkerFlavor::Msvc(Lld::No), - &[ - // Mark all dynamic libraries and executables as compatible with the larger 4GiB address - // space available to x86 Windows binaries on x86_64. - "/LARGEADDRESSAWARE", - // Ensure the linker will only produce an image if it can also produce a table of - // the image's safe exception handlers. - // https://docs.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers - "/SAFESEH", - ], - ); + base.add_pre_link_args(LinkerFlavor::Msvc(Lld::No), &[ + // Mark all dynamic libraries and executables as compatible with the larger 4GiB address + // space available to x86 Windows binaries on x86_64. + "/LARGEADDRESSAWARE", + // Ensure the linker will only produce an image if it can also produce a table of + // the image's safe exception handlers. + // https://docs.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers + "/SAFESEH", + ]); Target { llvm_target: "i686-pc-windows-msvc".into(), diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_freebsd.rs index 8ba58dfd705ba..85ab87cc07f77 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::freebsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs index b2316fd3bf422..1ab493c787c2a 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_haiku.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::haiku::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_hurd_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_hurd_gnu.rs index 2e303ff402fa6..3961656d1b61c 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_hurd_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_hurd_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::hurd_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_linux_gnu.rs index 15bc4da1775a0..c95cb308d7f5c 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_linux_musl.rs index 8dd08a9567b46..b805b80b85b42 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, FramePointer, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_netbsd.rs index 02a95ee6626f2..092ba5c7baa16 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_netbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::netbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_openbsd.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_openbsd.rs index b8c9efc7c471a..7ae9189e23393 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_openbsd.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_openbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::openbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_redox.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_redox.rs index 0e00249d66cf7..bfe52a330d30d 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_redox.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_redox.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::redox::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_unknown_uefi.rs b/compiler/rustc_target/src/spec/targets/i686_unknown_uefi.rs index 3cda78003edbe..39d3a5a46330f 100644 --- a/compiler/rustc_target/src/spec/targets/i686_unknown_uefi.rs +++ b/compiler/rustc_target/src/spec/targets/i686_unknown_uefi.rs @@ -5,7 +5,7 @@ // The cdecl ABI is used. It differs from the stdcall or fastcall ABI. // "i686-unknown-windows" is used to get the minimal subset of windows-specific features. -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { let mut base = base::uefi_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs index 901c9fc378d21..ffb9926e9444b 100644 --- a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, FramePointer, LinkerFlavor, Lld, Target}; +use crate::spec::{Cc, FramePointer, LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_uwp_gnu::opts(); @@ -8,10 +8,11 @@ pub(crate) fn target() -> Target { // Mark all dynamic libraries and executables as compatible with the larger 4GiB address // space available to x86 Windows binaries on x86_64. - base.add_pre_link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &["-m", "i386pe", "--large-address-aware"], - ); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "-m", + "i386pe", + "--large-address-aware", + ]); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-Wl,--large-address-aware"]); Target { diff --git a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_msvc.rs index c7703666ae032..e0de9b9af45f2 100644 --- a/compiler/rustc_target/src/spec/targets/i686_uwp_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/i686_uwp_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_uwp_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs index 79302cdc0a1a3..4fc395c221cb6 100644 --- a/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/i686_win7_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, LinkerFlavor, Lld, Target}; +use crate::spec::{LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); @@ -6,18 +6,15 @@ pub(crate) fn target() -> Target { base.max_atomic_width = Some(64); base.vendor = "win7".into(); - base.add_pre_link_args( - LinkerFlavor::Msvc(Lld::No), - &[ - // Mark all dynamic libraries and executables as compatible with the larger 4GiB address - // space available to x86 Windows binaries on x86_64. - "/LARGEADDRESSAWARE", - // Ensure the linker will only produce an image if it can also produce a table of - // the image's safe exception handlers. - // https://docs.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers - "/SAFESEH", - ], - ); + base.add_pre_link_args(LinkerFlavor::Msvc(Lld::No), &[ + // Mark all dynamic libraries and executables as compatible with the larger 4GiB address + // space available to x86 Windows binaries on x86_64. + "/LARGEADDRESSAWARE", + // Ensure the linker will only produce an image if it can also produce a table of + // the image's safe exception handlers. + // https://docs.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers + "/SAFESEH", + ]); Target { llvm_target: "i686-pc-windows-msvc".into(), diff --git a/compiler/rustc_target/src/spec/targets/i686_wrs_vxworks.rs b/compiler/rustc_target/src/spec/targets/i686_wrs_vxworks.rs index ba669334e7f4d..c2b9bc14ca438 100644 --- a/compiler/rustc_target/src/spec/targets/i686_wrs_vxworks.rs +++ b/compiler/rustc_target/src/spec/targets/i686_wrs_vxworks.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::vxworks::opts(); diff --git a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_gnu.rs index 0bcbf655bd89e..de8d99977b438 100644 --- a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, CodeModel, Target, TargetOptions}; +use crate::spec::{CodeModel, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs index 223d979a06fbf..a5088bcd5c257 100644 --- a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, CodeModel, Target, TargetOptions}; +use crate::spec::{CodeModel, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_ohos.rs b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_ohos.rs new file mode 100644 index 0000000000000..f9f7098684e6e --- /dev/null +++ b/compiler/rustc_target/src/spec/targets/loongarch64_unknown_linux_ohos.rs @@ -0,0 +1,24 @@ +use crate::spec::{Target, TargetOptions, base}; + +pub(crate) fn target() -> Target { + Target { + // LLVM 15 doesn't support OpenHarmony yet, use a linux target instead. + llvm_target: "loongarch64-unknown-linux-musl".into(), + metadata: crate::spec::TargetMetadata { + description: Some("LoongArch64 OpenHarmony".into()), + tier: Some(3), + host_tools: Some(false), + std: Some(true), + }, + pointer_width: 64, + data_layout: "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128".into(), + arch: "loongarch64".into(), + options: TargetOptions { + cpu: "generic".into(), + features: "+f,+d".into(), + llvm_abiname: "lp64d".into(), + max_atomic_width: Some(64), + ..base::linux_ohos::opts() + }, + } +} diff --git a/compiler/rustc_target/src/spec/targets/m68k_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/m68k_unknown_linux_gnu.rs index 9d9f6145e2f5d..c0bcc79b5b9a5 100644 --- a/compiler/rustc_target/src/spec/targets/m68k_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/m68k_unknown_linux_gnu.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/mips64_openwrt_linux_musl.rs b/compiler/rustc_target/src/spec/targets/mips64_openwrt_linux_musl.rs index 72577749ac64f..e83a43c1df257 100644 --- a/compiler/rustc_target/src/spec/targets/mips64_openwrt_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/mips64_openwrt_linux_musl.rs @@ -1,7 +1,7 @@ //! A target tuple for OpenWrt MIPS64 targets. use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_gnuabi64.rs b/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_gnuabi64.rs index 1fad6be2f8df3..252d614e9ac9d 100644 --- a/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_gnuabi64.rs +++ b/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_gnuabi64.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_muslabi64.rs b/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_muslabi64.rs index 7627131bc2fe6..a1a596c9f1bc9 100644 --- a/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_muslabi64.rs +++ b/compiler/rustc_target/src/spec/targets/mips64_unknown_linux_muslabi64.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/mips64el_unknown_linux_gnuabi64.rs b/compiler/rustc_target/src/spec/targets/mips64el_unknown_linux_gnuabi64.rs index f93e5676b051d..35d2911fa9d6b 100644 --- a/compiler/rustc_target/src/spec/targets/mips64el_unknown_linux_gnuabi64.rs +++ b/compiler/rustc_target/src/spec/targets/mips64el_unknown_linux_gnuabi64.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mips64el_unknown_linux_muslabi64.rs b/compiler/rustc_target/src/spec/targets/mips64el_unknown_linux_muslabi64.rs index 6fbb4f40024d9..9dab932aed408 100644 --- a/compiler/rustc_target/src/spec/targets/mips64el_unknown_linux_muslabi64.rs +++ b/compiler/rustc_target/src/spec/targets/mips64el_unknown_linux_muslabi64.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/mips_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/mips_unknown_linux_gnu.rs index 778b0041214db..b9dc0d4a6ceb0 100644 --- a/compiler/rustc_target/src/spec/targets/mips_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/mips_unknown_linux_gnu.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mips_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/mips_unknown_linux_musl.rs index 2cce3271c57f8..b283b3b1ef79d 100644 --- a/compiler/rustc_target/src/spec/targets/mips_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/mips_unknown_linux_musl.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/mips_unknown_linux_uclibc.rs b/compiler/rustc_target/src/spec/targets/mips_unknown_linux_uclibc.rs index ef7d6bf82e321..36e61d55fa066 100644 --- a/compiler/rustc_target/src/spec/targets/mips_unknown_linux_uclibc.rs +++ b/compiler/rustc_target/src/spec/targets/mips_unknown_linux_uclibc.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mipsel_sony_psp.rs b/compiler/rustc_target/src/spec/targets/mipsel_sony_psp.rs index 850808b4c7ba1..bf51d86437212 100644 --- a/compiler/rustc_target/src/spec/targets/mipsel_sony_psp.rs +++ b/compiler/rustc_target/src/spec/targets/mipsel_sony_psp.rs @@ -1,13 +1,13 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, RelocModel, Target, TargetOptions, cvs}; // The PSP has custom linker requirements. const LINKER_SCRIPT: &str = include_str!("./mipsel_sony_psp_linker_script.ld"); pub(crate) fn target() -> Target { - let pre_link_args = TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &["--emit-relocs", "--nmagic"], - ); + let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "--emit-relocs", + "--nmagic", + ]); Target { llvm_target: "mipsel-sony-psp".into(), diff --git a/compiler/rustc_target/src/spec/targets/mipsel_sony_psx.rs b/compiler/rustc_target/src/spec/targets/mipsel_sony_psx.rs index 761495b2a29fb..c60bf65031128 100644 --- a/compiler/rustc_target/src/spec/targets/mipsel_sony_psx.rs +++ b/compiler/rustc_target/src/spec/targets/mipsel_sony_psx.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_gnu.rs index 2784b3714690c..08226449358a2 100644 --- a/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_musl.rs index 1b2d8e9a105f2..744396aa1babd 100644 --- a/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_uclibc.rs b/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_uclibc.rs index 21f03a40ec2d5..88474e71848c2 100644 --- a/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_uclibc.rs +++ b/compiler/rustc_target/src/spec/targets/mipsel_unknown_linux_uclibc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mipsel_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/mipsel_unknown_netbsd.rs index ea2fb2e7f3aad..e1adeb98ec213 100644 --- a/compiler/rustc_target/src/spec/targets/mipsel_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/mipsel_unknown_netbsd.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::netbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/mipsisa32r6_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/mipsisa32r6_unknown_linux_gnu.rs index 5c07e9ea6dddb..2ff06dc6669bb 100644 --- a/compiler/rustc_target/src/spec/targets/mipsisa32r6_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/mipsisa32r6_unknown_linux_gnu.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mipsisa32r6el_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/mipsisa32r6el_unknown_linux_gnu.rs index 63b3cc47ffc26..05b246698482a 100644 --- a/compiler/rustc_target/src/spec/targets/mipsisa32r6el_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/mipsisa32r6el_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mipsisa64r6_unknown_linux_gnuabi64.rs b/compiler/rustc_target/src/spec/targets/mipsisa64r6_unknown_linux_gnuabi64.rs index 7f5e2edb03613..89ba7b889ec85 100644 --- a/compiler/rustc_target/src/spec/targets/mipsisa64r6_unknown_linux_gnuabi64.rs +++ b/compiler/rustc_target/src/spec/targets/mipsisa64r6_unknown_linux_gnuabi64.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/mipsisa64r6el_unknown_linux_gnuabi64.rs b/compiler/rustc_target/src/spec/targets/mipsisa64r6el_unknown_linux_gnuabi64.rs index a2d807bcfe1b9..195894d9aac4d 100644 --- a/compiler/rustc_target/src/spec/targets/mipsisa64r6el_unknown_linux_gnuabi64.rs +++ b/compiler/rustc_target/src/spec/targets/mipsisa64r6el_unknown_linux_gnuabi64.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/msp430_none_elf.rs b/compiler/rustc_target/src/spec/targets/msp430_none_elf.rs index 5bc5f79d1b6c6..80cb740450a83 100644 --- a/compiler/rustc_target/src/spec/targets/msp430_none_elf.rs +++ b/compiler/rustc_target/src/spec/targets/msp430_none_elf.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/powerpc64_ibm_aix.rs b/compiler/rustc_target/src/spec/targets/powerpc64_ibm_aix.rs index 0f90efb4bb3db..0f361054f7a02 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64_ibm_aix.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64_ibm_aix.rs @@ -1,12 +1,14 @@ -use crate::spec::{base, Cc, LinkerFlavor, Target}; +use crate::spec::{Cc, LinkerFlavor, Target, base}; pub(crate) fn target() -> Target { let mut base = base::aix::opts(); base.max_atomic_width = Some(64); - base.add_pre_link_args( - LinkerFlavor::Unix(Cc::No), - &["-b64", "-bpT:0x100000000", "-bpD:0x110000000", "-bcdtors:all:0:s"], - ); + base.add_pre_link_args(LinkerFlavor::Unix(Cc::No), &[ + "-b64", + "-bpT:0x100000000", + "-bpD:0x110000000", + "-bcdtors:all:0:s", + ]); Target { llvm_target: "powerpc64-ibm-aix".into(), diff --git a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_freebsd.rs index 89afe2343768e..680b024cb6e60 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_freebsd.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::freebsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_gnu.rs index e39849c9b1883..5acd9205a8c74 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_gnu.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_musl.rs index 24a56f917e5d5..5da891cc13f6d 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_linux_musl.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_openbsd.rs b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_openbsd.rs index 1dab74e93762e..c723847cada73 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64_unknown_openbsd.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64_unknown_openbsd.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::openbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc64_wrs_vxworks.rs b/compiler/rustc_target/src/spec/targets/powerpc64_wrs_vxworks.rs index 1029a135e4aa7..11cf957cc1859 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64_wrs_vxworks.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64_wrs_vxworks.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::vxworks::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_freebsd.rs index 3c9d01e2d18d0..e194f5f8a36f3 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::freebsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_linux_gnu.rs index df8f9f07c2f3e..23913687a1fd8 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_linux_musl.rs index 909a25304f46f..e2921aa17fe64 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc64le_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_freebsd.rs index e8f09d70cc844..393946980f8b3 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_freebsd.rs @@ -1,13 +1,13 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::freebsd::opts(); // Extra hint to linker that we are generating secure-PLT code. - base.add_pre_link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-m32", "--target=powerpc-unknown-freebsd13.0"], - ); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-m32", + "--target=powerpc-unknown-freebsd13.0", + ]); base.max_atomic_width = Some(32); base.stack_probes = StackProbeType::Inline; diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_gnu.rs index 9e5cea6eff586..1ae879d01bd46 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_gnu.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_gnuspe.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_gnuspe.rs index dbea70168a52a..4a5ab375c7307 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_gnuspe.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_gnuspe.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_musl.rs index 86840f16d902c..9859e8ced4f46 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_musl.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_muslspe.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_muslspe.rs index 51cd3c186fa9a..2305db81c5edf 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_muslspe.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_linux_muslspe.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_netbsd.rs index 7129fe42876d3..142443aa5b159 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_netbsd.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::netbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc_unknown_openbsd.rs b/compiler/rustc_target/src/spec/targets/powerpc_unknown_openbsd.rs index 6e98ecce45b74..a8254af9736c0 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_unknown_openbsd.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_unknown_openbsd.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, StackProbeType, Target}; +use crate::spec::{StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::openbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc_wrs_vxworks.rs b/compiler/rustc_target/src/spec/targets/powerpc_wrs_vxworks.rs index b19513bf1d7c9..24cad76b00040 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_wrs_vxworks.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_wrs_vxworks.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::vxworks::opts(); diff --git a/compiler/rustc_target/src/spec/targets/powerpc_wrs_vxworks_spe.rs b/compiler/rustc_target/src/spec/targets/powerpc_wrs_vxworks_spe.rs index 8484c160a99c2..ee61a7da41c9c 100644 --- a/compiler/rustc_target/src/spec/targets/powerpc_wrs_vxworks_spe.rs +++ b/compiler/rustc_target/src/spec/targets/powerpc_wrs_vxworks_spe.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::vxworks::opts(); diff --git a/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_gnu.rs index 8913df3b95465..8b0a140c9ade5 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_gnu.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use crate::spec::{base, CodeModel, SplitDebuginfo, Target, TargetOptions}; +use crate::spec::{CodeModel, SplitDebuginfo, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_musl.rs index 5717e7a390754..212de791e499a 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32gc_unknown_linux_musl.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use crate::spec::{base, CodeModel, SplitDebuginfo, Target, TargetOptions}; +use crate::spec::{CodeModel, SplitDebuginfo, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv32imac_esp_espidf.rs b/compiler/rustc_target/src/spec/targets/riscv32imac_esp_espidf.rs index 0d453901efa73..9795af5656941 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imac_esp_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imac_esp_espidf.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_nuttx_elf.rs index 5ee6b3cbfa6ee..62397dcae9a1b 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imac_unknown_nuttx_elf.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv32imafc_esp_espidf.rs b/compiler/rustc_target/src/spec/targets/riscv32imafc_esp_espidf.rs index c2882151d3d18..0d5eda708d100 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imafc_esp_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imafc_esp_espidf.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv32imafc_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32imafc_unknown_nuttx_elf.rs index dcd4fcd9b4836..08dd3cc2a09de 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imafc_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imafc_unknown_nuttx_elf.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv32imc_esp_espidf.rs b/compiler/rustc_target/src/spec/targets/riscv32imc_esp_espidf.rs index 50d36e724a2c3..9ae84ace457dd 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imc_esp_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imc_esp_espidf.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_nuttx_elf.rs index eab18064334a5..5f3917edf7019 100644 --- a/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv32imc_unknown_nuttx_elf.rs @@ -1,4 +1,4 @@ -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, PanicStrategy, RelocModel, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64_linux_android.rs b/compiler/rustc_target/src/spec/targets/riscv64_linux_android.rs index 00059a2691dc2..8b5d4751a5733 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64_linux_android.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64_linux_android.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use crate::spec::{base, CodeModel, SanitizerSet, SplitDebuginfo, Target, TargetOptions}; +use crate::spec::{CodeModel, SanitizerSet, SplitDebuginfo, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_freebsd.rs index 8d2b16c45016e..d1b0d801fd60b 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, CodeModel, Target, TargetOptions}; +use crate::spec::{CodeModel, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_fuchsia.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_fuchsia.rs index f5e6b1cbd78f4..6de51f9b07e2a 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_fuchsia.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_fuchsia.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, CodeModel, SanitizerSet, Target, TargetOptions}; +use crate::spec::{CodeModel, SanitizerSet, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_hermit.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_hermit.rs index 3033479358ecd..a24e24edc59d3 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_hermit.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_hermit.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, CodeModel, RelocModel, Target, TargetOptions, TlsModel}; +use crate::spec::{CodeModel, RelocModel, Target, TargetOptions, TlsModel, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_gnu.rs index 07253803f5c2e..da2c272005d76 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_gnu.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use crate::spec::{base, CodeModel, SplitDebuginfo, Target, TargetOptions}; +use crate::spec::{CodeModel, SplitDebuginfo, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_musl.rs index 9b0b14cb1088d..2e6fce91d4c75 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_linux_musl.rs @@ -1,6 +1,6 @@ use std::borrow::Cow; -use crate::spec::{base, CodeModel, SplitDebuginfo, Target, TargetOptions}; +use crate::spec::{CodeModel, SplitDebuginfo, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_netbsd.rs index 3eb9366c850b6..9edec38f65282 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_netbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, CodeModel, Target, TargetOptions}; +use crate::spec::{CodeModel, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_nuttx_elf.rs index 27b8ae99753bc..c389759aecd2c 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_nuttx_elf.rs @@ -1,6 +1,6 @@ use crate::spec::{ - cvs, Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, SanitizerSet, Target, - TargetOptions, + Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, SanitizerSet, Target, + TargetOptions, cvs, }; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_openbsd.rs b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_openbsd.rs index dca8a524b103f..6aacb04418e24 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_openbsd.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64gc_unknown_openbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, CodeModel, Target, TargetOptions}; +use crate::spec::{CodeModel, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs index 5fbc2a86fa942..a737e46de1baa 100644 --- a/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs +++ b/compiler/rustc_target/src/spec/targets/riscv64imac_unknown_nuttx_elf.rs @@ -1,6 +1,6 @@ use crate::spec::{ - cvs, Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, SanitizerSet, Target, - TargetOptions, + Cc, CodeModel, LinkerFlavor, Lld, PanicStrategy, RelocModel, SanitizerSet, Target, + TargetOptions, cvs, }; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_gnu.rs index 71086daaf2c90..a8163e228e690 100644 --- a/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_gnu.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, SanitizerSet, StackProbeType, Target}; +use crate::spec::{SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_musl.rs index 016ff5abe4ccd..e52bcc987f9ba 100644 --- a/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/s390x_unknown_linux_musl.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, SanitizerSet, StackProbeType, Target}; +use crate::spec::{SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/sparc64_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/sparc64_unknown_linux_gnu.rs index 7c37fa0d63259..7d089aeb78714 100644 --- a/compiler/rustc_target/src/spec/targets/sparc64_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/sparc64_unknown_linux_gnu.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/sparc64_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/sparc64_unknown_netbsd.rs index 842e35392dcea..21f09d6428ed4 100644 --- a/compiler/rustc_target/src/spec/targets/sparc64_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/sparc64_unknown_netbsd.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::netbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/sparc64_unknown_openbsd.rs b/compiler/rustc_target/src/spec/targets/sparc64_unknown_openbsd.rs index a8767fa9d3c06..12626dce47708 100644 --- a/compiler/rustc_target/src/spec/targets/sparc64_unknown_openbsd.rs +++ b/compiler/rustc_target/src/spec/targets/sparc64_unknown_openbsd.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::openbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs index 7089fc511242a..08f0bb302dd47 100644 --- a/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/sparc_unknown_linux_gnu.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { @@ -16,10 +16,9 @@ pub(crate) fn target() -> Target { options: TargetOptions { cpu: "v9".into(), endian: Endian::Big, - late_link_args: TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-mcpu=v9", "-m32"], - ), + late_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-mcpu=v9", "-m32", + ]), max_atomic_width: Some(32), ..base::linux_gnu::opts() }, diff --git a/compiler/rustc_target/src/spec/targets/sparcv9_sun_solaris.rs b/compiler/rustc_target/src/spec/targets/sparcv9_sun_solaris.rs index a932632b85740..138ce902d5eba 100644 --- a/compiler/rustc_target/src/spec/targets/sparcv9_sun_solaris.rs +++ b/compiler/rustc_target/src/spec/targets/sparcv9_sun_solaris.rs @@ -1,5 +1,5 @@ use crate::abi::Endian; -use crate::spec::{base, Cc, LinkerFlavor, Target}; +use crate::spec::{Cc, LinkerFlavor, Target, base}; pub(crate) fn target() -> Target { let mut base = base::solaris::opts(); diff --git a/compiler/rustc_target/src/spec/targets/thumbv4t_none_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv4t_none_eabi.rs index 0f5e16408932f..6368cbfe7c21d 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv4t_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv4t_none_eabi.rs @@ -9,7 +9,7 @@ //! The default link script is very likely wrong, so you should use //! `-Clink-arg=-Tmy_script.ld` to override that with a correct linker script. -use crate::spec::{base, cvs, FramePointer, PanicStrategy, RelocModel, Target, TargetOptions}; +use crate::spec::{FramePointer, PanicStrategy, RelocModel, Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv5te_none_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv5te_none_eabi.rs index 6ae41ce439939..afd48e6ea1669 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv5te_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv5te_none_eabi.rs @@ -1,6 +1,6 @@ //! Targets the ARMv5TE, with code as `t32` code by default. -use crate::spec::{base, cvs, FramePointer, Target, TargetOptions}; +use crate::spec::{FramePointer, Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv6m_none_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv6m_none_eabi.rs index 9d4cc66c7f075..1eac51b8e0a77 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv6m_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv6m_none_eabi.rs @@ -1,6 +1,6 @@ // Targets the Cortex-M0, Cortex-M0+ and Cortex-M1 processors (ARMv6-M architecture) -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv6m_nuttx_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv6m_nuttx_eabi.rs index bc9d9856e036e..0a6dc88c1457b 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv6m_nuttx_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv6m_nuttx_eabi.rs @@ -1,6 +1,6 @@ // Targets the Cortex-M0, Cortex-M0+ and Cortex-M1 processors (ARMv6-M architecture) -use crate::spec::{base, cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv7a_pc_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/thumbv7a_pc_windows_msvc.rs index a927cf6902e92..861604987f84c 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7a_pc_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7a_pc_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, LinkerFlavor, Lld, PanicStrategy, Target, TargetOptions}; +use crate::spec::{LinkerFlavor, Lld, PanicStrategy, Target, TargetOptions, base}; pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/thumbv7a_uwp_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/thumbv7a_uwp_windows_msvc.rs index 473113854a81b..bb30f81fb20b5 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7a_uwp_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7a_uwp_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, PanicStrategy, Target, TargetOptions}; +use crate::spec::{PanicStrategy, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv7em_none_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv7em_none_eabi.rs index dca3e73dda570..d35d30c34a31c 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7em_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7em_none_eabi.rs @@ -9,7 +9,7 @@ // To opt-in to hardware accelerated floating point operations, you can use, for example, // `-C target-feature=+vfp4` or `-C target-cpu=cortex-m4`. -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv7em_none_eabihf.rs b/compiler/rustc_target/src/spec/targets/thumbv7em_none_eabihf.rs index acc5acfbfb684..c439059728280 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7em_none_eabihf.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7em_none_eabihf.rs @@ -8,7 +8,7 @@ // // To opt into double precision hardware support, use the `-C target-feature=+fp64` flag. -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv7em_nuttx_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv7em_nuttx_eabi.rs index b4cd9686f5cc9..0f3457402a593 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7em_nuttx_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7em_nuttx_eabi.rs @@ -9,7 +9,7 @@ // To opt-in to hardware accelerated floating point operations, you can use, for example, // `-C target-feature=+vfp4` or `-C target-cpu=cortex-m4`. -use crate::spec::{base, cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv7em_nuttx_eabihf.rs b/compiler/rustc_target/src/spec/targets/thumbv7em_nuttx_eabihf.rs index bdb3a38be9391..99612e132a9d0 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7em_nuttx_eabihf.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7em_nuttx_eabihf.rs @@ -8,7 +8,7 @@ // // To opt into double precision hardware support, use the `-C target-feature=+fp64` flag. -use crate::spec::{base, cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv7m_none_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv7m_none_eabi.rs index f5615de231544..1727add111509 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7m_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7m_none_eabi.rs @@ -1,6 +1,6 @@ // Targets the Cortex-M3 processor (ARMv7-M) -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv7m_nuttx_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv7m_nuttx_eabi.rs index 0e3663e1603b9..07c19376a311a 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7m_nuttx_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7m_nuttx_eabi.rs @@ -1,6 +1,6 @@ // Targets the Cortex-M3 processor (ARMv7-M) -use crate::spec::{base, cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv7neon_linux_androideabi.rs b/compiler/rustc_target/src/spec/targets/thumbv7neon_linux_androideabi.rs index 9b4d13a96c8ff..19bb515e3c306 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7neon_linux_androideabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7neon_linux_androideabi.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, TargetOptions, base}; // This target if is for the Android v7a ABI in thumb mode with // NEON unconditionally enabled and, therefore, with 32 FPU registers diff --git a/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_gnueabihf.rs b/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_gnueabihf.rs index b85b9b60b4209..45de2e82f5a88 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_gnueabihf.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_gnueabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; // This target is for glibc Linux on ARMv7 with thumb mode enabled // (for consistency with Android and Debian-based distributions) diff --git a/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_musleabihf.rs b/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_musleabihf.rs index f53f21d721772..5c43ca69bd852 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_musleabihf.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv7neon_unknown_linux_musleabihf.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; // This target is for musl Linux on ARMv7 with thumb mode enabled // (for consistency with Android and Debian-based distributions) diff --git a/compiler/rustc_target/src/spec/targets/thumbv8m_base_none_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv8m_base_none_eabi.rs index e392240a3335b..3856cdff05c77 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv8m_base_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv8m_base_none_eabi.rs @@ -1,6 +1,6 @@ // Targets the Cortex-M23 processor (Baseline ARMv8-M) -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv8m_base_nuttx_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv8m_base_nuttx_eabi.rs index 903b8f029114b..9f493b6904594 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv8m_base_nuttx_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv8m_base_nuttx_eabi.rs @@ -1,6 +1,6 @@ // Targets the Cortex-M23 processor (Baseline ARMv8-M) -use crate::spec::{base, cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv8m_main_none_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv8m_main_none_eabi.rs index d287321c9f293..3f8d20f48f76d 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv8m_main_none_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv8m_main_none_eabi.rs @@ -1,7 +1,7 @@ // Targets the Cortex-M33 processor (Armv8-M Mainline architecture profile), // without the Floating Point extension. -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv8m_main_none_eabihf.rs b/compiler/rustc_target/src/spec/targets/thumbv8m_main_none_eabihf.rs index 74b143f69956e..7c8fa078e2628 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv8m_main_none_eabihf.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv8m_main_none_eabihf.rs @@ -1,7 +1,7 @@ // Targets the Cortex-M33 processor (Armv8-M Mainline architecture profile), // with the Floating Point extension. -use crate::spec::{base, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv8m_main_nuttx_eabi.rs b/compiler/rustc_target/src/spec/targets/thumbv8m_main_nuttx_eabi.rs index c5de209246c7a..f73360e8501ac 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv8m_main_nuttx_eabi.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv8m_main_nuttx_eabi.rs @@ -1,7 +1,7 @@ // Targets the Cortex-M33 processor (Armv8-M Mainline architecture profile), // without the Floating Point extension. -use crate::spec::{base, cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/thumbv8m_main_nuttx_eabihf.rs b/compiler/rustc_target/src/spec/targets/thumbv8m_main_nuttx_eabihf.rs index 44ad78b4684a7..cf642e3189612 100644 --- a/compiler/rustc_target/src/spec/targets/thumbv8m_main_nuttx_eabihf.rs +++ b/compiler/rustc_target/src/spec/targets/thumbv8m_main_nuttx_eabihf.rs @@ -1,7 +1,7 @@ // Targets the Cortex-M33 processor (Armv8-M Mainline architecture profile), // with the Floating Point extension. -use crate::spec::{base, cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, base, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/wasm32_unknown_emscripten.rs b/compiler/rustc_target/src/spec/targets/wasm32_unknown_emscripten.rs index c22f1589ca137..a213adadbea78 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_unknown_emscripten.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_unknown_emscripten.rs @@ -1,5 +1,5 @@ use crate::spec::{ - base, cvs, LinkArgs, LinkerFlavor, PanicStrategy, RelocModel, Target, TargetOptions, + LinkArgs, LinkerFlavor, PanicStrategy, RelocModel, Target, TargetOptions, base, cvs, }; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/wasm32_unknown_unknown.rs b/compiler/rustc_target/src/spec/targets/wasm32_unknown_unknown.rs index 300108530a5b2..e7165533b9c09 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_unknown_unknown.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_unknown_unknown.rs @@ -10,29 +10,23 @@ //! This target is more or less managed by the Rust and WebAssembly Working //! Group nowadays at . -use crate::spec::{base, Cc, LinkerFlavor, Target}; +use crate::spec::{Cc, LinkerFlavor, Target, base}; pub(crate) fn target() -> Target { let mut options = base::wasm::options(); options.os = "unknown".into(); - options.add_pre_link_args( - LinkerFlavor::WasmLld(Cc::No), - &[ - // For now this target just never has an entry symbol no matter the output - // type, so unconditionally pass this. - "--no-entry", - ], - ); - options.add_pre_link_args( - LinkerFlavor::WasmLld(Cc::Yes), - &[ - // Make sure clang uses LLD as its linker and is configured appropriately - // otherwise - "--target=wasm32-unknown-unknown", - "-Wl,--no-entry", - ], - ); + options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::No), &[ + // For now this target just never has an entry symbol no matter the output + // type, so unconditionally pass this. + "--no-entry", + ]); + options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::Yes), &[ + // Make sure clang uses LLD as its linker and is configured appropriately + // otherwise + "--target=wasm32-unknown-unknown", + "-Wl,--no-entry", + ]); Target { llvm_target: "wasm32-unknown-unknown".into(), diff --git a/compiler/rustc_target/src/spec/targets/wasm32_wasip1.rs b/compiler/rustc_target/src/spec/targets/wasm32_wasip1.rs index 7728d83c2b680..89d0721bf353e 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_wasip1.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_wasip1.rs @@ -10,7 +10,7 @@ //! was since renamed to `wasm32-wasip1` after the preview2 target was //! introduced. -use crate::spec::{base, crt_objects, Cc, LinkSelfContainedDefault, LinkerFlavor, Target}; +use crate::spec::{Cc, LinkSelfContainedDefault, LinkerFlavor, Target, base, crt_objects}; pub(crate) fn target() -> Target { let mut options = base::wasm::options(); diff --git a/compiler/rustc_target/src/spec/targets/wasm32_wasip1_threads.rs b/compiler/rustc_target/src/spec/targets/wasm32_wasip1_threads.rs index 0ae844c8da8ff..19bc5db4d9bcc 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_wasip1_threads.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_wasip1_threads.rs @@ -7,7 +7,7 @@ //! //! Historically this target was known as `wasm32-wasi-preview1-threads`. -use crate::spec::{base, crt_objects, Cc, LinkSelfContainedDefault, LinkerFlavor, Target}; +use crate::spec::{Cc, LinkSelfContainedDefault, LinkerFlavor, Target, base, crt_objects}; pub(crate) fn target() -> Target { let mut options = base::wasm::options(); @@ -15,19 +15,17 @@ pub(crate) fn target() -> Target { options.os = "wasi".into(); options.env = "p1".into(); - options.add_pre_link_args( - LinkerFlavor::WasmLld(Cc::No), - &["--import-memory", "--export-memory", "--shared-memory"], - ); - options.add_pre_link_args( - LinkerFlavor::WasmLld(Cc::Yes), - &[ - "--target=wasm32-wasip1-threads", - "-Wl,--import-memory", - "-Wl,--export-memory,", - "-Wl,--shared-memory", - ], - ); + options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::No), &[ + "--import-memory", + "--export-memory", + "--shared-memory", + ]); + options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::Yes), &[ + "--target=wasm32-wasip1-threads", + "-Wl,--import-memory", + "-Wl,--export-memory,", + "-Wl,--shared-memory", + ]); options.pre_link_objects_self_contained = crt_objects::pre_wasi_self_contained(); options.post_link_objects_self_contained = crt_objects::post_wasi_self_contained(); diff --git a/compiler/rustc_target/src/spec/targets/wasm32_wasip2.rs b/compiler/rustc_target/src/spec/targets/wasm32_wasip2.rs index 876aa7073f812..bd6bba067efc1 100644 --- a/compiler/rustc_target/src/spec/targets/wasm32_wasip2.rs +++ b/compiler/rustc_target/src/spec/targets/wasm32_wasip2.rs @@ -16,7 +16,7 @@ //! You can see more about wasi at and the component model at //! . -use crate::spec::{base, crt_objects, LinkSelfContainedDefault, RelocModel, Target}; +use crate::spec::{LinkSelfContainedDefault, RelocModel, Target, base, crt_objects}; pub(crate) fn target() -> Target { let mut options = base::wasm::options(); diff --git a/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs b/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs index 35c553744763f..5ba0fca9f64f0 100644 --- a/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs +++ b/compiler/rustc_target/src/spec/targets/wasm64_unknown_unknown.rs @@ -7,30 +7,24 @@ //! the standard library is available, most of it returns an error immediately //! (e.g. trying to create a TCP stream or something like that). -use crate::spec::{base, Cc, LinkerFlavor, Target}; +use crate::spec::{Cc, LinkerFlavor, Target, base}; pub(crate) fn target() -> Target { let mut options = base::wasm::options(); options.os = "unknown".into(); - options.add_pre_link_args( - LinkerFlavor::WasmLld(Cc::No), - &[ - // For now this target just never has an entry symbol no matter the output - // type, so unconditionally pass this. - "--no-entry", - "-mwasm64", - ], - ); - options.add_pre_link_args( - LinkerFlavor::WasmLld(Cc::Yes), - &[ - // Make sure clang uses LLD as its linker and is configured appropriately - // otherwise - "--target=wasm64-unknown-unknown", - "-Wl,--no-entry", - ], - ); + options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::No), &[ + // For now this target just never has an entry symbol no matter the output + // type, so unconditionally pass this. + "--no-entry", + "-mwasm64", + ]); + options.add_pre_link_args(LinkerFlavor::WasmLld(Cc::Yes), &[ + // Make sure clang uses LLD as its linker and is configured appropriately + // otherwise + "--target=wasm64-unknown-unknown", + "-Wl,--no-entry", + ]); // Any engine that implements wasm64 will surely implement the rest of these // features since they were all merged into the official spec by the time diff --git a/compiler/rustc_target/src/spec/targets/x86_64_apple_darwin.rs b/compiler/rustc_target/src/spec/targets/x86_64_apple_darwin.rs index 4304dfc3f682d..52ef3fc88fd7e 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_apple_darwin.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_apple_darwin.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("64-bit macOS (10.12+, Sierra+)".into()), + description: Some("x86_64 Apple macOS (10.12+, Sierra+)".into()), tier: Some(1), host_tools: Some(true), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/x86_64_apple_ios.rs b/compiler/rustc_target/src/spec/targets/x86_64_apple_ios.rs index 847c4f011f9f5..f421e6b8984a5 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_apple_ios.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_apple_ios.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -8,7 +8,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("64-bit x86 iOS".into()), + description: Some("x86_64 Apple iOS Simulator".into()), tier: Some(2), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/x86_64_apple_ios_macabi.rs b/compiler/rustc_target/src/spec/targets/x86_64_apple_ios_macabi.rs index 042079f800b97..3687446b93977 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_apple_ios_macabi.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_apple_ios_macabi.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("Apple Catalyst on x86_64".into()), + description: Some("x86_64 Apple Mac Catalyst".into()), tier: Some(2), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/x86_64_apple_tvos.rs b/compiler/rustc_target/src/spec/targets/x86_64_apple_tvos.rs index 947086097908c..07338a364e81f 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_apple_tvos.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_apple_tvos.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -8,7 +8,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("x86 64-bit tvOS".into()), + description: Some("x86_64 Apple tvOS Simulator".into()), tier: Some(3), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/x86_64_apple_watchos_sim.rs b/compiler/rustc_target/src/spec/targets/x86_64_apple_watchos_sim.rs index 1dab95988601d..4a03c250e6fff 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_apple_watchos_sim.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_apple_watchos_sim.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -6,7 +6,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("x86 64-bit Apple WatchOS simulator".into()), + description: Some("x86_64 Apple watchOS Simulator".into()), tier: Some(3), host_tools: Some(false), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/x86_64_fortanix_unknown_sgx.rs b/compiler/rustc_target/src/spec/targets/x86_64_fortanix_unknown_sgx.rs index a3d18e5ecdaf0..65c3163463093 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_fortanix_unknown_sgx.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_fortanix_unknown_sgx.rs @@ -1,42 +1,39 @@ use std::borrow::Cow; -use crate::spec::{cvs, Cc, LinkerFlavor, Lld, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { - let pre_link_args = TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &[ - "-e", - "elf_entry", - "-Bstatic", - "--gc-sections", - "-z", - "text", - "-z", - "norelro", - "--no-undefined", - "--error-unresolved-symbols", - "--no-undefined-version", - "-Bsymbolic", - "--export-dynamic", - // The following symbols are needed by libunwind, which is linked after - // libstd. Make sure they're included in the link. - "-u", - "__rust_abort", - "-u", - "__rust_c_alloc", - "-u", - "__rust_c_dealloc", - "-u", - "__rust_print_err", - "-u", - "__rust_rwlock_rdlock", - "-u", - "__rust_rwlock_unlock", - "-u", - "__rust_rwlock_wrlock", - ], - ); + let pre_link_args = TargetOptions::link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "-e", + "elf_entry", + "-Bstatic", + "--gc-sections", + "-z", + "text", + "-z", + "norelro", + "--no-undefined", + "--error-unresolved-symbols", + "--no-undefined-version", + "-Bsymbolic", + "--export-dynamic", + // The following symbols are needed by libunwind, which is linked after + // libstd. Make sure they're included in the link. + "-u", + "__rust_abort", + "-u", + "__rust_c_alloc", + "-u", + "__rust_c_dealloc", + "-u", + "__rust_print_err", + "-u", + "__rust_rwlock_rdlock", + "-u", + "__rust_rwlock_unlock", + "-u", + "__rust_rwlock_wrlock", + ]); const EXPORT_SYMBOLS: &[&str] = &[ "sgx_entry", diff --git a/compiler/rustc_target/src/spec/targets/x86_64_fuchsia.rs b/compiler/rustc_target/src/spec/targets/x86_64_fuchsia.rs deleted file mode 100644 index ce3e1e159b7d7..0000000000000 --- a/compiler/rustc_target/src/spec/targets/x86_64_fuchsia.rs +++ /dev/null @@ -1 +0,0 @@ -pub(crate) use crate::spec::targets::x86_64_unknown_fuchsia::target; diff --git a/compiler/rustc_target/src/spec/targets/x86_64_linux_android.rs b/compiler/rustc_target/src/spec/targets/x86_64_linux_android.rs index 84a747e1feb29..d8f74f66f70b6 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_linux_android.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_linux_android.rs @@ -1,5 +1,5 @@ use crate::spec::{ - base, Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, TargetOptions, + Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, TargetOptions, base, }; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_nto_qnx710.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_nto_qnx710.rs index 45963565b06d2..1aa82494a499e 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_pc_nto_qnx710.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_nto_qnx710.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { @@ -17,10 +17,9 @@ pub(crate) fn target() -> Target { cpu: "x86-64".into(), plt_by_default: false, max_atomic_width: Some(64), - pre_link_args: TargetOptions::link_args( - LinkerFlavor::Gnu(Cc::Yes, Lld::No), - &["-Vgcc_ntox86_64_cxx"], - ), + pre_link_args: TargetOptions::link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &[ + "-Vgcc_ntox86_64_cxx", + ]), env: "nto71".into(), ..base::nto_qnx::opts() }, diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_solaris.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_solaris.rs index 37cc7708d6310..28dd3c426c7f7 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_pc_solaris.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_solaris.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, SanitizerSet, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::solaris::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnu.rs index 8efebfd42bba7..e0ffcaf5a72b6 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_gnu::opts(); @@ -6,10 +6,11 @@ pub(crate) fn target() -> Target { base.features = "+cx16,+sse3,+sahf".into(); base.plt_by_default = false; // Use high-entropy 64 bit address space for ASLR - base.add_pre_link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &["-m", "i386pep", "--high-entropy-va"], - ); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "-m", + "i386pep", + "--high-entropy-va", + ]); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64", "-Wl,--high-entropy-va"]); base.max_atomic_width = Some(128); base.linker = Some("x86_64-w64-mingw32-gcc".into()); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnullvm.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnullvm.rs index 056b0451bbebd..46c233f1863dd 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnullvm.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_gnullvm.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_gnullvm::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_msvc.rs index d1881caa27321..baf0d8b0c8b31 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_pc_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, Target}; +use crate::spec::{SanitizerSet, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unikraft_linux_musl.rs b/compiler/rustc_target/src/spec/targets/x86_64_unikraft_linux_musl.rs index 43fac44e48b1f..8aa0128aaa374 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unikraft_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unikraft_linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_dragonfly.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_dragonfly.rs index 7ad0dc69e7bd1..6492d3d7d2f3b 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_dragonfly.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_dragonfly.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::dragonfly::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_freebsd.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_freebsd.rs index 91cc6669f72c5..62cafd502e44e 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_freebsd.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_freebsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::freebsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_fuchsia.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_fuchsia.rs index 836d41a096350..a45f8159de01a 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_fuchsia.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_fuchsia.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, SanitizerSet, StackProbeType, Target}; +use crate::spec::{SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::fuchsia::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_haiku.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_haiku.rs index 7aab43b520aba..b70b38dbbfe7a 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_haiku.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_haiku.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::haiku::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_hermit.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_hermit.rs index 6bc3ec5428648..2e239cafe955d 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_hermit.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_hermit.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, StackProbeType, Target, TargetOptions}; +use crate::spec::{StackProbeType, Target, TargetOptions, base}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_hurd_gnu.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_hurd_gnu.rs index 6461ece5dd141..34835a209568a 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_hurd_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_hurd_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::hurd_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_illumos.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_illumos.rs index 780fd6eb619e3..69715fc257f78 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_illumos.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_illumos.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, SanitizerSet, Target}; +use crate::spec::{Cc, LinkerFlavor, SanitizerSet, Target, base}; pub(crate) fn target() -> Target { let mut base = base::illumos::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_l4re_uclibc.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_l4re_uclibc.rs index f67e9f3b3f11c..db7e402cc806c 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_l4re_uclibc.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_l4re_uclibc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, PanicStrategy, Target}; +use crate::spec::{PanicStrategy, Target, base}; pub(crate) fn target() -> Target { let mut base = base::l4re::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_gnu.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_gnu.rs index 80f49d3a64529..59ec6c7f9d5fb 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_gnux32.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_gnux32.rs index dce23e2ebee0d..8a613477940de 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_gnux32.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_gnux32.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_gnu::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs index 0262c8fd34fdd..8be0f335db9a4 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_musl::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_none.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_none.rs index 47ff0460d7bde..91eb7b53fea8a 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_none.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_none.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_ohos.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_ohos.rs index 28982bc13577d..e455aad5f51ae 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_ohos.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_ohos.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::linux_ohos::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_netbsd.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_netbsd.rs index 1ec07fe5a825e..e49729419573d 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_netbsd.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_netbsd.rs @@ -1,5 +1,5 @@ use crate::spec::{ - base, Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, TargetOptions, + Cc, LinkerFlavor, Lld, SanitizerSet, StackProbeType, Target, TargetOptions, base, }; pub(crate) fn target() -> Target { diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_openbsd.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_openbsd.rs index 580d0ef85309c..3135ecf45dc46 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_openbsd.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_openbsd.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::openbsd::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_redox.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_redox.rs index 5694395151899..43a28fca09ab9 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_redox.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_redox.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::redox::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs index f5ab3afffc32c..a11a79ff41a8e 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_uefi.rs @@ -6,7 +6,7 @@ // LLVM. "x86_64-unknown-windows" is used to get the minimal subset of windows-specific features. use crate::abi::call::Conv; -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { let mut base = base::uefi_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_gnu.rs b/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_gnu.rs index 69c70c96d2b54..fd10bc087efe7 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_gnu.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_gnu.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_uwp_gnu::opts(); @@ -6,10 +6,11 @@ pub(crate) fn target() -> Target { base.features = "+cx16,+sse3,+sahf".into(); base.plt_by_default = false; // Use high-entropy 64 bit address space for ASLR - base.add_pre_link_args( - LinkerFlavor::Gnu(Cc::No, Lld::No), - &["-m", "i386pep", "--high-entropy-va"], - ); + base.add_pre_link_args(LinkerFlavor::Gnu(Cc::No, Lld::No), &[ + "-m", + "i386pep", + "--high-entropy-va", + ]); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64", "-Wl,--high-entropy-va"]); base.max_atomic_width = Some(128); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_msvc.rs index 74493f0941f20..31861c16099dc 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_uwp_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_uwp_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_win7_windows_msvc.rs b/compiler/rustc_target/src/spec/targets/x86_64_win7_windows_msvc.rs index 815016e0adea5..3a3716db350dd 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_win7_windows_msvc.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_win7_windows_msvc.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Target}; +use crate::spec::{Target, base}; pub(crate) fn target() -> Target { let mut base = base::windows_msvc::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64_wrs_vxworks.rs b/compiler/rustc_target/src/spec/targets/x86_64_wrs_vxworks.rs index 604f71ffaa616..8fbdd8f57f658 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_wrs_vxworks.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_wrs_vxworks.rs @@ -1,4 +1,4 @@ -use crate::spec::{base, Cc, LinkerFlavor, Lld, StackProbeType, Target}; +use crate::spec::{Cc, LinkerFlavor, Lld, StackProbeType, Target, base}; pub(crate) fn target() -> Target { let mut base = base::vxworks::opts(); diff --git a/compiler/rustc_target/src/spec/targets/x86_64h_apple_darwin.rs b/compiler/rustc_target/src/spec/targets/x86_64h_apple_darwin.rs index 9fb5a46187a31..0f73a860821ec 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64h_apple_darwin.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64h_apple_darwin.rs @@ -1,4 +1,4 @@ -use crate::spec::base::apple::{base, Arch, TargetAbi}; +use crate::spec::base::apple::{Arch, TargetAbi, base}; use crate::spec::{FramePointer, SanitizerSet, Target, TargetOptions}; pub(crate) fn target() -> Target { @@ -29,7 +29,7 @@ pub(crate) fn target() -> Target { Target { llvm_target, metadata: crate::spec::TargetMetadata { - description: Some("macOS with late-gen Intel (at least Haswell)".into()), + description: Some("x86_64 Apple macOS with Intel Haswell+".into()), tier: Some(3), host_tools: Some(true), std: Some(true), diff --git a/compiler/rustc_target/src/spec/targets/xtensa_esp32_espidf.rs b/compiler/rustc_target/src/spec/targets/xtensa_esp32_espidf.rs index 804659d3c5281..442523aa39717 100644 --- a/compiler/rustc_target/src/spec/targets/xtensa_esp32_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/xtensa_esp32_espidf.rs @@ -1,6 +1,6 @@ use crate::abi::Endian; use crate::spec::base::xtensa; -use crate::spec::{cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_espidf.rs b/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_espidf.rs index 6c15a82e95cd7..353034df6f1b5 100644 --- a/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/xtensa_esp32s2_espidf.rs @@ -1,6 +1,6 @@ use crate::abi::Endian; use crate::spec::base::xtensa; -use crate::spec::{cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_espidf.rs b/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_espidf.rs index 536bd6dc1b2d9..a242f451c342c 100644 --- a/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_espidf.rs +++ b/compiler/rustc_target/src/spec/targets/xtensa_esp32s3_espidf.rs @@ -1,6 +1,6 @@ use crate::abi::Endian; use crate::spec::base::xtensa; -use crate::spec::{cvs, Target, TargetOptions}; +use crate::spec::{Target, TargetOptions, cvs}; pub(crate) fn target() -> Target { Target { diff --git a/compiler/rustc_target/src/target_features.rs b/compiler/rustc_target/src/target_features.rs index 8319cb880cc79..b9e86269d4595 100644 --- a/compiler/rustc_target/src/target_features.rs +++ b/compiler/rustc_target/src/target_features.rs @@ -1,5 +1,5 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_span::symbol::{sym, Symbol}; +use rustc_span::symbol::{Symbol, sym}; /// Features that control behaviour of rustc, rather than the codegen. pub const RUSTC_SPECIFIC_FEATURES: &[&str] = &["crt-static"]; @@ -243,17 +243,13 @@ const AARCH64_ALLOWED_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ ("sve2p1", Unstable(sym::aarch64_unstable_target_feature), &["sve2"]), // FEAT_TME ("tme", Stable, &[]), - ( - "v8.1a", - Unstable(sym::aarch64_ver_target_feature), - &["crc", "lse", "rdm", "pan", "lor", "vh"], - ), + ("v8.1a", Unstable(sym::aarch64_ver_target_feature), &[ + "crc", "lse", "rdm", "pan", "lor", "vh", + ]), ("v8.2a", Unstable(sym::aarch64_ver_target_feature), &["v8.1a", "ras", "dpb"]), - ( - "v8.3a", - Unstable(sym::aarch64_ver_target_feature), - &["v8.2a", "rcpc", "paca", "pacg", "jsconv"], - ), + ("v8.3a", Unstable(sym::aarch64_ver_target_feature), &[ + "v8.2a", "rcpc", "paca", "pacg", "jsconv", + ]), ("v8.4a", Unstable(sym::aarch64_ver_target_feature), &["v8.3a", "dotprod", "dit", "flagm"]), ("v8.5a", Unstable(sym::aarch64_ver_target_feature), &["v8.4a", "ssbs", "sb", "dpb2", "bti"]), ("v8.6a", Unstable(sym::aarch64_ver_target_feature), &["v8.5a", "bf16", "i8mm"]), diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index d486416f22a30..c7b3f704330bd 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -51,7 +51,7 @@ use std::path::PathBuf; use std::{cmp, fmt, iter}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; -use rustc_errors::{pluralize, Applicability, Diag, DiagStyledString, IntoDiagArg, StringPart}; +use rustc_errors::{Applicability, Diag, DiagStyledString, IntoDiagArg, StringPart, pluralize}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; @@ -61,12 +61,12 @@ use rustc_macros::extension; use rustc_middle::bug; use rustc_middle::dep_graph::DepContext; use rustc_middle::ty::error::{ExpectedFound, TypeError, TypeErrorToStringExt}; -use rustc_middle::ty::print::{with_forced_trimmed_paths, PrintError, PrintTraitRefExt as _}; +use rustc_middle::ty::print::{PrintError, PrintTraitRefExt as _, with_forced_trimmed_paths}; use rustc_middle::ty::{ self, List, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, }; -use rustc_span::{sym, BytePos, DesugaringKind, Pos, Span}; +use rustc_span::{BytePos, DesugaringKind, Pos, Span, sym}; use rustc_target::spec::abi; use tracing::{debug, instrument}; @@ -203,8 +203,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn check_and_note_conflicting_crates(&self, err: &mut Diag<'_>, terr: TypeError<'tcx>) { use hir::def_id::CrateNum; use rustc_hir::definitions::DisambiguatedDefPathData; - use ty::print::Printer; use ty::GenericArg; + use ty::print::Printer; struct AbsolutePathPrinter<'tcx> { tcx: TyCtxt<'tcx>, diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index cf9891f15adcf..a6474f10d5b65 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -6,7 +6,7 @@ use rustc_errors::codes::*; use rustc_errors::{Diag, IntoDiagArg}; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Namespace, Res}; -use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{Body, Closure, Expr, ExprKind, FnRetTy, HirId, LetStmt, LocalSource}; use rustc_middle::bug; @@ -17,8 +17,8 @@ use rustc_middle::ty::{ self, GenericArg, GenericArgKind, GenericArgsRef, InferConst, IsSuggestable, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeckResults, }; -use rustc_span::symbol::{sym, Ident}; -use rustc_span::{BytePos, FileName, Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, sym}; +use rustc_span::{BytePos, DUMMY_SP, FileName, Span}; use tracing::{debug, instrument, warn}; use crate::error_reporting::TypeErrCtxt; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/different_lifetimes.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/different_lifetimes.rs index 47e9a3755e89d..7f84725343953 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/different_lifetimes.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/different_lifetimes.rs @@ -2,14 +2,14 @@ //! where both the regions are anonymous. use rustc_errors::{Diag, ErrorGuaranteed, Subdiagnostic}; -use rustc_hir::def_id::LocalDefId; use rustc_hir::Ty; +use rustc_hir::def_id::LocalDefId; use rustc_middle::ty::{Region, TyCtxt}; use tracing::debug; +use crate::error_reporting::infer::nice_region_error::NiceRegionError; use crate::error_reporting::infer::nice_region_error::find_anon_type::find_anon_type; use crate::error_reporting::infer::nice_region_error::util::AnonymousParamInfo; -use crate::error_reporting::infer::nice_region_error::NiceRegionError; use crate::errors::{AddLifetimeParamsSuggestion, LifetimeMismatch, LifetimeMismatchLabels}; use crate::infer::{RegionResolutionError, SubregionOrigin}; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs index 4fe26fa81af00..54d8a9e25ca7f 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mismatched_static_lifetime.rs @@ -11,8 +11,8 @@ use tracing::debug; use crate::error_reporting::infer::nice_region_error::NiceRegionError; use crate::errors::{ - note_and_explain, DoesNotOutliveStaticFromImpl, ImplicitStaticLifetimeSubdiag, - IntroducesStaticBecauseUnmetLifetimeReq, MismatchedStaticLifetime, + DoesNotOutliveStaticFromImpl, ImplicitStaticLifetimeSubdiag, + IntroducesStaticBecauseUnmetLifetimeReq, MismatchedStaticLifetime, note_and_explain, }; use crate::infer::{RegionResolutionError, SubregionOrigin, TypeTrace}; use crate::traits::ObligationCauseCode; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs index 79a770ac9b300..e456ba0eda5c3 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/mod.rs @@ -19,7 +19,7 @@ mod util; pub use different_lifetimes::suggest_adding_lifetime_params; pub use find_anon_type::find_anon_type; -pub use static_impl_trait::{suggest_new_region_bound, HirTraitObjectVisitor, TraitObjectVisitor}; +pub use static_impl_trait::{HirTraitObjectVisitor, TraitObjectVisitor, suggest_new_region_bound}; pub use util::find_param_with_region; impl<'cx, 'tcx> TypeErrCtxt<'cx, 'tcx> { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/named_anon_conflict.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/named_anon_conflict.rs index a7a1fa1c2b454..7cf9818377498 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/named_anon_conflict.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/named_anon_conflict.rs @@ -6,8 +6,8 @@ use rustc_middle::ty; use rustc_span::symbol::kw; use tracing::debug; -use crate::error_reporting::infer::nice_region_error::find_anon_type::find_anon_type; use crate::error_reporting::infer::nice_region_error::NiceRegionError; +use crate::error_reporting::infer::nice_region_error::find_anon_type::find_anon_type; use crate::errors::ExplicitLifetimeRequired; impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs index 2b7927367d8cd..14c2bf19a9cf7 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs @@ -3,7 +3,7 @@ use std::fmt; use rustc_data_structures::intern::Interned; use rustc_errors::{Diag, IntoDiagArg}; use rustc_hir::def::Namespace; -use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; use rustc_middle::bug; use rustc_middle::ty::error::ExpectedFound; use rustc_middle::ty::print::{FmtPrinter, Print, PrintTraitRefExt as _, RegionHighlightMode}; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs index 95ebeab13ef8e..4bde120cba9d0 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/static_impl_trait.rs @@ -3,7 +3,7 @@ use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{Applicability, Diag, ErrorGuaranteed, MultiSpan, Subdiagnostic}; use rustc_hir::def_id::DefId; -use rustc_hir::intravisit::{walk_ty, Visitor}; +use rustc_hir::intravisit::{Visitor, walk_ty}; use rustc_hir::{ self as hir, GenericBound, GenericParam, GenericParamKind, Item, ItemKind, Lifetime, LifetimeName, LifetimeParamKind, MissingLifetimeKind, Node, TyKind, @@ -11,9 +11,9 @@ use rustc_hir::{ use rustc_middle::ty::{ self, AssocItemContainer, StaticLifetimeVisitor, Ty, TyCtxt, TypeSuperVisitable, TypeVisitor, }; +use rustc_span::Span; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::Ident; -use rustc_span::Span; use tracing::debug; use crate::error_reporting::infer::nice_region_error::NiceRegionError; @@ -329,12 +329,9 @@ pub fn suggest_new_region_bound( .params .iter() .filter(|p| { - matches!( - p.kind, - GenericParamKind::Lifetime { - kind: hir::LifetimeParamKind::Explicit - } - ) + matches!(p.kind, GenericParamKind::Lifetime { + kind: hir::LifetimeParamKind::Explicit + }) }) .map(|p| { if let hir::ParamName::Plain(name) = p.name { diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note.rs index e38b8e2f3d6d8..c4dac1a936c7e 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note.rs @@ -7,10 +7,10 @@ use rustc_span::symbol::kw; use tracing::debug; use super::ObligationCauseAsDiagArg; -use crate::error_reporting::infer::{note_and_explain_region, TypeErrCtxt}; +use crate::error_reporting::infer::{TypeErrCtxt, note_and_explain_region}; use crate::errors::{ - note_and_explain, FulfillReqLifetime, LfBoundNotSatisfied, OutlivesBound, OutlivesContent, - RefLongerThanData, RegionOriginNote, WhereClauseSuggestions, + FulfillReqLifetime, LfBoundNotSatisfied, OutlivesBound, OutlivesContent, RefLongerThanData, + RegionOriginNote, WhereClauseSuggestions, note_and_explain, }; use crate::fluent_generated as fluent; use crate::infer::{self, SubregionOrigin}; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index 7bfc6471dc83f..7802d5bf7a6b9 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -1,14 +1,14 @@ use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect}; -use rustc_errors::{pluralize, Diag, MultiSpan}; +use rustc_errors::{Diag, MultiSpan, pluralize}; use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::fast_reject::DeepRejectCtxt; use rustc_middle::ty::print::{FmtPrinter, Printer}; -use rustc_middle::ty::{self, suggest_constraining_type_param, Ty}; +use rustc_middle::ty::{self, Ty, suggest_constraining_type_param}; use rustc_span::def_id::DefId; -use rustc_span::{sym, BytePos, Span, Symbol}; +use rustc_span::{BytePos, Span, Symbol, sym}; use tracing::debug; use crate::error_reporting::TypeErrCtxt; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs index b8ac83e8f9672..41fe8a2bf2266 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/region.rs @@ -2,7 +2,7 @@ use std::iter; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{ - struct_span_code_err, Applicability, Diag, Subdiagnostic, E0309, E0310, E0311, E0495, + Applicability, Diag, E0309, E0310, E0311, E0495, Subdiagnostic, struct_span_code_err, }; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; @@ -17,13 +17,13 @@ use rustc_span::{BytePos, ErrorGuaranteed, Span, Symbol}; use rustc_type_ir::Upcast as _; use tracing::{debug, instrument}; -use super::nice_region_error::find_anon_type; use super::ObligationCauseAsDiagArg; -use crate::error_reporting::infer::ObligationCauseExt; +use super::nice_region_error::find_anon_type; use crate::error_reporting::TypeErrCtxt; +use crate::error_reporting::infer::ObligationCauseExt; use crate::errors::{ - self, note_and_explain, FulfillReqLifetime, LfBoundNotSatisfied, OutlivesBound, - OutlivesContent, RefLongerThanData, RegionOriginNote, WhereClauseSuggestions, + self, FulfillReqLifetime, LfBoundNotSatisfied, OutlivesBound, OutlivesContent, + RefLongerThanData, RegionOriginNote, WhereClauseSuggestions, note_and_explain, }; use crate::fluent_generated as fluent; use crate::infer::region_constraints::GenericKind; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs index 50cbdcc615185..6c3f3afce11b9 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs @@ -1,7 +1,7 @@ use core::ops::ControlFlow; use hir::def::CtorKind; -use hir::intravisit::{walk_expr, walk_stmt, Visitor}; +use hir::intravisit::{Visitor, walk_expr, walk_stmt}; use hir::{LetStmt, QPath}; use rustc_data_structures::fx::FxIndexSet; use rustc_errors::{Applicability, Diag}; @@ -14,11 +14,11 @@ use rustc_middle::traits::{ }; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{self as ty, GenericArgKind, IsSuggestable, Ty, TypeVisitableExt}; -use rustc_span::{sym, Span}; +use rustc_span::{Span, sym}; use tracing::debug; -use crate::error_reporting::infer::hir::Path; use crate::error_reporting::TypeErrCtxt; +use crate::error_reporting::infer::hir::Path; use crate::errors::{ ConsiderAddingAwait, FnConsiderCasting, FnItemsAreDistinct, FnUniqTypes, FunctionPointerSuggestion, SuggestAccessingField, SuggestRemoveSemiOrReturnBinding, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs index 79c1f7222809d..fc0de13aeab09 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs @@ -1,27 +1,27 @@ use std::ops::ControlFlow; use rustc_errors::{ - struct_span_code_err, Applicability, Diag, MultiSpan, StashKey, E0283, E0284, E0790, + Applicability, Diag, E0283, E0284, E0790, MultiSpan, StashKey, struct_span_code_err, }; use rustc_hir as hir; +use rustc_hir::LangItem; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor as _; -use rustc_hir::LangItem; use rustc_infer::infer::{BoundRegionConversionTime, InferCtxt}; use rustc_infer::traits::util::elaborate; use rustc_infer::traits::{ Obligation, ObligationCause, ObligationCauseCode, PolyTraitObligation, PredicateObligation, }; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable as _, TypeVisitableExt as _}; -use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use tracing::{debug, instrument}; -use crate::error_reporting::infer::need_type_info::TypeAnnotationNeeded; -use crate::error_reporting::traits::{to_pretty_impl_header, FindExprBySpan}; use crate::error_reporting::TypeErrCtxt; -use crate::traits::query::evaluate_obligation::InferCtxtExt; +use crate::error_reporting::infer::need_type_info::TypeAnnotationNeeded; +use crate::error_reporting::traits::{FindExprBySpan, to_pretty_impl_header}; use crate::traits::ObligationCtxt; +use crate::traits::query::evaluate_obligation::InferCtxtExt; #[derive(Debug)] pub enum CandidateSource { diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index 1f11ee3f93991..19e2679ae4da7 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -5,29 +5,29 @@ use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::unord::UnordSet; use rustc_errors::codes::*; use rustc_errors::{ - pluralize, struct_span_code_err, Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, - StringPart, Suggestions, + Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey, StringPart, Suggestions, pluralize, + struct_span_code_err, }; use rustc_hir::def::Namespace; -use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::intravisit::Visitor; use rustc_hir::{self as hir, LangItem, Node}; use rustc_infer::infer::{InferOk, TypeTrace}; -use rustc_middle::traits::select::OverflowError; use rustc_middle::traits::SignatureMismatchData; +use rustc_middle::traits::select::OverflowError; use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::fold::{BottomUpFolder, TypeFolder, TypeSuperFoldable}; +use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable}; use rustc_middle::ty::print::{ - with_forced_trimmed_paths, FmtPrinter, Print, PrintTraitPredicateExt as _, - PrintTraitRefExt as _, + FmtPrinter, Print, PrintTraitPredicateExt as _, PrintTraitRefExt as _, + with_forced_trimmed_paths, }; use rustc_middle::ty::{ self, ToPolyTraitRef, TraitRef, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, Upcast, }; use rustc_middle::{bug, span_bug}; use rustc_span::symbol::sym; -use rustc_span::{BytePos, Span, Symbol, DUMMY_SP}; +use rustc_span::{BytePos, DUMMY_SP, Span, Symbol}; use tracing::{debug, instrument}; use super::on_unimplemented::{AppendConstMessage, OnUnimplementedNote}; @@ -35,18 +35,18 @@ use super::suggestions::get_explanation_based_on_obligation; use super::{ ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate, UnsatisfiedConst, }; +use crate::error_reporting::TypeErrCtxt; use crate::error_reporting::infer::TyCategory; use crate::error_reporting::traits::report_object_safety_error; -use crate::error_reporting::TypeErrCtxt; use crate::errors::{ AsyncClosureNotFn, ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, }; use crate::infer::{self, InferCtxt, InferCtxtExt as _}; use crate::traits::query::evaluate_obligation::InferCtxtExt as _; use crate::traits::{ - elaborate, MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, - ObligationCauseCode, ObligationCtxt, Overflow, PredicateObligation, SelectionError, - SignatureMismatch, TraitNotObjectSafe, + MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, ObligationCauseCode, + ObligationCtxt, Overflow, PredicateObligation, SelectionError, SignatureMismatch, + TraitNotObjectSafe, elaborate, }; impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { @@ -1688,16 +1688,13 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { for (sp, label) in spans.into_iter() { span.push_span_label(sp, label); } - err.highlighted_span_help( - span, - vec![ - StringPart::normal("there are ".to_string()), - StringPart::highlighted("multiple different versions".to_string()), - StringPart::normal(" of crate `".to_string()), - StringPart::highlighted(format!("{name}")), - StringPart::normal("` in the dependency graph".to_string()), - ], - ); + err.highlighted_span_help(span, vec![ + StringPart::normal("there are ".to_string()), + StringPart::highlighted("multiple different versions".to_string()), + StringPart::normal(" of crate `".to_string()), + StringPart::highlighted(format!("{name}")), + StringPart::normal("` in the dependency graph".to_string()), + ]); let candidates = if impl_candidates.is_empty() { alternative_candidates(trait_def_id) } else { @@ -1724,17 +1721,14 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { span.push_span_label(self.tcx.def_span(trait_def_id), "this is the required trait"); span.push_span_label(sp_candidate, "this type implements the required trait"); span.push_span_label(sp_found, "this type doesn't implement the required trait"); - err.highlighted_span_note( - span, - vec![ - StringPart::normal( - "two types coming from two different versions of the same crate are \ + err.highlighted_span_note(span, vec![ + StringPart::normal( + "two types coming from two different versions of the same crate are \ different types " - .to_string(), - ), - StringPart::highlighted("even if they look the same".to_string()), - ], - ); + .to_string(), + ), + StringPart::highlighted("even if they look the same".to_string()), + ]); } err.help("you can use `cargo tree` to explore your dependency tree"); return true; @@ -1794,22 +1788,18 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { return false; } - let cand = self.resolve_vars_if_possible(impl_trait_ref).fold_with( - &mut BottomUpFolder { - tcx: self.tcx, - ty_op: |ty| ty, - lt_op: |lt| lt, - ct_op: |ct| ct.normalize(self.tcx, ty::ParamEnv::empty()), - }, - ); - if cand.references_error() { + let impl_trait_ref = self.resolve_vars_if_possible(impl_trait_ref); + if impl_trait_ref.references_error() { return false; } err.highlighted_help(vec![ - StringPart::normal(format!("the trait `{}` ", cand.print_trait_sugared())), + StringPart::normal(format!( + "the trait `{}` ", + impl_trait_ref.print_trait_sugared() + )), StringPart::highlighted("is"), StringPart::normal(" implemented for `"), - StringPart::highlighted(cand.self_ty().to_string()), + StringPart::highlighted(impl_trait_ref.self_ty().to_string()), StringPart::normal("`"), ]); @@ -1921,15 +1911,18 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let mut impl_candidates: Vec<_> = impl_candidates .iter() .cloned() + .filter(|cand| !cand.trait_ref.references_error()) .map(|mut cand| { - // Fold the consts so that they shows up as, e.g., `10` - // instead of `core::::array::{impl#30}::{constant#0}`. - cand.trait_ref = cand.trait_ref.fold_with(&mut BottomUpFolder { - tcx: self.tcx, - ty_op: |ty| ty, - lt_op: |lt| lt, - ct_op: |ct| ct.normalize(self.tcx, ty::ParamEnv::empty()), - }); + // Normalize the trait ref in its *own* param-env so + // that consts are folded and any trivial projections + // are normalized. + cand.trait_ref = self + .tcx + .try_normalize_erasing_regions( + self.tcx.param_env(cand.impl_def_id), + cand.trait_ref, + ) + .unwrap_or(cand.trait_ref); cand }) .collect(); @@ -2742,10 +2735,12 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { .inputs .iter() .map(|arg| match arg.kind { - hir::TyKind::Tup(tys) => ArgKind::Tuple( - Some(arg.span), - vec![("_".to_owned(), "_".to_owned()); tys.len()], - ), + hir::TyKind::Tup(tys) => { + ArgKind::Tuple(Some(arg.span), vec![ + ("_".to_owned(), "_".to_owned()); + tys.len() + ]) + } _ => ArgKind::empty(), }) .collect::>(), diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs index 752ef729113a5..b229499a9f4c0 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs @@ -7,7 +7,7 @@ pub mod suggestions; use std::{fmt, iter}; use rustc_data_structures::fx::{FxIndexMap, FxIndexSet}; -use rustc_errors::{struct_span_code_err, Applicability, Diag, MultiSpan, E0038, E0276}; +use rustc_errors::{Applicability, Diag, E0038, E0276, MultiSpan, struct_span_code_err}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::Visitor; use rustc_hir::{self as hir, LangItem}; @@ -15,7 +15,7 @@ use rustc_infer::traits::{ ObjectSafetyViolation, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation, SelectionError, }; -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, Ty, TyCtxt}; use rustc_span::{ErrorGuaranteed, ExpnKind, Span}; use tracing::{info, instrument}; diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs index 41b0ee56a4cb5..2c7ca50f9549c 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/on_unimplemented.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; use rustc_ast::{AttrArgs, AttrArgsEq, AttrKind, Attribute, MetaItem, NestedMetaItem}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, ErrorGuaranteed}; +use rustc_errors::{ErrorGuaranteed, struct_span_code_err}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_macros::LintDiagnostic; use rustc_middle::bug; @@ -12,8 +12,8 @@ use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{self, GenericArgsRef, GenericParamDefKind, TyCtxt}; use rustc_parse_format::{ParseMode, Parser, Piece, Position}; use rustc_session::lint::builtin::UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES; -use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, kw, sym}; use tracing::{debug, info}; use {rustc_attr as attr, rustc_hir as hir}; diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs index 51fb9f3c6229d..f4c5733d4a6d9 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/overflow.rs @@ -1,7 +1,7 @@ use std::fmt; use rustc_errors::{ - struct_span_code_err, Diag, EmissionGuarantee, ErrorGuaranteed, FatalError, E0275, + Diag, E0275, EmissionGuarantee, ErrorGuaranteed, FatalError, struct_span_code_err, }; use rustc_hir::def::Namespace; use rustc_hir::def_id::LOCAL_CRATE; diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index e2796c764129e..6df7fac949c2f 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -9,8 +9,8 @@ use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::codes::*; use rustc_errors::{ - pluralize, struct_span_code_err, Applicability, Diag, EmissionGuarantee, MultiSpan, Style, - SuggestionStyle, + Applicability, Diag, EmissionGuarantee, MultiSpan, Style, SuggestionStyle, pluralize, + struct_span_code_err, }; use rustc_hir as hir; use rustc_hir::def::{CtorOf, DefKind, Res}; @@ -18,25 +18,25 @@ use rustc_hir::def_id::DefId; use rustc_hir::intravisit::Visitor; use rustc_hir::lang_items::LangItem; use rustc_hir::{ - is_range_literal, CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node, + CoroutineDesugaring, CoroutineKind, CoroutineSource, Expr, HirId, Node, is_range_literal, }; use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferCtxt, InferOk}; use rustc_middle::hir::map; use rustc_middle::traits::IsConstable; use rustc_middle::ty::error::TypeError; use rustc_middle::ty::print::{ - with_forced_trimmed_paths, with_no_trimmed_paths, PrintPolyTraitPredicateExt as _, - PrintPolyTraitRefExt, PrintTraitPredicateExt as _, + PrintPolyTraitPredicateExt as _, PrintPolyTraitRefExt, PrintTraitPredicateExt as _, + with_forced_trimmed_paths, with_no_trimmed_paths, }; use rustc_middle::ty::{ - self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, GenericArgs, - InferTy, IsSuggestable, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder, - TypeSuperFoldable, TypeVisitableExt, TypeckResults, Upcast, + self, AdtKind, GenericArgs, InferTy, IsSuggestable, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable, + TypeFolder, TypeSuperFoldable, TypeVisitableExt, TypeckResults, Upcast, + suggest_arbitrary_trait_bound, suggest_constraining_type_param, }; use rustc_middle::{bug, span_bug}; use rustc_span::def_id::LocalDefId; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{BytePos, DesugaringKind, ExpnKind, MacroKind, Span, DUMMY_SP}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, ExpnKind, MacroKind, Span}; use rustc_target::spec::abi; use tracing::{debug, instrument}; @@ -668,10 +668,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } // Empty suggestions with empty spans ICE with debug assertions if steps == 0 { - return ( - msg.trim_end_matches(" and dereferencing instead"), - vec![(prefix_span, String::new())], - ); + return (msg.trim_end_matches(" and dereferencing instead"), vec![( + prefix_span, + String::new(), + )]); } let derefs = "*".repeat(steps); let needs_parens = steps > 0 @@ -3553,11 +3553,10 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { } ObligationCauseCode::TrivialBound => { err.help("see issue #48214"); - tcx.disabled_nightly_features( - err, - Some(tcx.local_def_id_to_hir_id(body_id)), - [(String::new(), sym::trivial_bounds)], - ); + tcx.disabled_nightly_features(err, Some(tcx.local_def_id_to_hir_id(body_id)), [( + String::new(), + sym::trivial_bounds, + )]); } ObligationCauseCode::OpaqueReturnType(expr_info) => { if let Some((expr_ty, hir_id)) = expr_info { @@ -4621,7 +4620,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { format!("&{}{ty}", mutability.prefix_str()) } } - ty::Array(ty, len) if let Some(len) = len.try_eval_target_usize(tcx, param_env) => { + ty::Array(ty, len) if let Some(len) = len.try_to_target_usize(tcx) => { if len == 0 { "[]".to_string() } else if self.type_is_copy_modulo_regions(param_env, ty) || len == 1 { diff --git a/compiler/rustc_trait_selection/src/errors.rs b/compiler/rustc_trait_selection/src/errors.rs index ebaec0b905936..455e3ec751e63 100644 --- a/compiler/rustc_trait_selection/src/errors.rs +++ b/compiler/rustc_trait_selection/src/errors.rs @@ -8,17 +8,17 @@ use rustc_errors::{ }; use rustc_hir as hir; use rustc_hir::def_id::LocalDefId; -use rustc_hir::intravisit::{walk_ty, Visitor}; +use rustc_hir::intravisit::{Visitor, walk_ty}; use rustc_hir::{FnRetTy, GenericParamKind}; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_middle::ty::print::{PrintTraitRefExt as _, TraitRefPrintOnlyTraitPath}; use rustc_middle::ty::{self, Binder, ClosureKind, FnSig, PolyTraitRef, Region, Ty, TyCtxt}; -use rustc_span::symbol::{kw, Ident, Symbol}; +use rustc_span::symbol::{Ident, Symbol, kw}; use rustc_span::{BytePos, Span}; +use crate::error_reporting::infer::ObligationCauseAsDiagArg; use crate::error_reporting::infer::need_type_info::UnderspecifiedArgKind; use crate::error_reporting::infer::nice_region_error::placeholder_error::Highlighted; -use crate::error_reporting::infer::ObligationCauseAsDiagArg; use crate::fluent_generated as fluent; pub mod note_and_explain; diff --git a/compiler/rustc_trait_selection/src/errors/note_and_explain.rs b/compiler/rustc_trait_selection/src/errors/note_and_explain.rs index b14777630283f..67463b9884c84 100644 --- a/compiler/rustc_trait_selection/src/errors/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/errors/note_and_explain.rs @@ -2,8 +2,8 @@ use rustc_errors::{Diag, EmissionGuarantee, IntoDiagArg, SubdiagMessageOp, Subdi use rustc_hir::def_id::LocalDefId; use rustc_middle::bug; use rustc_middle::ty::{self, TyCtxt}; -use rustc_span::symbol::kw; use rustc_span::Span; +use rustc_span::symbol::kw; use crate::error_reporting::infer::nice_region_error::find_anon_type; use crate::fluent_generated as fluent; diff --git a/compiler/rustc_trait_selection/src/regions.rs b/compiler/rustc_trait_selection/src/regions.rs index 65762cfcd2ebf..863b6e293ff89 100644 --- a/compiler/rustc_trait_selection/src/regions.rs +++ b/compiler/rustc_trait_selection/src/regions.rs @@ -1,8 +1,8 @@ use rustc_infer::infer::outlives::env::OutlivesEnvironment; use rustc_infer::infer::{InferCtxt, RegionResolutionError}; use rustc_macros::extension; -use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; +use rustc_middle::traits::query::NoSolution; use crate::traits::ScrubbedTraitError; diff --git a/compiler/rustc_trait_selection/src/solve/delegate.rs b/compiler/rustc_trait_selection/src/solve/delegate.rs index a7b0719d8d4ae..5c344930314a6 100644 --- a/compiler/rustc_trait_selection/src/solve/delegate.rs +++ b/compiler/rustc_trait_selection/src/solve/delegate.rs @@ -11,7 +11,7 @@ use rustc_infer::traits::solve::Goal; use rustc_infer::traits::{ObligationCause, Reveal}; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt as _}; -use rustc_span::{ErrorGuaranteed, Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span}; use rustc_type_ir::solve::{Certainty, NoSolution, SolverMode}; use tracing::trace; @@ -182,10 +182,10 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate< } fn inject_new_hidden_type_unchecked(&self, key: ty::OpaqueTypeKey<'tcx>, hidden_ty: Ty<'tcx>) { - self.0.inject_new_hidden_type_unchecked( - key, - ty::OpaqueHiddenType { ty: hidden_ty, span: DUMMY_SP }, - ) + self.0.inject_new_hidden_type_unchecked(key, ty::OpaqueHiddenType { + ty: hidden_ty, + span: DUMMY_SP, + }) } fn reset_opaque_types(&self) { diff --git a/compiler/rustc_trait_selection/src/solve/fulfill.rs b/compiler/rustc_trait_selection/src/solve/fulfill.rs index cfc73e2e47e87..fc15f5b5906f6 100644 --- a/compiler/rustc_trait_selection/src/solve/fulfill.rs +++ b/compiler/rustc_trait_selection/src/solve/fulfill.rs @@ -15,9 +15,9 @@ use rustc_middle::ty::{self, TyCtxt}; use rustc_next_trait_solver::solve::{GenerateProofTree, SolverDelegateEvalExt as _}; use tracing::instrument; +use super::Certainty; use super::delegate::SolverDelegate; use super::inspect::{self, ProofTreeInferCtxtExt, ProofTreeVisitor}; -use super::Certainty; use crate::traits::{FulfillmentError, FulfillmentErrorCode, ScrubbedTraitError}; /// A trait engine using the new trait solver. @@ -347,10 +347,10 @@ fn find_best_leaf_obligation<'tcx>( ) -> PredicateObligation<'tcx> { let obligation = infcx.resolve_vars_if_possible(obligation.clone()); infcx - .visit_proof_tree( - obligation.clone().into(), - &mut BestObligation { obligation: obligation.clone(), consider_ambiguities }, - ) + .visit_proof_tree(obligation.clone().into(), &mut BestObligation { + obligation: obligation.clone(), + consider_ambiguities, + }) .break_value() .unwrap_or(obligation) } diff --git a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs index 49c37a684b572..254620e0b597f 100644 --- a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs +++ b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs @@ -15,14 +15,14 @@ use rustc_ast_ir::try_visit; use rustc_ast_ir::visit::VisitorResult; use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, InferOk}; use rustc_macros::extension; -use rustc_middle::traits::solve::{Certainty, Goal, GoalSource, NoSolution, QueryResult}; use rustc_middle::traits::ObligationCause; +use rustc_middle::traits::solve::{Certainty, Goal, GoalSource, NoSolution, QueryResult}; use rustc_middle::ty::{TyCtxt, TypeFoldable}; use rustc_middle::{bug, ty}; use rustc_next_trait_solver::resolve::EagerResolver; use rustc_next_trait_solver::solve::inspect::{self, instantiate_canonical_state}; use rustc_next_trait_solver::solve::{GenerateProofTree, MaybeCause, SolverDelegateEvalExt as _}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::instrument; use crate::solve::delegate::SolverDelegate; diff --git a/compiler/rustc_trait_selection/src/solve/normalize.rs b/compiler/rustc_trait_selection/src/solve/normalize.rs index 938ba2dde8491..a724705ffe912 100644 --- a/compiler/rustc_trait_selection/src/solve/normalize.rs +++ b/compiler/rustc_trait_selection/src/solve/normalize.rs @@ -3,8 +3,8 @@ use std::fmt::Debug; use std::marker::PhantomData; use rustc_data_structures::stack::ensure_sufficient_stack; -use rustc_infer::infer::at::At; use rustc_infer::infer::InferCtxt; +use rustc_infer::infer::at::At; use rustc_infer::traits::{FromSolverError, Obligation, TraitEngine}; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::{ @@ -14,8 +14,8 @@ use rustc_middle::ty::{ use tracing::instrument; use super::{FulfillmentCtxt, NextSolverError}; -use crate::error_reporting::traits::OverflowCause; use crate::error_reporting::InferCtxtErrorExt; +use crate::error_reporting::traits::OverflowCause; use crate::traits::query::evaluate_obligation::InferCtxtExt; use crate::traits::{BoundVarReplacer, PlaceholderReplacer, ScrubbedTraitError}; @@ -130,12 +130,11 @@ where self.depth += 1; let new_infer_ct = infcx.next_const_var(self.at.cause.span); - let obligation = Obligation::new( - tcx, - self.at.cause.clone(), - self.at.param_env, - ty::NormalizesTo { alias: uv.into(), term: new_infer_ct.into() }, - ); + let obligation = + Obligation::new(tcx, self.at.cause.clone(), self.at.param_env, ty::NormalizesTo { + alias: uv.into(), + term: new_infer_ct.into(), + }); let result = if infcx.predicate_may_hold(&obligation) { self.fulfill_cx.register_predicate_obligation(infcx, obligation); @@ -253,20 +252,20 @@ impl<'tcx> TypeFolder> for DeeplyNormalizeForDiagnosticsFolder<'_, } fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { - deeply_normalize_with_skipped_universes( - self.at, - ty, - vec![None; ty.outer_exclusive_binder().as_usize()], - ) + deeply_normalize_with_skipped_universes(self.at, ty, vec![ + None; + ty.outer_exclusive_binder() + .as_usize() + ]) .unwrap_or_else(|_: Vec>| ty.super_fold_with(self)) } fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> { - deeply_normalize_with_skipped_universes( - self.at, - ct, - vec![None; ct.outer_exclusive_binder().as_usize()], - ) + deeply_normalize_with_skipped_universes(self.at, ct, vec![ + None; + ct.outer_exclusive_binder() + .as_usize() + ]) .unwrap_or_else(|_: Vec>| ct.super_fold_with(self)) } } diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index bafe1ffae44d3..27d2a3c15b9ac 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -20,20 +20,20 @@ use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableEx use rustc_middle::ty::{self, Ty, TyCtxt}; pub use rustc_next_trait_solver::coherence::*; use rustc_span::symbol::sym; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument, warn}; use super::ObligationCtxt; use crate::error_reporting::traits::suggest_new_overflow_limit; -use crate::infer::outlives::env::OutlivesEnvironment; use crate::infer::InferOk; +use crate::infer::outlives::env::OutlivesEnvironment; use crate::solve::inspect::{InspectGoal, ProofTreeInferCtxtExt, ProofTreeVisitor}; use crate::solve::{deeply_normalize_for_diagnostics, inspect}; use crate::traits::query::evaluate_obligation::InferCtxtExt; use crate::traits::select::IntercrateAmbiguityCause; use crate::traits::{ - util, FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation, - SelectionContext, SkipLeakCheck, + FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation, + SelectionContext, SkipLeakCheck, util, }; pub struct OverlapResult<'tcx> { @@ -346,10 +346,9 @@ fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>( overflowing_predicates: ambiguities .into_iter() .filter(|error| { - matches!( - error.code, - FulfillmentErrorCode::Ambiguity { overflow: Some(true) } - ) + matches!(error.code, FulfillmentErrorCode::Ambiguity { + overflow: Some(true) + }) }) .map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate)) .collect(), @@ -470,16 +469,13 @@ fn plug_infer_with_placeholders<'tcx>( // Comparing against a type variable never registers hidden types anyway DefineOpaqueTypes::Yes, ty, - Ty::new_placeholder( - self.infcx.tcx, - ty::Placeholder { - universe: self.universe, - bound: ty::BoundTy { - var: self.next_var(), - kind: ty::BoundTyKind::Anon, - }, + Ty::new_placeholder(self.infcx.tcx, ty::Placeholder { + universe: self.universe, + bound: ty::BoundTy { + var: self.next_var(), + kind: ty::BoundTyKind::Anon, }, - ), + }), ) else { bug!("we always expect to be able to plug an infer var with placeholder") @@ -499,10 +495,10 @@ fn plug_infer_with_placeholders<'tcx>( // registration happening anyway. DefineOpaqueTypes::Yes, ct, - ty::Const::new_placeholder( - self.infcx.tcx, - ty::Placeholder { universe: self.universe, bound: self.next_var() }, - ), + ty::Const::new_placeholder(self.infcx.tcx, ty::Placeholder { + universe: self.universe, + bound: self.next_var(), + }), ) else { bug!("we always expect to be able to plug an infer var with placeholder") @@ -527,16 +523,13 @@ fn plug_infer_with_placeholders<'tcx>( // Lifetimes don't contain opaque types (or any types for that matter). DefineOpaqueTypes::Yes, r, - ty::Region::new_placeholder( - self.infcx.tcx, - ty::Placeholder { - universe: self.universe, - bound: ty::BoundRegion { - var: self.next_var(), - kind: ty::BoundRegionKind::BrAnon, - }, + ty::Region::new_placeholder(self.infcx.tcx, ty::Placeholder { + universe: self.universe, + bound: ty::BoundRegion { + var: self.next_var(), + kind: ty::BoundRegionKind::BrAnon, }, - ), + }), ) else { bug!("we always expect to be able to plug an infer var with placeholder") diff --git a/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs b/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs index 4289384725f70..c258832bf2bef 100644 --- a/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs +++ b/compiler/rustc_trait_selection/src/traits/const_evaluatable.rs @@ -16,7 +16,7 @@ use rustc_middle::mir::interpret::ErrorHandled; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::{self, TyCtxt, TypeVisitable, TypeVisitableExt, TypeVisitor}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; use crate::traits::ObligationCtxt; diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index 16ba06f8667ff..fcd0936c055c5 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -18,8 +18,8 @@ use tracing::{debug, debug_span, instrument}; use super::project::{self, ProjectAndUnifyResult}; use super::select::SelectionContext; use super::{ - const_evaluatable, wf, EvaluationResult, FulfillmentError, FulfillmentErrorCode, - PredicateObligation, ScrubbedTraitError, Unimplemented, + EvaluationResult, FulfillmentError, FulfillmentErrorCode, PredicateObligation, + ScrubbedTraitError, Unimplemented, const_evaluatable, wf, }; use crate::error_reporting::InferCtxtErrorExt; use crate::infer::{InferCtxt, TyOrConstInferVar}; diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 538e23f444957..61592d4778475 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -35,20 +35,20 @@ use rustc_middle::ty::visit::{TypeVisitable, TypeVisitableExt}; use rustc_middle::ty::{ self, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFolder, TypeSuperVisitable, Upcast, }; -use rustc_span::def_id::DefId; use rustc_span::Span; +use rustc_span::def_id::DefId; use tracing::{debug, instrument}; pub use self::coherence::{ - add_placeholder_note, orphan_check_trait_ref, overlapping_impls, InCrate, IsFirstInputType, - OrphanCheckErr, OrphanCheckMode, OverlapResult, UncoveredTyParams, + InCrate, IsFirstInputType, OrphanCheckErr, OrphanCheckMode, OverlapResult, UncoveredTyParams, + add_placeholder_note, orphan_check_trait_ref, overlapping_impls, }; pub use self::engine::{ObligationCtxt, TraitEngineExt}; pub use self::fulfill::{FulfillmentContext, OldSolverError, PendingPredicateObligation}; pub use self::normalize::NormalizeExt; pub use self::object_safety::{ - hir_ty_lowering_object_safety_violations, is_vtable_safe_method, - object_safety_violations_for_assoc_item, ObjectSafetyViolation, + ObjectSafetyViolation, hir_ty_lowering_object_safety_violations, is_vtable_safe_method, + object_safety_violations_for_assoc_item, }; pub use self::project::{normalize_inherent_projection, normalize_projection_ty}; pub use self::select::{ @@ -59,13 +59,13 @@ pub use self::specialize::specialization_graph::{ FutureCompatOverlapError, FutureCompatOverlapErrorKind, }; pub use self::specialize::{ - specialization_graph, translate_args, translate_args_with_cause, OverlapError, + OverlapError, specialization_graph, translate_args, translate_args_with_cause, }; pub use self::structural_normalize::StructurallyNormalizeExt; pub use self::util::{ - elaborate, expand_trait_aliases, impl_item_is_final, supertraits, + BoundVarReplacer, PlaceholderReplacer, TraitAliasExpander, TraitAliasExpansionInfo, elaborate, + expand_trait_aliases, impl_item_is_final, supertraits, transitive_bounds_that_define_assoc_item, upcast_choices, with_replaced_escaping_bound_vars, - BoundVarReplacer, PlaceholderReplacer, TraitAliasExpander, TraitAliasExpansionInfo, }; use crate::error_reporting::InferCtxtErrorExt; use crate::infer::outlives::env::OutlivesEnvironment; diff --git a/compiler/rustc_trait_selection/src/traits/normalize.rs b/compiler/rustc_trait_selection/src/traits/normalize.rs index aad47df73696f..a7130cbd28f29 100644 --- a/compiler/rustc_trait_selection/src/traits/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/normalize.rs @@ -1,8 +1,8 @@ //! Deeply normalize types using the old trait solver. use rustc_data_structures::stack::ensure_sufficient_stack; -use rustc_infer::infer::at::At; use rustc_infer::infer::InferOk; +use rustc_infer::infer::at::At; use rustc_infer::traits::{ FromSolverError, Normalized, Obligation, PredicateObligation, TraitEngine, }; @@ -14,11 +14,11 @@ use rustc_middle::ty::{ use tracing::{debug, instrument}; use super::{ - project, with_replaced_escaping_bound_vars, BoundVarReplacer, PlaceholderReplacer, - SelectionContext, + BoundVarReplacer, PlaceholderReplacer, SelectionContext, project, + with_replaced_escaping_bound_vars, }; -use crate::error_reporting::traits::OverflowCause; use crate::error_reporting::InferCtxtErrorExt; +use crate::error_reporting::traits::OverflowCause; use crate::solve::NextSolverError; #[extension(pub trait NormalizeExt<'tcx>)] diff --git a/compiler/rustc_trait_selection/src/traits/object_safety.rs b/compiler/rustc_trait_selection/src/traits/object_safety.rs index a3d5c5307974d..b6169f8508d59 100644 --- a/compiler/rustc_trait_selection/src/traits/object_safety.rs +++ b/compiler/rustc_trait_selection/src/traits/object_safety.rs @@ -20,17 +20,17 @@ use rustc_middle::ty::{ TypeFoldable, TypeFolder, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, Upcast, }; -use rustc_span::symbol::Symbol; use rustc_span::Span; +use rustc_span::symbol::Symbol; use rustc_target::abi::Abi; use smallvec::SmallVec; use tracing::{debug, instrument}; use super::elaborate; use crate::infer::TyCtxtInferExt; -use crate::traits::query::evaluate_obligation::InferCtxtExt; pub use crate::traits::ObjectSafetyViolation; -use crate::traits::{util, MethodViolationCode, Obligation, ObligationCause}; +use crate::traits::query::evaluate_obligation::InferCtxtExt; +use crate::traits::{MethodViolationCode, Obligation, ObligationCause, util}; /// Returns the object safety violations that affect HIR ty lowering. /// diff --git a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs index ee1b0fc6f2e5e..f1faff2c036f7 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_bounds.rs @@ -1,6 +1,6 @@ use rustc_data_structures::fx::FxIndexSet; -use rustc_infer::infer::resolve::OpportunisticRegionResolver; use rustc_infer::infer::InferOk; +use rustc_infer::infer::resolve::OpportunisticRegionResolver; use rustc_macros::extension; use rustc_middle::infer::canonical::{OriginalQueryValues, QueryRegionConstraints}; use rustc_middle::span_bug; diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index c27a9285b3abe..9cd99d99fc3c3 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -7,11 +7,11 @@ use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::ErrorGuaranteed; use rustc_hir::def::DefKind; use rustc_hir::lang_items::LangItem; -use rustc_infer::infer::resolve::OpportunisticRegionResolver; use rustc_infer::infer::DefineOpaqueTypes; +use rustc_infer::infer::resolve::OpportunisticRegionResolver; use rustc_infer::traits::ObligationCauseCode; -use rustc_middle::traits::select::OverflowError; pub use rustc_middle::traits::Reveal; +use rustc_middle::traits::select::OverflowError; use rustc_middle::traits::{BuiltinImplSource, ImplSource, ImplSourceUserDefinedData}; use rustc_middle::ty::fast_reject::DeepRejectCtxt; use rustc_middle::ty::fold::TypeFoldable; @@ -22,9 +22,9 @@ use rustc_span::symbol::sym; use tracing::{debug, instrument}; use super::{ - specialization_graph, translate_args, util, MismatchedProjectionTypes, Normalized, - NormalizedTerm, Obligation, ObligationCause, PredicateObligation, ProjectionCacheEntry, - ProjectionCacheKey, Selection, SelectionContext, SelectionError, + MismatchedProjectionTypes, Normalized, NormalizedTerm, Obligation, ObligationCause, + PredicateObligation, ProjectionCacheEntry, ProjectionCacheKey, Selection, SelectionContext, + SelectionError, specialization_graph, translate_args, util, }; use crate::errors::InherentProjectionNormalizationOverflow; use crate::infer::{BoundRegionConversionTime, InferOk}; @@ -1696,18 +1696,14 @@ fn confirm_closure_candidate<'cx, 'tcx>( } else { let upvars_projection_def_id = tcx.require_lang_item(LangItem::AsyncFnKindUpvars, None); - let tupled_upvars_ty = Ty::new_projection( - tcx, - upvars_projection_def_id, - [ - ty::GenericArg::from(kind_ty), - Ty::from_closure_kind(tcx, ty::ClosureKind::FnOnce).into(), - tcx.lifetimes.re_static.into(), - sig.tupled_inputs_ty.into(), - args.tupled_upvars_ty().into(), - args.coroutine_captures_by_ref_ty().into(), - ], - ); + let tupled_upvars_ty = Ty::new_projection(tcx, upvars_projection_def_id, [ + ty::GenericArg::from(kind_ty), + Ty::from_closure_kind(tcx, ty::ClosureKind::FnOnce).into(), + tcx.lifetimes.re_static.into(), + sig.tupled_inputs_ty.into(), + args.tupled_upvars_ty().into(), + args.coroutine_captures_by_ref_ty().into(), + ]); sig.to_coroutine( tcx, args.parent_args(), @@ -1834,18 +1830,14 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( // will project to the right upvars for the generator, appending the inputs and // coroutine upvars respecting the closure kind. // N.B. No need to register a `AsyncFnKindHelper` goal here, it's already in `nested`. - let tupled_upvars_ty = Ty::new_projection( - tcx, - upvars_projection_def_id, - [ - ty::GenericArg::from(kind_ty), - Ty::from_closure_kind(tcx, goal_kind).into(), - env_region.into(), - sig.tupled_inputs_ty.into(), - args.tupled_upvars_ty().into(), - args.coroutine_captures_by_ref_ty().into(), - ], - ); + let tupled_upvars_ty = Ty::new_projection(tcx, upvars_projection_def_id, [ + ty::GenericArg::from(kind_ty), + Ty::from_closure_kind(tcx, goal_kind).into(), + env_region.into(), + sig.tupled_inputs_ty.into(), + args.tupled_upvars_ty().into(), + args.coroutine_captures_by_ref_ty().into(), + ]); sig.to_coroutine( tcx, args.parent_args(), @@ -1859,16 +1851,17 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( name => bug!("no such associated type: {name}"), }; let projection_term = match item_name { - sym::CallOnceFuture | sym::Output => ty::AliasTerm::new( - tcx, - obligation.predicate.def_id, - [self_ty, sig.tupled_inputs_ty], - ), - sym::CallRefFuture => ty::AliasTerm::new( - tcx, - obligation.predicate.def_id, - [ty::GenericArg::from(self_ty), sig.tupled_inputs_ty.into(), env_region.into()], - ), + sym::CallOnceFuture | sym::Output => { + ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ + self_ty, + sig.tupled_inputs_ty, + ]) + } + sym::CallRefFuture => ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ + ty::GenericArg::from(self_ty), + sig.tupled_inputs_ty.into(), + env_region.into(), + ]), name => bug!("no such associated type: {name}"), }; @@ -1888,20 +1881,17 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( name => bug!("no such associated type: {name}"), }; let projection_term = match item_name { - sym::CallOnceFuture | sym::Output => ty::AliasTerm::new( - tcx, - obligation.predicate.def_id, - [self_ty, Ty::new_tup(tcx, sig.inputs())], - ), - sym::CallRefFuture => ty::AliasTerm::new( - tcx, - obligation.predicate.def_id, - [ - ty::GenericArg::from(self_ty), - Ty::new_tup(tcx, sig.inputs()).into(), - env_region.into(), - ], - ), + sym::CallOnceFuture | sym::Output => { + ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ + self_ty, + Ty::new_tup(tcx, sig.inputs()), + ]) + } + sym::CallRefFuture => ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ + ty::GenericArg::from(self_ty), + Ty::new_tup(tcx, sig.inputs()).into(), + env_region.into(), + ]), name => bug!("no such associated type: {name}"), }; @@ -1924,11 +1914,11 @@ fn confirm_async_closure_candidate<'cx, 'tcx>( sym::CallOnceFuture | sym::Output => { ty::AliasTerm::new(tcx, obligation.predicate.def_id, [self_ty, sig.inputs()[0]]) } - sym::CallRefFuture => ty::AliasTerm::new( - tcx, - obligation.predicate.def_id, - [ty::GenericArg::from(self_ty), sig.inputs()[0].into(), env_region.into()], - ), + sym::CallRefFuture => ty::AliasTerm::new(tcx, obligation.predicate.def_id, [ + ty::GenericArg::from(self_ty), + sig.inputs()[0].into(), + env_region.into(), + ]), name => bug!("no such associated type: {name}"), }; diff --git a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs index 7036df0246597..c70fe13fc69a2 100644 --- a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs @@ -1,11 +1,11 @@ use rustc_data_structures::fx::FxHashSet; use rustc_middle::traits::query::{DropckConstraint, DropckOutlivesResult}; use rustc_middle::ty::{self, EarlyBinder, ParamEnvAnd, Ty, TyCtxt}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; -use crate::traits::query::normalize::QueryNormalizeExt; use crate::traits::query::NoSolution; +use crate::traits::query::normalize::QueryNormalizeExt; use crate::traits::{Normalized, ObligationCause, ObligationCtxt}; /// This returns true if the type `ty` is "trivial" for diff --git a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs index 692feee739511..76017299f2c08 100644 --- a/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs +++ b/compiler/rustc_trait_selection/src/traits/query/evaluate_obligation.rs @@ -1,8 +1,8 @@ use rustc_macros::extension; use rustc_middle::span_bug; -use crate::infer::canonical::OriginalQueryValues; use crate::infer::InferCtxt; +use crate::infer::canonical::OriginalQueryValues; use crate::traits::{ EvaluationResult, ObligationCtxt, OverflowError, PredicateObligation, SelectionContext, }; diff --git a/compiler/rustc_trait_selection/src/traits/query/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/normalize.rs index 525fba69a87c6..36b24eac5c435 100644 --- a/compiler/rustc_trait_selection/src/traits/query/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/normalize.rs @@ -13,8 +13,8 @@ use rustc_span::DUMMY_SP; use tracing::{debug, info, instrument}; use super::NoSolution; -use crate::error_reporting::traits::OverflowCause; use crate::error_reporting::InferCtxtErrorExt; +use crate::error_reporting::traits::OverflowCause; use crate::infer::at::At; use crate::infer::canonical::OriginalQueryValues; use crate::infer::{InferCtxt, InferOk}; diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs index 2b3c11d4c48aa..c84c3147a3842 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/ascribe_user_type.rs @@ -1,10 +1,10 @@ -use rustc_hir::def_id::{DefId, CRATE_DEF_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; use rustc_infer::traits::Obligation; -pub use rustc_middle::traits::query::type_op::AscribeUserType; use rustc_middle::traits::query::NoSolution; +pub use rustc_middle::traits::query::type_op::AscribeUserType; use rustc_middle::traits::{ObligationCause, ObligationCauseCode}; use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, UserArgs, UserSelfTy, UserType}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument}; use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs index 6efc2d07843ee..18010603286d1 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/custom.rs @@ -7,10 +7,10 @@ use rustc_middle::ty::{TyCtxt, TypeFoldable}; use rustc_span::Span; use tracing::info; -use crate::infer::canonical::query_response; use crate::infer::InferCtxt; -use crate::traits::query::type_op::TypeOpOutput; +use crate::infer::canonical::query_response; use crate::traits::ObligationCtxt; +use crate::traits::query::type_op::TypeOpOutput; pub struct CustomTypeOp { closure: F, diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs index a493615a1dfbc..3d9dc1a8d4d50 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/implied_outlives_bounds.rs @@ -5,14 +5,14 @@ use rustc_macros::{HashStable, TypeFoldable, TypeVisitable}; use rustc_middle::infer::canonical::CanonicalQueryResponse; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::{self, ParamEnvAnd, Ty, TyCtxt, TypeFolder, TypeVisitableExt}; -use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::DUMMY_SP; -use rustc_type_ir::outlives::{push_outlives_components, Component}; -use smallvec::{smallvec, SmallVec}; +use rustc_span::def_id::CRATE_DEF_ID; +use rustc_type_ir::outlives::{Component, push_outlives_components}; +use smallvec::{SmallVec, smallvec}; use tracing::debug; use crate::traits::query::NoSolution; -use crate::traits::{wf, ObligationCtxt}; +use crate::traits::{ObligationCtxt, wf}; #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable)] pub struct ImpliedOutlivesBounds<'tcx> { diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs index 41c34f6da2955..62d5655922b09 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/normalize.rs @@ -1,8 +1,8 @@ use std::fmt; -pub use rustc_middle::traits::query::type_op::Normalize; -use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; +use rustc_middle::traits::query::NoSolution; +pub use rustc_middle::traits::query::type_op::Normalize; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::{self, Lift, ParamEnvAnd, Ty, TyCtxt, TypeVisitableExt}; diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs index 49d324fa62ecd..d891d4ca06f9d 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/outlives.rs @@ -3,10 +3,10 @@ use rustc_middle::traits::query::{DropckOutlivesResult, NoSolution}; use rustc_middle::ty::{ParamEnvAnd, Ty, TyCtxt}; use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; +use crate::traits::ObligationCtxt; use crate::traits::query::dropck_outlives::{ compute_dropck_outlives_inner, trivial_dropck_outlives, }; -use crate::traits::ObligationCtxt; #[derive(Copy, Clone, Debug, HashStable, TypeFoldable, TypeVisitable)] pub struct DropckOutlives<'tcx> { diff --git a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs index d6687c762c311..7cdb9ee691e4b 100644 --- a/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs +++ b/compiler/rustc_trait_selection/src/traits/query/type_op/prove_predicate.rs @@ -1,8 +1,8 @@ use rustc_hir::LangItem; use rustc_infer::traits::Obligation; -pub use rustc_middle::traits::query::type_op::ProvePredicate; -use rustc_middle::traits::query::NoSolution; use rustc_middle::traits::ObligationCause; +use rustc_middle::traits::query::NoSolution; +pub use rustc_middle::traits::query::type_op::ProvePredicate; use rustc_middle::ty::{self, ParamEnvAnd, TyCtxt}; use crate::infer::canonical::{Canonical, CanonicalQueryResponse}; diff --git a/compiler/rustc_trait_selection/src/traits/select/_match.rs b/compiler/rustc_trait_selection/src/traits/select/_match.rs index f77f83ed4471c..3980d672a11bc 100644 --- a/compiler/rustc_trait_selection/src/traits/select/_match.rs +++ b/compiler/rustc_trait_selection/src/traits/select/_match.rs @@ -1,5 +1,5 @@ use rustc_infer::infer::relate::{ - self, structurally_relate_tys, Relate, RelateResult, TypeRelation, + self, Relate, RelateResult, TypeRelation, structurally_relate_tys, }; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{self, InferConst, Ty, TyCtxt}; diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 3e3589538c710..e5f1d5c36daf6 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -8,8 +8,8 @@ use std::ops::ControlFlow; -use hir::def_id::DefId; use hir::LangItem; +use hir::def_id::DefId; use rustc_data_structures::fx::{FxHashSet, FxIndexSet}; use rustc_hir as hir; use rustc_infer::traits::{Obligation, ObligationCause, PolyTraitObligation, SelectionError}; diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index daf0700ec0cd5..d15acd51c86e3 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -305,15 +305,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let make_transmute_obl = |src, dst| { let transmute_trait = obligation.predicate.def_id(); let assume = obligation.predicate.skip_binder().trait_ref.args.const_at(2); - let trait_ref = ty::TraitRef::new( - tcx, - transmute_trait, - [ - ty::GenericArg::from(dst), - ty::GenericArg::from(src), - ty::GenericArg::from(assume), - ], - ); + let trait_ref = ty::TraitRef::new(tcx, transmute_trait, [ + ty::GenericArg::from(dst), + ty::GenericArg::from(src), + ty::GenericArg::from(assume), + ]); Obligation::with_depth( tcx, obligation.cause.clone(), @@ -324,11 +320,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }; let make_freeze_obl = |ty| { - let trait_ref = ty::TraitRef::new( - tcx, - tcx.require_lang_item(LangItem::Freeze, None), - [ty::GenericArg::from(ty)], - ); + let trait_ref = + ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Freeze, None), [ + ty::GenericArg::from(ty), + ]); Obligation::with_depth( tcx, obligation.cause.clone(), @@ -657,28 +652,20 @@ impl<'cx, 'tcx> SelectionContext<'cx, '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 { .. } => { @@ -921,11 +908,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ), ty::CoroutineClosure(_, args) => { args.as_coroutine_closure().coroutine_closure_sig().map_bound(|sig| { - ty::TraitRef::new( - self.tcx(), - obligation.predicate.def_id(), - [self_ty, sig.tupled_inputs_ty], - ) + ty::TraitRef::new(self.tcx(), obligation.predicate.def_id(), [ + self_ty, + sig.tupled_inputs_ty, + ]) }) } _ => { @@ -951,22 +937,20 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::CoroutineClosure(_, args) => { let args = args.as_coroutine_closure(); let trait_ref = args.coroutine_closure_sig().map_bound(|sig| { - ty::TraitRef::new( - self.tcx(), - obligation.predicate.def_id(), - [self_ty, sig.tupled_inputs_ty], - ) + ty::TraitRef::new(self.tcx(), obligation.predicate.def_id(), [ + self_ty, + sig.tupled_inputs_ty, + ]) }); (trait_ref, args.kind_ty()) } ty::FnDef(..) | ty::FnPtr(..) => { let sig = self_ty.fn_sig(tcx); let trait_ref = sig.map_bound(|sig| { - ty::TraitRef::new( - self.tcx(), - obligation.predicate.def_id(), - [self_ty, Ty::new_tup(tcx, sig.inputs())], - ) + ty::TraitRef::new(self.tcx(), obligation.predicate.def_id(), [ + self_ty, + Ty::new_tup(tcx, sig.inputs()), + ]) }); // We must additionally check that the return type impls `Future`. @@ -990,11 +974,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let args = args.as_closure(); let sig = args.sig(); let trait_ref = sig.map_bound(|sig| { - ty::TraitRef::new( - self.tcx(), - obligation.predicate.def_id(), - [self_ty, sig.inputs()[0]], - ) + ty::TraitRef::new(self.tcx(), obligation.predicate.def_id(), [ + self_ty, + sig.inputs()[0], + ]) }); // We must additionally check that the return type impls `Future`. @@ -1310,11 +1293,10 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // Construct the nested `TailField: Unsize>` predicate. let tail_unsize_obligation = obligation.with( tcx, - ty::TraitRef::new( - tcx, - obligation.predicate.def_id(), - [source_tail, target_tail], - ), + ty::TraitRef::new(tcx, obligation.predicate.def_id(), [ + source_tail, + target_tail, + ]), ); nested.push(tail_unsize_obligation); diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index f5cd7273ca240..cbc17a058f6d1 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -12,25 +12,25 @@ use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet}; use rustc_data_structures::stack::ensure_sufficient_stack; use rustc_errors::{Diag, EmissionGuarantee}; use rustc_hir as hir; -use rustc_hir::def_id::DefId; use rustc_hir::LangItem; -use rustc_infer::infer::relate::TypeRelation; +use rustc_hir::def_id::DefId; use rustc_infer::infer::BoundRegionConversionTime::{self, HigherRankedType}; use rustc_infer::infer::DefineOpaqueTypes; +use rustc_infer::infer::relate::TypeRelation; use rustc_infer::traits::TraitObligation; use rustc_middle::bug; -use rustc_middle::dep_graph::{dep_kinds, DepNodeIndex}; +use rustc_middle::dep_graph::{DepNodeIndex, dep_kinds}; use rustc_middle::mir::interpret::ErrorHandled; pub use rustc_middle::traits::select::*; use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::error::TypeErrorToStringExt; -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, GenericArgsRef, PolyProjectionPredicate, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, Upcast, }; -use rustc_span::symbol::sym; use rustc_span::Symbol; +use rustc_span::symbol::sym; use tracing::{debug, instrument, trace}; use self::EvaluationResult::*; @@ -39,9 +39,9 @@ use super::coherence::{self, Conflict}; use super::project::ProjectionTermObligation; use super::util::closure_trait_ref_and_return_type; use super::{ - const_evaluatable, project, util, wf, ImplDerivedCause, Normalized, Obligation, - ObligationCause, ObligationCauseCode, Overflow, PolyTraitObligation, PredicateObligation, - Selection, SelectionError, SelectionResult, TraitQueryMode, + ImplDerivedCause, Normalized, Obligation, ObligationCause, ObligationCauseCode, Overflow, + PolyTraitObligation, PredicateObligation, Selection, SelectionError, SelectionResult, + TraitQueryMode, const_evaluatable, project, util, wf, }; use crate::error_reporting::InferCtxtErrorExt; use crate::infer::{InferCtxt, InferCtxtExt, InferOk, TypeFreshener}; @@ -2449,11 +2449,9 @@ impl<'tcx> SelectionContext<'_, 'tcx> { } else { // If this is an ill-formed auto/built-in trait, then synthesize // new error args for the missing generics. - let err_args = ty::GenericArgs::extend_with_error( - tcx, - trait_def_id, - &[normalized_ty.into()], - ); + let err_args = ty::GenericArgs::extend_with_error(tcx, trait_def_id, &[ + normalized_ty.into(), + ]); ty::TraitRef::new_from_args(tcx, trait_def_id, err_args) }; diff --git a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs index 7337b59f87041..b82a343364581 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs @@ -21,16 +21,16 @@ use rustc_middle::query::LocalCrate; use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::{self, GenericArgsRef, ImplSubject, Ty, TyCtxt, TypeVisitableExt}; use rustc_session::lint::builtin::{COHERENCE_LEAK_CHECK, ORDER_DEPENDENT_TRAIT_OBJECTS}; -use rustc_span::{sym, ErrorGuaranteed, Span, DUMMY_SP}; +use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, sym}; use specialization_graph::GraphExt; use tracing::{debug, instrument}; -use super::{util, SelectionContext}; +use super::{SelectionContext, util}; use crate::error_reporting::traits::to_pretty_impl_header; use crate::errors::NegativePositiveConflict; use crate::infer::{InferCtxt, InferOk, TyCtxtInferExt}; use crate::traits::select::IntercrateAmbiguityCause; -use crate::traits::{coherence, FutureCompatOverlapErrorKind, ObligationCause, ObligationCtxt}; +use crate::traits::{FutureCompatOverlapErrorKind, ObligationCause, ObligationCtxt, coherence}; /// Information pertinent to an overlapping impl error. #[derive(Debug)] diff --git a/compiler/rustc_trait_selection/src/traits/structural_normalize.rs b/compiler/rustc_trait_selection/src/traits/structural_normalize.rs index 9d657ade86bfe..3814f8112e92e 100644 --- a/compiler/rustc_trait_selection/src/traits/structural_normalize.rs +++ b/compiler/rustc_trait_selection/src/traits/structural_normalize.rs @@ -46,4 +46,44 @@ impl<'tcx> At<'_, 'tcx> { Ok(self.normalize(ty).into_value_registering_obligations(self.infcx, fulfill_cx)) } } + + fn structurally_normalize_const( + &self, + ct: ty::Const<'tcx>, + fulfill_cx: &mut dyn TraitEngine<'tcx, E>, + ) -> Result, Vec> { + assert!(!ct.is_ct_infer(), "should have resolved vars before calling"); + + if self.infcx.next_trait_solver() { + let ty::ConstKind::Unevaluated(..) = ct.kind() else { + return Ok(ct); + }; + + let new_infer_ct = self.infcx.next_const_var(self.cause.span); + + // We simply emit an `alias-eq` goal here, since that will take care of + // normalizing the LHS of the projection until it is a rigid projection + // (or a not-yet-defined opaque in scope). + let obligation = Obligation::new( + self.infcx.tcx, + self.cause.clone(), + self.param_env, + ty::PredicateKind::AliasRelate( + ct.into(), + new_infer_ct.into(), + ty::AliasRelationDirection::Equate, + ), + ); + + fulfill_cx.register_predicate_obligation(self.infcx, obligation); + let errors = fulfill_cx.select_where_possible(self.infcx); + if !errors.is_empty() { + return Err(errors); + } + + Ok(self.infcx.resolve_vars_if_possible(new_infer_ct)) + } else { + Ok(self.normalize(ct).into_value_registering_obligations(self.infcx, fulfill_cx)) + } + } } diff --git a/compiler/rustc_trait_selection/src/traits/util.rs b/compiler/rustc_trait_selection/src/traits/util.rs index 99445d039655a..aed2e3d61aa66 100644 --- a/compiler/rustc_trait_selection/src/traits/util.rs +++ b/compiler/rustc_trait_selection/src/traits/util.rs @@ -11,7 +11,7 @@ use rustc_middle::ty::{ TypeVisitableExt, Upcast, }; use rustc_span::Span; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use tracing::debug; use super::{NormalizeExt, ObligationCause, PredicateObligation, SelectionContext}; @@ -223,15 +223,11 @@ pub(crate) fn closure_trait_ref_and_return_type<'tcx>( TupleArgumentsFlag::Yes => Ty::new_tup(tcx, sig.skip_binder().inputs()), }; let trait_ref = if tcx.has_host_param(fn_trait_def_id) { - ty::TraitRef::new( - tcx, - fn_trait_def_id, - [ - ty::GenericArg::from(self_ty), - ty::GenericArg::from(arguments_tuple), - ty::GenericArg::from(fn_host_effect), - ], - ) + ty::TraitRef::new(tcx, fn_trait_def_id, [ + ty::GenericArg::from(self_ty), + ty::GenericArg::from(arguments_tuple), + ty::GenericArg::from(fn_host_effect), + ]) } else { ty::TraitRef::new(tcx, fn_trait_def_id, [self_ty, arguments_tuple]) }; diff --git a/compiler/rustc_trait_selection/src/traits/vtable.rs b/compiler/rustc_trait_selection/src/traits/vtable.rs index f525c17e0531c..a2760fe6049b0 100644 --- a/compiler/rustc_trait_selection/src/traits/vtable.rs +++ b/compiler/rustc_trait_selection/src/traits/vtable.rs @@ -8,8 +8,8 @@ use rustc_middle::query::Providers; use rustc_middle::ty::{ self, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeVisitableExt, Upcast, VtblEntry, }; -use rustc_span::{sym, Span, DUMMY_SP}; -use smallvec::{smallvec, SmallVec}; +use rustc_span::{DUMMY_SP, Span, sym}; +use smallvec::{SmallVec, smallvec}; use tracing::debug; use crate::errors::DumpVTableEntries; diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 889e4ed7fcc6c..354f3034b8ac5 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -8,8 +8,8 @@ use rustc_middle::ty::{ self, GenericArg, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, }; -use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; -use rustc_span::{Span, DUMMY_SP}; +use rustc_span::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; +use rustc_span::{DUMMY_SP, Span}; use tracing::{debug, instrument, trace}; use crate::infer::InferCtxt; diff --git a/compiler/rustc_traits/src/dropck_outlives.rs b/compiler/rustc_traits/src/dropck_outlives.rs index add7ec50a1e64..0d052ecf0dfd2 100644 --- a/compiler/rustc_traits/src/dropck_outlives.rs +++ b/compiler/rustc_traits/src/dropck_outlives.rs @@ -1,7 +1,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir::def_id::DefId; -use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_middle::bug; use rustc_middle::query::Providers; use rustc_middle::traits::query::{DropckConstraint, DropckOutlivesResult}; diff --git a/compiler/rustc_traits/src/implied_outlives_bounds.rs b/compiler/rustc_traits/src/implied_outlives_bounds.rs index 24e91c263e344..f9e1db567c2ba 100644 --- a/compiler/rustc_traits/src/implied_outlives_bounds.rs +++ b/compiler/rustc_traits/src/implied_outlives_bounds.rs @@ -2,8 +2,8 @@ //! Do not call this query directory. See //! [`rustc_trait_selection::traits::query::type_op::implied_outlives_bounds`]. -use rustc_infer::infer::canonical::{self, Canonical}; use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::canonical::{self, Canonical}; use rustc_infer::traits::query::OutlivesBound; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; diff --git a/compiler/rustc_traits/src/normalize_projection_ty.rs b/compiler/rustc_traits/src/normalize_projection_ty.rs index 0dff4751262f1..3102da218db4d 100644 --- a/compiler/rustc_traits/src/normalize_projection_ty.rs +++ b/compiler/rustc_traits/src/normalize_projection_ty.rs @@ -1,5 +1,5 @@ -use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_middle::query::Providers; use rustc_middle::ty::{ParamEnvAnd, TyCtxt}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; diff --git a/compiler/rustc_traits/src/type_op.rs b/compiler/rustc_traits/src/type_op.rs index f34adf8575565..c982cd66bca12 100644 --- a/compiler/rustc_traits/src/type_op.rs +++ b/compiler/rustc_traits/src/type_op.rs @@ -1,14 +1,14 @@ use std::fmt; -use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_infer::infer::TyCtxtInferExt; +use rustc_infer::infer::canonical::{Canonical, QueryResponse}; use rustc_middle::query::Providers; use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::{Clause, FnSig, ParamEnvAnd, PolyFnSig, Ty, TyCtxt, TypeFoldable}; use rustc_trait_selection::infer::InferCtxtBuilderExt; use rustc_trait_selection::traits::query::normalize::QueryNormalizeExt; use rustc_trait_selection::traits::query::type_op::ascribe_user_type::{ - type_op_ascribe_user_type_with_span, AscribeUserType, + AscribeUserType, type_op_ascribe_user_type_with_span, }; use rustc_trait_selection::traits::query::type_op::normalize::Normalize; use rustc_trait_selection::traits::query::type_op::prove_predicate::ProvePredicate; diff --git a/compiler/rustc_transmute/src/layout/dfa.rs b/compiler/rustc_transmute/src/layout/dfa.rs index 58bd517d7e89f..a70dc034e63dd 100644 --- a/compiler/rustc_transmute/src/layout/dfa.rs +++ b/compiler/rustc_transmute/src/layout/dfa.rs @@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use tracing::instrument; -use super::{nfa, Byte, Nfa, Ref}; +use super::{Byte, Nfa, Ref, nfa}; use crate::Map; #[derive(PartialEq, Clone, Debug)] diff --git a/compiler/rustc_transmute/src/layout/tree.rs b/compiler/rustc_transmute/src/layout/tree.rs index ddf9b6c28f3a9..6d5859a5a6563 100644 --- a/compiler/rustc_transmute/src/layout/tree.rs +++ b/compiler/rustc_transmute/src/layout/tree.rs @@ -179,7 +179,7 @@ pub(crate) mod rustc { }; use super::Tree; - use crate::layout::rustc::{layout_of, Def, Ref}; + use crate::layout::rustc::{Def, Ref, layout_of}; #[derive(Debug, Copy, Clone)] pub(crate) enum Err { diff --git a/compiler/rustc_transmute/src/maybe_transmutable/mod.rs b/compiler/rustc_transmute/src/maybe_transmutable/mod.rs index 9a31d9e3ac446..1e5da4ec49d09 100644 --- a/compiler/rustc_transmute/src/maybe_transmutable/mod.rs +++ b/compiler/rustc_transmute/src/maybe_transmutable/mod.rs @@ -4,7 +4,7 @@ pub(crate) mod query_context; #[cfg(test)] mod tests; -use crate::layout::{self, dfa, Byte, Def, Dfa, Nfa, Ref, Tree, Uninhabited}; +use crate::layout::{self, Byte, Def, Dfa, Nfa, Ref, Tree, Uninhabited, dfa}; use crate::maybe_transmutable::query_context::QueryContext; use crate::{Answer, Condition, Map, Reason}; diff --git a/compiler/rustc_transmute/src/maybe_transmutable/tests.rs b/compiler/rustc_transmute/src/maybe_transmutable/tests.rs index c3be4203cceb9..84af20c773e05 100644 --- a/compiler/rustc_transmute/src/maybe_transmutable/tests.rs +++ b/compiler/rustc_transmute/src/maybe_transmutable/tests.rs @@ -2,7 +2,7 @@ use itertools::Itertools; use super::query_context::test::{Def, UltraMinimal}; use crate::maybe_transmutable::MaybeTransmutableQuery; -use crate::{layout, Reason}; +use crate::{Reason, layout}; mod safety { use super::*; diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index 00d38350b20fc..f23c2cf2c07a7 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -5,7 +5,7 @@ use rustc_hir::lang_items::LangItem; use rustc_middle::bug; use rustc_middle::query::Providers; use rustc_middle::ty::layout::{ - fn_can_unwind, FnAbiError, HasParamEnv, HasTyCtxt, LayoutCx, LayoutOf, TyAndLayout, + FnAbiError, HasParamEnv, HasTyCtxt, LayoutCx, LayoutOf, TyAndLayout, fn_can_unwind, }; use rustc_middle::ty::{self, InstanceKind, Ty, TyCtxt}; use rustc_session::config::OptLevel; diff --git a/compiler/rustc_ty_utils/src/consts.rs b/compiler/rustc_ty_utils/src/consts.rs index ae5341ddec16f..391985ce88a21 100644 --- a/compiler/rustc_ty_utils/src/consts.rs +++ b/compiler/rustc_ty_utils/src/consts.rs @@ -11,7 +11,7 @@ use rustc_middle::ty::abstract_const::CastKind; use rustc_middle::ty::{self, Expr, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, mir, thir}; use rustc_span::Span; -use rustc_target::abi::{VariantIdx, FIRST_VARIANT}; +use rustc_target::abi::{FIRST_VARIANT, VariantIdx}; use tracing::{debug, instrument}; use crate::errors::{GenericConstantTooComplex, GenericConstantTooComplexSub}; diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index 70321a071a208..5cd10e9053872 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -78,10 +78,10 @@ fn assumed_wf_types<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx [(Ty<' if matches!(*orig_lt, ty::ReLateParam(..)) { mapping.insert( orig_lt, - ty::Region::new_early_param( - tcx, - ty::EarlyParamRegion { index: param.index, name: param.name }, - ), + ty::Region::new_early_param(tcx, ty::EarlyParamRegion { + index: param.index, + name: param.name, + }), ); } } diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index d77c3a277bfe8..9b764133f2c6a 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -1,6 +1,6 @@ use rustc_errors::ErrorGuaranteed; -use rustc_hir::def_id::DefId; use rustc_hir::LangItem; +use rustc_hir::def_id::DefId; use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::bug; use rustc_middle::query::Providers; @@ -11,7 +11,7 @@ use rustc_span::sym; use rustc_trait_selection::traits; use rustc_type_ir::ClosureKind; use tracing::debug; -use traits::{translate_args, Reveal}; +use traits::{Reveal, translate_args}; use crate::errors::UnexpectedFnPtrAssociatedItem; diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index c153fb64c333b..34c9f1b63c066 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -9,7 +9,7 @@ use rustc_middle::bug; use rustc_middle::mir::{CoroutineLayout, CoroutineSavedLocal}; use rustc_middle::query::Providers; use rustc_middle::ty::layout::{ - FloatExt, HasTyCtxt, IntegerExt, LayoutCx, LayoutError, LayoutOf, TyAndLayout, MAX_SIMD_LANES, + FloatExt, HasTyCtxt, IntegerExt, LayoutCx, LayoutError, LayoutOf, MAX_SIMD_LANES, TyAndLayout, }; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{ @@ -194,20 +194,14 @@ fn layout_of_uncached<'tcx>( } // Basic scalars. - ty::Bool => tcx.mk_layout(LayoutS::scalar( - cx, - Scalar::Initialized { - value: Int(I8, false), - valid_range: WrappingRange { start: 0, end: 1 }, - }, - )), - ty::Char => tcx.mk_layout(LayoutS::scalar( - cx, - Scalar::Initialized { - value: Int(I32, false), - valid_range: WrappingRange { start: 0, end: 0x10FFFF }, - }, - )), + ty::Bool => tcx.mk_layout(LayoutS::scalar(cx, Scalar::Initialized { + value: Int(I8, false), + valid_range: WrappingRange { start: 0, end: 1 }, + })), + ty::Char => tcx.mk_layout(LayoutS::scalar(cx, Scalar::Initialized { + value: Int(I32, false), + valid_range: WrappingRange { start: 0, end: 0x10FFFF }, + })), ty::Int(ity) => scalar(Int(Integer::from_int_ty(dl, ity), true)), ty::Uint(ity) => scalar(Int(Integer::from_uint_ty(dl, ity), false)), ty::Float(fty) => scalar(Float(Float::from_float_ty(fty))), @@ -510,13 +504,10 @@ fn layout_of_uncached<'tcx>( // Non-power-of-two vectors have padding up to the next power-of-two. // If we're a packed repr, remove the padding while keeping the alignment as close // to a vector as possible. - ( - Abi::Aggregate { sized: true }, - AbiAndPrefAlign { - abi: Align::max_for_offset(size), - pref: dl.vector_align(size).pref, - }, - ) + (Abi::Aggregate { sized: true }, AbiAndPrefAlign { + abi: Align::max_for_offset(size), + pref: dl.vector_align(size).pref, + }) } else { (Abi::Vector { element: e_abi, count: e_len }, dl.vector_align(size)) }; @@ -1124,13 +1115,10 @@ fn variant_info_for_adt<'tcx>( }) .collect(); - ( - variant_infos, - match tag_encoding { - TagEncoding::Direct => Some(tag.size(cx)), - _ => None, - }, - ) + (variant_infos, match tag_encoding { + TagEncoding::Direct => Some(tag.size(cx)), + _ => None, + }) } } } @@ -1250,11 +1238,8 @@ fn variant_info_for_coroutine<'tcx>( let end_states: Vec<_> = end_states.collect(); variant_infos.extend(end_states); - ( - variant_infos, - match tag_encoding { - TagEncoding::Direct => Some(tag.size(cx)), - _ => None, - }, - ) + (variant_infos, match tag_encoding { + TagEncoding::Direct => Some(tag.size(cx)), + _ => None, + }) } diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 9a3956596d23f..5fecbd310b770 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -4,7 +4,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir::def_id::DefId; use rustc_middle::bug; use rustc_middle::query::Providers; -use rustc_middle::ty::util::{needs_drop_components, AlwaysRequiresDrop}; +use rustc_middle::ty::util::{AlwaysRequiresDrop, needs_drop_components}; use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt}; use rustc_session::Limit; use rustc_span::sym; diff --git a/compiler/rustc_ty_utils/src/opaque_types.rs b/compiler/rustc_ty_utils/src/opaque_types.rs index 6b24929467be2..bac0d020d721b 100644 --- a/compiler/rustc_ty_utils/src/opaque_types.rs +++ b/compiler/rustc_ty_utils/src/opaque_types.rs @@ -2,7 +2,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir::def::DefKind; use rustc_hir::def_id::LocalDefId; use rustc_hir::intravisit::Visitor; -use rustc_hir::{intravisit, CRATE_HIR_ID}; +use rustc_hir::{CRATE_HIR_ID, intravisit}; use rustc_middle::bug; use rustc_middle::query::Providers; use rustc_middle::ty::util::{CheckRegions, NotUniqueParam}; diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index aba2acd1842f1..28a81b1b06217 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -1,7 +1,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir as hir; -use rustc_hir::def::DefKind; use rustc_hir::LangItem; +use rustc_hir::def::DefKind; use rustc_index::bit_set::BitSet; use rustc_middle::bug; use rustc_middle::query::Providers; @@ -9,8 +9,8 @@ use rustc_middle::ty::{ self, EarlyBinder, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, Upcast, }; -use rustc_span::def_id::{DefId, LocalDefId, CRATE_DEF_ID}; use rustc_span::DUMMY_SP; +use rustc_span::def_id::{CRATE_DEF_ID, DefId, LocalDefId}; use rustc_trait_selection::traits; use tracing::{debug, instrument}; diff --git a/compiler/rustc_type_ir/src/effects.rs b/compiler/rustc_type_ir/src/effects.rs index a29e0a43befa3..ab43533dd8692 100644 --- a/compiler/rustc_type_ir/src/effects.rs +++ b/compiler/rustc_type_ir/src/effects.rs @@ -1,6 +1,6 @@ +use crate::Interner; use crate::inherent::*; use crate::lang_items::TraitSolverLangItem::{EffectsMaybe, EffectsNoRuntime, EffectsRuntime}; -use crate::Interner; #[derive(Clone, Copy, PartialEq, Eq)] pub enum EffectKind { diff --git a/compiler/rustc_type_ir/src/elaborate.rs b/compiler/rustc_type_ir/src/elaborate.rs index f30419c801f18..3db9b8b06610e 100644 --- a/compiler/rustc_type_ir/src/elaborate.rs +++ b/compiler/rustc_type_ir/src/elaborate.rs @@ -4,7 +4,7 @@ use smallvec::smallvec; use crate::data_structures::HashSet; use crate::inherent::*; -use crate::outlives::{push_outlives_components, Component}; +use crate::outlives::{Component, push_outlives_components}; use crate::{self as ty, Interner, Upcast as _}; /// "Elaboration" is the process of identifying all the predicates that diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index be261b348de52..02a9ad1e35fab 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -56,6 +56,12 @@ mod ty_info; mod ty_kind; mod upcast; +pub use AliasTyKind::*; +pub use DynKind::*; +pub use InferTy::*; +pub use RegionKind::*; +pub use TyKind::*; +pub use Variance::*; pub use binder::*; pub use canonical::*; #[cfg(feature = "nightly")] @@ -73,12 +79,6 @@ pub use region_kind::*; pub use ty_info::*; pub use ty_kind::*; pub use upcast::*; -pub use AliasTyKind::*; -pub use DynKind::*; -pub use InferTy::*; -pub use RegionKind::*; -pub use TyKind::*; -pub use Variance::*; rustc_index::newtype_index! { /// A [De Bruijn index][dbi] is a standard means of representing diff --git a/compiler/rustc_type_ir/src/outlives.rs b/compiler/rustc_type_ir/src/outlives.rs index e8afaf1a4809a..ac35215fbaa0d 100644 --- a/compiler/rustc_type_ir/src/outlives.rs +++ b/compiler/rustc_type_ir/src/outlives.rs @@ -3,7 +3,7 @@ //! RFC for reference. use derive_where::derive_where; -use smallvec::{smallvec, SmallVec}; +use smallvec::{SmallVec, smallvec}; use crate::data_structures::SsoHashSet; use crate::inherent::*; diff --git a/compiler/rustc_type_ir/src/predicate.rs b/compiler/rustc_type_ir/src/predicate.rs index e4bf1e1379c95..7e300fe02dca4 100644 --- a/compiler/rustc_type_ir/src/predicate.rs +++ b/compiler/rustc_type_ir/src/predicate.rs @@ -492,29 +492,35 @@ impl AliasTerm { pub fn to_term(self, interner: I) -> I::Term { match self.kind(interner) { - AliasTermKind::ProjectionTy => Ty::new_alias( - interner, - ty::AliasTyKind::Projection, - ty::AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () }, - ) - .into(), - AliasTermKind::InherentTy => Ty::new_alias( - interner, - ty::AliasTyKind::Inherent, - ty::AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () }, - ) - .into(), - AliasTermKind::OpaqueTy => Ty::new_alias( - interner, - ty::AliasTyKind::Opaque, - ty::AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () }, - ) - .into(), - AliasTermKind::WeakTy => Ty::new_alias( - interner, - ty::AliasTyKind::Weak, - ty::AliasTy { def_id: self.def_id, args: self.args, _use_alias_ty_new_instead: () }, - ) + AliasTermKind::ProjectionTy => { + Ty::new_alias(interner, ty::AliasTyKind::Projection, ty::AliasTy { + def_id: self.def_id, + args: self.args, + _use_alias_ty_new_instead: (), + }) + .into() + } + AliasTermKind::InherentTy => { + Ty::new_alias(interner, ty::AliasTyKind::Inherent, ty::AliasTy { + def_id: self.def_id, + args: self.args, + _use_alias_ty_new_instead: (), + }) + .into() + } + AliasTermKind::OpaqueTy => { + Ty::new_alias(interner, ty::AliasTyKind::Opaque, ty::AliasTy { + def_id: self.def_id, + args: self.args, + _use_alias_ty_new_instead: (), + }) + .into() + } + AliasTermKind::WeakTy => Ty::new_alias(interner, ty::AliasTyKind::Weak, ty::AliasTy { + def_id: self.def_id, + args: self.args, + _use_alias_ty_new_instead: (), + }) .into(), AliasTermKind::UnevaluatedConst | AliasTermKind::ProjectionConst => { I::Const::new_unevaluated( diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 80c3565911e9a..b7f6ef4ffbb9a 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -10,8 +10,8 @@ use rustc_data_structures::unify::{NoError, UnifyKey, UnifyValue}; use rustc_macros::{Decodable, Encodable, HashStable_NoContext, TyDecodable, TyEncodable}; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; -pub use self::closure::*; use self::TyKind::*; +pub use self::closure::*; use crate::inherent::*; use crate::{self as ty, DebruijnIndex, Interner}; diff --git a/compiler/rustc_type_ir/src/ty_kind/closure.rs b/compiler/rustc_type_ir/src/ty_kind/closure.rs index 9d907baeeb302..09a43b1795516 100644 --- a/compiler/rustc_type_ir/src/ty_kind/closure.rs +++ b/compiler/rustc_type_ir/src/ty_kind/closure.rs @@ -3,7 +3,7 @@ use std::ops::ControlFlow; use derive_where::derive_where; use rustc_type_ir_macros::{Lift_Generic, TypeFoldable_Generic, TypeVisitable_Generic}; -use crate::fold::{shift_region, TypeFoldable, TypeFolder, TypeSuperFoldable}; +use crate::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable, shift_region}; use crate::inherent::*; use crate::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitor}; use crate::{self as ty, Interner}; @@ -394,18 +394,15 @@ impl CoroutineClosureSignature { coroutine_def_id: I::DefId, tupled_upvars_ty: I::Ty, ) -> I::Ty { - let coroutine_args = ty::CoroutineArgs::new( - cx, - ty::CoroutineArgsParts { - parent_args, - kind_ty: coroutine_kind_ty, - resume_ty: self.resume_ty, - yield_ty: self.yield_ty, - return_ty: self.return_ty, - witness: self.interior, - tupled_upvars_ty, - }, - ); + let coroutine_args = ty::CoroutineArgs::new(cx, ty::CoroutineArgsParts { + parent_args, + kind_ty: coroutine_kind_ty, + resume_ty: self.resume_ty, + yield_ty: self.yield_ty, + return_ty: self.return_ty, + witness: self.interior, + tupled_upvars_ty, + }); Ty::new_coroutine(cx, coroutine_def_id, coroutine_args.args) } diff --git a/compiler/rustc_type_ir_macros/src/lib.rs b/compiler/rustc_type_ir_macros/src/lib.rs index 2bfbfaa498bf3..1a0a2479f6f07 100644 --- a/compiler/rustc_type_ir_macros/src/lib.rs +++ b/compiler/rustc_type_ir_macros/src/lib.rs @@ -35,17 +35,14 @@ fn type_foldable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Toke }) }); - s.bound_impl( - quote!(::rustc_type_ir::fold::TypeFoldable), - quote! { - fn try_fold_with<__F: ::rustc_type_ir::fold::FallibleTypeFolder>( - self, - __folder: &mut __F - ) -> Result { - Ok(match self { #body_fold }) - } - }, - ) + s.bound_impl(quote!(::rustc_type_ir::fold::TypeFoldable), quote! { + fn try_fold_with<__F: ::rustc_type_ir::fold::FallibleTypeFolder>( + self, + __folder: &mut __F + ) -> Result { + Ok(match self { #body_fold }) + } + }) } fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { @@ -85,19 +82,16 @@ fn lift_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::TokenStream { let self_ty: syn::Type = parse_quote! { #name #ty_generics }; let lifted_ty = lift(self_ty); - s.bound_impl( - quote!(::rustc_type_ir::lift::Lift), - quote! { - type Lifted = #lifted_ty; + s.bound_impl(quote!(::rustc_type_ir::lift::Lift), quote! { + type Lifted = #lifted_ty; - fn lift_to_interner( - self, - interner: J, - ) -> Option { - Some(match self { #body_fold }) - } - }, - ) + fn lift_to_interner( + self, + interner: J, + ) -> Option { + Some(match self { #body_fold }) + } + }) } fn lift(mut ty: syn::Type) -> syn::Type { @@ -145,16 +139,13 @@ fn type_visitable_derive(mut s: synstructure::Structure<'_>) -> proc_macro2::Tok }); s.bind_with(|_| synstructure::BindStyle::Move); - s.bound_impl( - quote!(::rustc_type_ir::visit::TypeVisitable), - quote! { - fn visit_with<__V: ::rustc_type_ir::visit::TypeVisitor>( - &self, - __visitor: &mut __V - ) -> __V::Result { - match *self { #body_visit } - <__V::Result as ::rustc_ast_ir::visit::VisitorResult>::output() - } - }, - ) + s.bound_impl(quote!(::rustc_type_ir::visit::TypeVisitable), quote! { + fn visit_with<__V: ::rustc_type_ir::visit::TypeVisitor>( + &self, + __visitor: &mut __V + ) -> __V::Result { + match *self { #body_visit } + <__V::Result as ::rustc_ast_ir::visit::VisitorResult>::output() + } + }) } diff --git a/compiler/stable_mir/src/abi.rs b/compiler/stable_mir/src/abi.rs index dc73d9c2188af..2ac30b5aff12a 100644 --- a/compiler/stable_mir/src/abi.rs +++ b/compiler/stable_mir/src/abi.rs @@ -8,7 +8,7 @@ use crate::compiler_interface::with; use crate::mir::FieldIdx; use crate::target::{MachineInfo, MachineSize as Size}; use crate::ty::{Align, IndexedVal, Ty, VariantIdx}; -use crate::{error, Error, Opaque}; +use crate::{Error, Opaque, error}; /// A function ABI definition. #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] diff --git a/compiler/stable_mir/src/compiler_interface.rs b/compiler/stable_mir/src/compiler_interface.rs index 5f2d9b96c73ca..9060a869f7fb1 100644 --- a/compiler/stable_mir/src/compiler_interface.rs +++ b/compiler/stable_mir/src/compiler_interface.rs @@ -18,8 +18,8 @@ use crate::ty::{ TraitDef, Ty, TyConst, TyConstId, TyKind, UintTy, VariantDef, }; use crate::{ - mir, Crate, CrateItem, CrateItems, CrateNum, DefId, Error, Filename, ImplTraitDecls, ItemKind, - Symbol, TraitDecls, + Crate, CrateItem, CrateItems, CrateNum, DefId, Error, Filename, ImplTraitDecls, ItemKind, + Symbol, TraitDecls, mir, }; /// This trait defines the interface between stable_mir and the Rust compiler. diff --git a/compiler/stable_mir/src/crate_def.rs b/compiler/stable_mir/src/crate_def.rs index 2882fdf7bed86..cf29176dbbdda 100644 --- a/compiler/stable_mir/src/crate_def.rs +++ b/compiler/stable_mir/src/crate_def.rs @@ -4,7 +4,7 @@ use serde::Serialize; use crate::ty::{GenericArgs, Span, Ty}; -use crate::{with, Crate, Symbol}; +use crate::{Crate, Symbol, with}; /// A unique identification number for each item accessible for the current compilation unit. #[derive(Clone, Copy, PartialEq, Eq, Hash, Serialize)] diff --git a/compiler/stable_mir/src/mir/alloc.rs b/compiler/stable_mir/src/mir/alloc.rs index a3768f8e01c9b..7e0c4a479b8ef 100644 --- a/compiler/stable_mir/src/mir/alloc.rs +++ b/compiler/stable_mir/src/mir/alloc.rs @@ -7,7 +7,7 @@ use serde::Serialize; use crate::mir::mono::{Instance, StaticDef}; use crate::target::{Endian, MachineInfo}; use crate::ty::{Allocation, Binder, ExistentialTraitRef, IndexedVal, Ty}; -use crate::{with, Error}; +use crate::{Error, with}; /// An allocation in the SMIR global memory can be either a function pointer, /// a static, or a "real" allocation with some data in it. diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs index 7c09fe1a08541..ab9fc218d19fb 100644 --- a/compiler/stable_mir/src/mir/body.rs +++ b/compiler/stable_mir/src/mir/body.rs @@ -960,6 +960,7 @@ pub enum CastKind { PointerExposeAddress, PointerWithExposedProvenance, PointerCoercion(PointerCoercion), + // FIXME(smir-rename): change this to PointerCoercion(DynStar) DynStar, IntToInt, FloatToInt, diff --git a/compiler/stable_mir/src/mir/mono.rs b/compiler/stable_mir/src/mir/mono.rs index cd02844453112..22507a49411f9 100644 --- a/compiler/stable_mir/src/mir/mono.rs +++ b/compiler/stable_mir/src/mir/mono.rs @@ -7,7 +7,7 @@ use crate::abi::FnAbi; use crate::crate_def::CrateDef; use crate::mir::Body; use crate::ty::{Allocation, ClosureDef, ClosureKind, FnDef, GenericArgs, IndexedVal, Ty}; -use crate::{with, CrateItem, DefId, Error, ItemKind, Opaque, Symbol}; +use crate::{CrateItem, DefId, Error, ItemKind, Opaque, Symbol, with}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize)] pub enum MonoItem { diff --git a/compiler/stable_mir/src/mir/pretty.rs b/compiler/stable_mir/src/mir/pretty.rs index dec0068ef7ef2..74081af1d86d0 100644 --- a/compiler/stable_mir/src/mir/pretty.rs +++ b/compiler/stable_mir/src/mir/pretty.rs @@ -7,7 +7,7 @@ use fmt::{Display, Formatter}; use super::{AssertMessage, BinOp, BorrowKind, FakeBorrowKind, TerminatorKind}; use crate::mir::{Operand, Place, Rvalue, StatementKind, UnwindAction, VarDebugInfoContents}; use crate::ty::{IndexedVal, MirConst, Ty, TyConst}; -use crate::{with, Body, Mutability}; +use crate::{Body, Mutability, with}; impl Display for Ty { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { diff --git a/compiler/stable_mir/src/ty.rs b/compiler/stable_mir/src/ty.rs index 011d19f61430e..b3dc4d9bb8207 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -4,10 +4,10 @@ use std::ops::Range; use serde::Serialize; use super::mir::{Body, Mutability, Safety}; -use super::{with, DefId, Error, Symbol}; +use super::{DefId, Error, Symbol, with}; use crate::abi::{FnAbi, Layout}; use crate::crate_def::{CrateDef, CrateDefType}; -use crate::mir::alloc::{read_target_int, read_target_uint, AllocId}; +use crate::mir::alloc::{AllocId, read_target_int, read_target_uint}; use crate::mir::mono::StaticDef; use crate::target::MachineInfo; use crate::{Filename, Opaque}; diff --git a/compiler/stable_mir/src/visitor.rs b/compiler/stable_mir/src/visitor.rs index 72cf84acb856a..3c769b2d37cfc 100644 --- a/compiler/stable_mir/src/visitor.rs +++ b/compiler/stable_mir/src/visitor.rs @@ -4,8 +4,8 @@ use super::ty::{ Allocation, Binder, ConstDef, ExistentialPredicate, FnSig, GenericArgKind, GenericArgs, MirConst, Promoted, Region, RigidTy, TermKind, Ty, UnevaluatedConst, }; -use crate::ty::TyConst; use crate::Opaque; +use crate::ty::TyConst; pub trait Visitor: Sized { type Break; diff --git a/library/Cargo.lock b/library/Cargo.lock index ded30dd82f7b4..2343b2baf8347 100644 --- a/library/Cargo.lock +++ b/library/Cargo.lock @@ -326,6 +326,7 @@ dependencies = [ "hashbrown", "hermit-abi", "libc", + "memchr", "miniz_oxide", "object", "panic_abort", diff --git a/library/alloc/benches/binary_heap.rs b/library/alloc/benches/binary_heap.rs index 917e71f250ee8..1b8f7f1c24278 100644 --- a/library/alloc/benches/binary_heap.rs +++ b/library/alloc/benches/binary_heap.rs @@ -1,7 +1,7 @@ use std::collections::BinaryHeap; use rand::seq::SliceRandom; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn bench_find_smallest_1000(b: &mut Bencher) { diff --git a/library/alloc/benches/btree/map.rs b/library/alloc/benches/btree/map.rs index 3bddef5045a00..b8119c9f0ebf4 100644 --- a/library/alloc/benches/btree/map.rs +++ b/library/alloc/benches/btree/map.rs @@ -1,9 +1,9 @@ use std::collections::BTreeMap; use std::ops::RangeBounds; -use rand::seq::SliceRandom; use rand::Rng; -use test::{black_box, Bencher}; +use rand::seq::SliceRandom; +use test::{Bencher, black_box}; macro_rules! map_insert_rand_bench { ($name: ident, $n: expr, $map: ident) => { diff --git a/library/alloc/benches/slice.rs b/library/alloc/benches/slice.rs index ab46603d7739c..48c74c4491dc8 100644 --- a/library/alloc/benches/slice.rs +++ b/library/alloc/benches/slice.rs @@ -1,8 +1,8 @@ use std::{mem, ptr}; -use rand::distributions::{Alphanumeric, DistString, Standard}; use rand::Rng; -use test::{black_box, Bencher}; +use rand::distributions::{Alphanumeric, DistString, Standard}; +use test::{Bencher, black_box}; #[bench] fn iterator(b: &mut Bencher) { diff --git a/library/alloc/benches/str.rs b/library/alloc/benches/str.rs index c148ab6b220a5..f020638e99271 100644 --- a/library/alloc/benches/str.rs +++ b/library/alloc/benches/str.rs @@ -1,4 +1,4 @@ -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn char_iterator(b: &mut Bencher) { diff --git a/library/alloc/benches/string.rs b/library/alloc/benches/string.rs index e0dbe80d28896..3d79ab78c6950 100644 --- a/library/alloc/benches/string.rs +++ b/library/alloc/benches/string.rs @@ -1,6 +1,6 @@ use std::iter::repeat; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn bench_with_capacity(b: &mut Bencher) { diff --git a/library/alloc/benches/vec.rs b/library/alloc/benches/vec.rs index 13d784d3fd40e..d29ffae9d70b1 100644 --- a/library/alloc/benches/vec.rs +++ b/library/alloc/benches/vec.rs @@ -1,7 +1,7 @@ use std::iter::repeat; use rand::RngCore; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn bench_new(b: &mut Bencher) { diff --git a/library/alloc/benches/vec_deque.rs b/library/alloc/benches/vec_deque.rs index fb1e2685cc333..a56f8496963bc 100644 --- a/library/alloc/benches/vec_deque.rs +++ b/library/alloc/benches/vec_deque.rs @@ -1,7 +1,7 @@ -use std::collections::{vec_deque, VecDeque}; +use std::collections::{VecDeque, vec_deque}; use std::mem; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn bench_new(b: &mut Bencher) { diff --git a/library/alloc/src/boxed.rs b/library/alloc/src/boxed.rs index 5978908e8f5ac..f61a484499f97 100644 --- a/library/alloc/src/boxed.rs +++ b/library/alloc/src/boxed.rs @@ -199,7 +199,7 @@ use core::ops::{ DerefPure, DispatchFromDyn, Receiver, }; use core::pin::{Pin, PinCoerceUnsized}; -use core::ptr::{self, addr_of_mut, NonNull, Unique}; +use core::ptr::{self, NonNull, Unique, addr_of_mut}; use core::task::{Context, Poll}; use core::{borrow, fmt, slice}; @@ -2480,7 +2480,10 @@ impl + ?Sized, A: Allocator> AsyncFnOnce #[unstable(feature = "async_fn_traits", issue = "none")] impl + ?Sized, A: Allocator> AsyncFnMut for Box { - type CallRefFuture<'a> = F::CallRefFuture<'a> where Self: 'a; + type CallRefFuture<'a> + = F::CallRefFuture<'a> + where + Self: 'a; extern "rust-call" fn async_call_mut(&mut self, args: Args) -> Self::CallRefFuture<'_> { F::async_call_mut(self, args) diff --git a/library/alloc/src/collections/binary_heap/mod.rs b/library/alloc/src/collections/binary_heap/mod.rs index a19a044fc7e2f..5e59abf54ee0f 100644 --- a/library/alloc/src/collections/binary_heap/mod.rs +++ b/library/alloc/src/collections/binary_heap/mod.rs @@ -145,7 +145,7 @@ use core::alloc::Allocator; use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen}; -use core::mem::{self, swap, ManuallyDrop}; +use core::mem::{self, ManuallyDrop, swap}; use core::num::NonZero; use core::ops::{Deref, DerefMut}; use core::{fmt, ptr}; diff --git a/library/alloc/src/collections/binary_heap/tests.rs b/library/alloc/src/collections/binary_heap/tests.rs index 1cb07c6214953..c18318724a4ef 100644 --- a/library/alloc/src/collections/binary_heap/tests.rs +++ b/library/alloc/src/collections/binary_heap/tests.rs @@ -1,4 +1,4 @@ -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use super::*; use crate::boxed::Box; diff --git a/library/alloc/src/collections/btree/fix.rs b/library/alloc/src/collections/btree/fix.rs index 4c1e19ead4031..95fb52b7f77b3 100644 --- a/library/alloc/src/collections/btree/fix.rs +++ b/library/alloc/src/collections/btree/fix.rs @@ -3,7 +3,7 @@ use core::alloc::Allocator; use super::map::MIN_LEN; use super::node::ForceResult::*; use super::node::LeftOrRight::*; -use super::node::{marker, Handle, NodeRef, Root}; +use super::node::{Handle, NodeRef, Root, marker}; impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { /// Stocks up a possibly underfull node by merging with or stealing from a diff --git a/library/alloc/src/collections/btree/map.rs b/library/alloc/src/collections/btree/map.rs index 0eadc9ecac8fa..55649d865fc63 100644 --- a/library/alloc/src/collections/btree/map.rs +++ b/library/alloc/src/collections/btree/map.rs @@ -13,7 +13,7 @@ use super::borrow::DormantMutRef; use super::dedup_sorted_iter::DedupSortedIter; use super::navigate::{LazyLeafRange, LeafRange}; use super::node::ForceResult::*; -use super::node::{self, marker, Handle, NodeRef, Root}; +use super::node::{self, Handle, NodeRef, Root, marker}; use super::search::SearchBound; use super::search::SearchResult::*; use super::set_val::SetValZST; @@ -22,9 +22,9 @@ use crate::vec::Vec; mod entry; +use Entry::*; #[stable(feature = "rust1", since = "1.0.0")] pub use entry::{Entry, OccupiedEntry, OccupiedError, VacantEntry}; -use Entry::*; /// Minimum number of elements in a node that is not a root. /// We might temporarily have fewer elements during methods. diff --git a/library/alloc/src/collections/btree/map/entry.rs b/library/alloc/src/collections/btree/map/entry.rs index d128ad8ee5f6d..75bb86916a887 100644 --- a/library/alloc/src/collections/btree/map/entry.rs +++ b/library/alloc/src/collections/btree/map/entry.rs @@ -5,7 +5,7 @@ use core::mem; use Entry::*; use super::super::borrow::DormantMutRef; -use super::super::node::{marker, Handle, NodeRef}; +use super::super::node::{Handle, NodeRef, marker}; use super::BTreeMap; use crate::alloc::{Allocator, Global}; diff --git a/library/alloc/src/collections/btree/map/tests.rs b/library/alloc/src/collections/btree/map/tests.rs index ff1254a5a0c42..d0e413778f87f 100644 --- a/library/alloc/src/collections/btree/map/tests.rs +++ b/library/alloc/src/collections/btree/map/tests.rs @@ -1,7 +1,7 @@ use core::assert_matches::assert_matches; use std::iter; use std::ops::Bound::{Excluded, Included, Unbounded}; -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; diff --git a/library/alloc/src/collections/btree/navigate.rs b/library/alloc/src/collections/btree/navigate.rs index f5c621e2c1759..14b7d4ad71f86 100644 --- a/library/alloc/src/collections/btree/navigate.rs +++ b/library/alloc/src/collections/btree/navigate.rs @@ -3,7 +3,7 @@ use core::ops::RangeBounds; use core::{hint, ptr}; use super::node::ForceResult::*; -use super::node::{marker, Handle, NodeRef}; +use super::node::{Handle, NodeRef, marker}; use super::search::SearchBound; use crate::alloc::Allocator; // `front` and `back` are always both `None` or both `Some`. diff --git a/library/alloc/src/collections/btree/remove.rs b/library/alloc/src/collections/btree/remove.rs index c46422c2f1d45..56f2824b782bd 100644 --- a/library/alloc/src/collections/btree/remove.rs +++ b/library/alloc/src/collections/btree/remove.rs @@ -3,7 +3,7 @@ use core::alloc::Allocator; use super::map::MIN_LEN; use super::node::ForceResult::*; use super::node::LeftOrRight::*; -use super::node::{marker, Handle, NodeRef}; +use super::node::{Handle, NodeRef, marker}; impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::KV> { /// Removes a key-value pair from the tree, and returns that pair, as well as diff --git a/library/alloc/src/collections/btree/search.rs b/library/alloc/src/collections/btree/search.rs index 1d5c927175ea6..22e015edac3d2 100644 --- a/library/alloc/src/collections/btree/search.rs +++ b/library/alloc/src/collections/btree/search.rs @@ -6,7 +6,7 @@ use SearchBound::*; use SearchResult::*; use super::node::ForceResult::*; -use super::node::{marker, Handle, NodeRef}; +use super::node::{Handle, NodeRef, marker}; pub enum SearchBound { /// An inclusive bound to look for, just like `Bound::Included(T)`. diff --git a/library/alloc/src/collections/btree/set.rs b/library/alloc/src/collections/btree/set.rs index 770cd80ea9c2e..a40209fa2e397 100644 --- a/library/alloc/src/collections/btree/set.rs +++ b/library/alloc/src/collections/btree/set.rs @@ -7,10 +7,10 @@ use core::iter::{FusedIterator, Peekable}; use core::mem::ManuallyDrop; use core::ops::{BitAnd, BitOr, BitXor, Bound, RangeBounds, Sub}; +use super::Recover; use super::map::{BTreeMap, Keys}; use super::merge_iter::MergeIterInner; use super::set_val::SetValZST; -use super::Recover; use crate::alloc::{Allocator, Global}; use crate::vec::Vec; diff --git a/library/alloc/src/collections/btree/set/tests.rs b/library/alloc/src/collections/btree/set/tests.rs index f947b6108c9a7..990044e069f64 100644 --- a/library/alloc/src/collections/btree/set/tests.rs +++ b/library/alloc/src/collections/btree/set/tests.rs @@ -1,5 +1,5 @@ use std::ops::Bound::{Excluded, Included}; -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use super::*; use crate::testing::crash_test::{CrashTestDummy, Panic}; @@ -132,11 +132,9 @@ fn test_difference() { check_difference(&[1, 3, 5, 9, 11], &[3, 6, 9], &[1, 5, 11]); check_difference(&[1, 3, 5, 9, 11], &[0, 1], &[3, 5, 9, 11]); check_difference(&[1, 3, 5, 9, 11], &[11, 12], &[1, 3, 5, 9]); - check_difference( - &[-5, 11, 22, 33, 40, 42], - &[-12, -5, 14, 23, 34, 38, 39, 50], - &[11, 22, 33, 40, 42], - ); + check_difference(&[-5, 11, 22, 33, 40, 42], &[-12, -5, 14, 23, 34, 38, 39, 50], &[ + 11, 22, 33, 40, 42, + ]); if cfg!(miri) { // Miri is too slow @@ -252,11 +250,9 @@ fn test_union() { check_union(&[], &[], &[]); check_union(&[1, 2, 3], &[2], &[1, 2, 3]); check_union(&[2], &[1, 2, 3], &[1, 2, 3]); - check_union( - &[1, 3, 5, 9, 11, 16, 19, 24], - &[-2, 1, 5, 9, 13, 19], - &[-2, 1, 3, 5, 9, 11, 13, 16, 19, 24], - ); + check_union(&[1, 3, 5, 9, 11, 16, 19, 24], &[-2, 1, 5, 9, 13, 19], &[ + -2, 1, 3, 5, 9, 11, 13, 16, 19, 24, + ]); } #[test] diff --git a/library/alloc/src/collections/linked_list/tests.rs b/library/alloc/src/collections/linked_list/tests.rs index c93e5813b1182..b7d4f8512a0f2 100644 --- a/library/alloc/src/collections/linked_list/tests.rs +++ b/library/alloc/src/collections/linked_list/tests.rs @@ -1,7 +1,7 @@ // FIXME(static_mut_refs): Do not allow `static_mut_refs` lint #![allow(static_mut_refs)] -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::thread; use rand::RngCore; @@ -696,10 +696,9 @@ fn test_cursor_mut_insert() { cursor.splice_after(p); cursor.splice_before(q); check_links(&m); - assert_eq!( - m.iter().cloned().collect::>(), - &[200, 201, 202, 203, 1, 100, 101, 102, 103, 8, 2, 3, 4, 5, 6] - ); + assert_eq!(m.iter().cloned().collect::>(), &[ + 200, 201, 202, 203, 1, 100, 101, 102, 103, 8, 2, 3, 4, 5, 6 + ]); let mut cursor = m.cursor_front_mut(); cursor.move_prev(); let tmp = cursor.split_before(); @@ -916,10 +915,9 @@ fn extract_if_complex() { assert_eq!(removed, vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]); assert_eq!(list.len(), 14); - assert_eq!( - list.into_iter().collect::>(), - vec![1, 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39] - ); + assert_eq!(list.into_iter().collect::>(), vec![ + 1, 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39 + ]); } { @@ -934,10 +932,9 @@ fn extract_if_complex() { assert_eq!(removed, vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]); assert_eq!(list.len(), 13); - assert_eq!( - list.into_iter().collect::>(), - vec![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39] - ); + assert_eq!(list.into_iter().collect::>(), vec![ + 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39 + ]); } { @@ -952,10 +949,9 @@ fn extract_if_complex() { assert_eq!(removed, vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]); assert_eq!(list.len(), 11); - assert_eq!( - list.into_iter().collect::>(), - vec![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35] - ); + assert_eq!(list.into_iter().collect::>(), vec![ + 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35 + ]); } { diff --git a/library/alloc/src/collections/vec_deque/mod.rs b/library/alloc/src/collections/vec_deque/mod.rs index a438517b75b9a..b1759a486ac64 100644 --- a/library/alloc/src/collections/vec_deque/mod.rs +++ b/library/alloc/src/collections/vec_deque/mod.rs @@ -9,7 +9,7 @@ use core::cmp::{self, Ordering}; use core::hash::{Hash, Hasher}; -use core::iter::{repeat_n, repeat_with, ByRefSized}; +use core::iter::{ByRefSized, repeat_n, repeat_with}; // This is used in a bunch of intra-doc links. // FIXME: For some reason, `#[cfg(doc)]` wasn't sufficient, resulting in // failures in linkchecker even though rustdoc built the docs just fine. diff --git a/library/alloc/src/collections/vec_deque/tests.rs b/library/alloc/src/collections/vec_deque/tests.rs index c90679f179775..6328b3b4db867 100644 --- a/library/alloc/src/collections/vec_deque/tests.rs +++ b/library/alloc/src/collections/vec_deque/tests.rs @@ -562,10 +562,9 @@ fn make_contiguous_head_to_end() { tester.push_front(i as char); } - assert_eq!( - tester, - ['P', 'O', 'N', 'M', 'L', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'] - ); + assert_eq!(tester, [ + 'P', 'O', 'N', 'M', 'L', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K' + ]); // ABCDEFGHIJKPONML let expected_start = 0; diff --git a/library/alloc/src/ffi/c_str.rs b/library/alloc/src/ffi/c_str.rs index 45037aa1615b4..797d591a8b51a 100644 --- a/library/alloc/src/ffi/c_str.rs +++ b/library/alloc/src/ffi/c_str.rs @@ -4,7 +4,7 @@ mod tests; use core::borrow::Borrow; -use core::ffi::{c_char, CStr}; +use core::ffi::{CStr, c_char}; use core::num::NonZero; use core::slice::memchr; use core::str::{self, Utf8Error}; diff --git a/library/alloc/src/fmt.rs b/library/alloc/src/fmt.rs index 571fcd177aae7..3da71038a5e76 100644 --- a/library/alloc/src/fmt.rs +++ b/library/alloc/src/fmt.rs @@ -580,10 +580,8 @@ pub use core::fmt::Alignment; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::Error; -#[unstable(feature = "debug_closure_helpers", issue = "117729")] -pub use core::fmt::{from_fn, FromFn}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::fmt::{write, Arguments}; +pub use core::fmt::{Arguments, write}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Binary, Octal}; #[stable(feature = "rust1", since = "1.0.0")] @@ -592,6 +590,8 @@ pub use core::fmt::{Debug, Display}; pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Formatter, Result, Write}; +#[unstable(feature = "debug_closure_helpers", issue = "117729")] +pub use core::fmt::{FromFn, from_fn}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{LowerExp, UpperExp}; #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index f0597f295b3f0..ff5ddd16e07e3 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -93,6 +93,7 @@ // tidy-alphabetical-start #![cfg_attr(not(no_global_oom_handling), feature(const_alloc_error))] #![cfg_attr(not(no_global_oom_handling), feature(const_btree_len))] +#![cfg_attr(test, feature(str_as_str))] #![feature(alloc_layout_extra)] #![feature(allocator_api)] #![feature(array_chunks)] diff --git a/library/alloc/src/rc.rs b/library/alloc/src/rc.rs index b9a92749aaea8..54669bd310a68 100644 --- a/library/alloc/src/rc.rs +++ b/library/alloc/src/rc.rs @@ -251,13 +251,13 @@ use core::intrinsics::abort; #[cfg(not(no_global_oom_handling))] use core::iter; use core::marker::{PhantomData, Unsize}; -use core::mem::{self, align_of_val_raw, ManuallyDrop}; +use core::mem::{self, ManuallyDrop, align_of_val_raw}; use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, Receiver}; use core::panic::{RefUnwindSafe, UnwindSafe}; #[cfg(not(no_global_oom_handling))] use core::pin::Pin; use core::pin::PinCoerceUnsized; -use core::ptr::{self, drop_in_place, NonNull}; +use core::ptr::{self, NonNull, drop_in_place}; #[cfg(not(no_global_oom_handling))] use core::slice::from_raw_parts_mut; use core::{borrow, fmt, hint}; diff --git a/library/alloc/src/rc/tests.rs b/library/alloc/src/rc/tests.rs index 84e8b325f71fc..333e1bde31c1e 100644 --- a/library/alloc/src/rc/tests.rs +++ b/library/alloc/src/rc/tests.rs @@ -448,7 +448,11 @@ fn test_from_box_str() { use std::string::String; let s = String::from("foo").into_boxed_str(); + assert_eq!((&&&s).as_str(), "foo"); + let r: Rc = Rc::from(s); + assert_eq!((&r).as_str(), "foo"); + assert_eq!(r.as_str(), "foo"); assert_eq!(&r[..], "foo"); } diff --git a/library/alloc/src/slice.rs b/library/alloc/src/slice.rs index 45fb88969c696..f636f10d5c08c 100644 --- a/library/alloc/src/slice.rs +++ b/library/alloc/src/slice.rs @@ -43,14 +43,6 @@ pub use core::slice::ArrayWindows; pub use core::slice::EscapeAscii; #[stable(feature = "slice_get_slice", since = "1.28.0")] pub use core::slice::SliceIndex; -#[stable(feature = "from_ref", since = "1.28.0")] -pub use core::slice::{from_mut, from_ref}; -#[unstable(feature = "slice_from_ptr_range", issue = "89792")] -pub use core::slice::{from_mut_ptr_range, from_ptr_range}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::slice::{from_raw_parts, from_raw_parts_mut}; -#[unstable(feature = "slice_range", issue = "76393")] -pub use core::slice::{range, try_range}; #[stable(feature = "slice_group_by", since = "1.77.0")] pub use core::slice::{ChunkBy, ChunkByMut}; #[stable(feature = "rust1", since = "1.0.0")] @@ -69,6 +61,14 @@ pub use core::slice::{RSplit, RSplitMut}; pub use core::slice::{RSplitN, RSplitNMut, SplitN, SplitNMut}; #[stable(feature = "split_inclusive", since = "1.51.0")] pub use core::slice::{SplitInclusive, SplitInclusiveMut}; +#[stable(feature = "from_ref", since = "1.28.0")] +pub use core::slice::{from_mut, from_ref}; +#[unstable(feature = "slice_from_ptr_range", issue = "89792")] +pub use core::slice::{from_mut_ptr_range, from_ptr_range}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::slice::{from_raw_parts, from_raw_parts_mut}; +#[unstable(feature = "slice_range", issue = "76393")] +pub use core::slice::{range, try_range}; //////////////////////////////////////////////////////////////////////////////// // Basic slice extension methods diff --git a/library/alloc/src/str.rs b/library/alloc/src/str.rs index d7fba3ae159c6..32212b61c6e87 100644 --- a/library/alloc/src/str.rs +++ b/library/alloc/src/str.rs @@ -9,9 +9,6 @@ use core::borrow::{Borrow, BorrowMut}; use core::iter::FusedIterator; -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::str::pattern; -use core::str::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; #[stable(feature = "encode_utf16", since = "1.8.0")] pub use core::str::EncodeUtf16; #[stable(feature = "split_ascii_whitespace", since = "1.34.0")] @@ -20,12 +17,11 @@ pub use core::str::SplitAsciiWhitespace; pub use core::str::SplitInclusive; #[stable(feature = "rust1", since = "1.0.0")] pub use core::str::SplitWhitespace; -#[unstable(feature = "str_from_raw_parts", issue = "119206")] -pub use core::str::{from_raw_parts, from_raw_parts_mut}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::str::{from_utf8, from_utf8_mut, Bytes, CharIndices, Chars}; +pub use core::str::pattern; +use core::str::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::str::{from_utf8_unchecked, from_utf8_unchecked_mut, ParseBoolError}; +pub use core::str::{Bytes, CharIndices, Chars, from_utf8, from_utf8_mut}; #[stable(feature = "str_escape", since = "1.34.0")] pub use core::str::{EscapeDebug, EscapeDefault, EscapeUnicode}; #[stable(feature = "rust1", since = "1.0.0")] @@ -38,6 +34,8 @@ pub use core::str::{MatchIndices, RMatchIndices}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::str::{Matches, RMatches}; #[stable(feature = "rust1", since = "1.0.0")] +pub use core::str::{ParseBoolError, from_utf8_unchecked, from_utf8_unchecked_mut}; +#[stable(feature = "rust1", since = "1.0.0")] pub use core::str::{RSplit, Split}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::str::{RSplitN, SplitN}; @@ -45,6 +43,8 @@ pub use core::str::{RSplitN, SplitN}; pub use core::str::{RSplitTerminator, SplitTerminator}; #[stable(feature = "utf8_chunks", since = "1.79.0")] pub use core::str::{Utf8Chunk, Utf8Chunks}; +#[unstable(feature = "str_from_raw_parts", issue = "119206")] +pub use core::str::{from_raw_parts, from_raw_parts_mut}; use core::unicode::conversions; use core::{mem, ptr}; diff --git a/library/alloc/src/string.rs b/library/alloc/src/string.rs index 8397735083211..ee878e879e98a 100644 --- a/library/alloc/src/string.rs +++ b/library/alloc/src/string.rs @@ -43,9 +43,9 @@ #![stable(feature = "rust1", since = "1.0.0")] use core::error::Error; +use core::iter::FusedIterator; #[cfg(not(no_global_oom_handling))] use core::iter::from_fn; -use core::iter::FusedIterator; #[cfg(not(no_global_oom_handling))] use core::ops::Add; #[cfg(not(no_global_oom_handling))] @@ -62,9 +62,9 @@ use crate::alloc::Allocator; use crate::borrow::{Cow, ToOwned}; use crate::boxed::Box; use crate::collections::TryReserveError; -use crate::str::{self, from_utf8_unchecked_mut, Chars, Utf8Error}; +use crate::str::{self, Chars, Utf8Error, from_utf8_unchecked_mut}; #[cfg(not(no_global_oom_handling))] -use crate::str::{from_boxed_utf8_unchecked, FromStr}; +use crate::str::{FromStr, from_boxed_utf8_unchecked}; use crate::vec::Vec; /// A UTF-8–encoded, growable string. diff --git a/library/alloc/src/sync.rs b/library/alloc/src/sync.rs index 4d4e84bfda587..50886244d582c 100644 --- a/library/alloc/src/sync.rs +++ b/library/alloc/src/sync.rs @@ -17,7 +17,7 @@ use core::intrinsics::abort; #[cfg(not(no_global_oom_handling))] use core::iter; use core::marker::{PhantomData, Unsize}; -use core::mem::{self, align_of_val_raw, ManuallyDrop}; +use core::mem::{self, ManuallyDrop, align_of_val_raw}; use core::ops::{CoerceUnsized, Deref, DerefPure, DispatchFromDyn, Receiver}; use core::panic::{RefUnwindSafe, UnwindSafe}; use core::pin::{Pin, PinCoerceUnsized}; diff --git a/library/alloc/src/sync/tests.rs b/library/alloc/src/sync/tests.rs index d6b3de875771e..3f66c88992344 100644 --- a/library/alloc/src/sync/tests.rs +++ b/library/alloc/src/sync/tests.rs @@ -1,10 +1,10 @@ use std::clone::Clone; use std::mem::MaybeUninit; use std::option::Option::None; +use std::sync::Mutex; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering::SeqCst; use std::sync::mpsc::channel; -use std::sync::Mutex; use std::thread; use super::*; diff --git a/library/alloc/src/vec/in_place_collect.rs b/library/alloc/src/vec/in_place_collect.rs index 23dbc3b63f9e7..fd94bbbdeb17c 100644 --- a/library/alloc/src/vec/in_place_collect.rs +++ b/library/alloc/src/vec/in_place_collect.rs @@ -163,7 +163,7 @@ use core::num::NonZero; use core::ptr; use super::{InPlaceDrop, InPlaceDstDataSrcBufDrop, SpecFromIter, SpecFromIterNested, Vec}; -use crate::alloc::{handle_alloc_error, Global}; +use crate::alloc::{Global, handle_alloc_error}; const fn in_place_collectible( step_merge: Option>, diff --git a/library/alloc/src/vec/in_place_drop.rs b/library/alloc/src/vec/in_place_drop.rs index 27f7597931045..4d5b4e47d39e4 100644 --- a/library/alloc/src/vec/in_place_drop.rs +++ b/library/alloc/src/vec/in_place_drop.rs @@ -1,5 +1,5 @@ use core::marker::PhantomData; -use core::ptr::{self, drop_in_place, NonNull}; +use core::ptr::{self, NonNull, drop_in_place}; use core::slice::{self}; use crate::alloc::Global; diff --git a/library/alloc/tests/slice.rs b/library/alloc/tests/slice.rs index df5a8af16fd70..9625e3d2b5e08 100644 --- a/library/alloc/tests/slice.rs +++ b/library/alloc/tests/slice.rs @@ -1417,8 +1417,8 @@ fn test_box_slice_clone() { #[cfg_attr(target_os = "emscripten", ignore)] #[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")] fn test_box_slice_clone_panics() { - use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; struct Canary { count: Arc, diff --git a/library/alloc/tests/str.rs b/library/alloc/tests/str.rs index a6b1fe5b97945..a80e5275dab60 100644 --- a/library/alloc/tests/str.rs +++ b/library/alloc/tests/str.rs @@ -1524,14 +1524,18 @@ fn test_lines() { t("bare\r", &["bare\r"]); t("bare\rcr", &["bare\rcr"]); t("Text\n\r", &["Text", "\r"]); - t( - "\nMäry häd ä little lämb\n\r\nLittle lämb\n", - &["", "Märy häd ä little lämb", "", "Little lämb"], - ); - t( - "\r\nMäry häd ä little lämb\n\nLittle lämb", - &["", "Märy häd ä little lämb", "", "Little lämb"], - ); + t("\nMäry häd ä little lämb\n\r\nLittle lämb\n", &[ + "", + "Märy häd ä little lämb", + "", + "Little lämb", + ]); + t("\r\nMäry häd ä little lämb\n\nLittle lämb", &[ + "", + "Märy häd ä little lämb", + "", + "Little lämb", + ]); } #[test] @@ -1971,88 +1975,73 @@ mod pattern { assert_eq!(v, right); } - make_test!( - str_searcher_ascii_haystack, - "bb", - "abbcbbd", - [Reject(0, 1), Match(1, 3), Reject(3, 4), Match(4, 6), Reject(6, 7),] - ); - make_test!( - str_searcher_ascii_haystack_seq, - "bb", - "abbcbbbbd", - [Reject(0, 1), Match(1, 3), Reject(3, 4), Match(4, 6), Match(6, 8), Reject(8, 9),] - ); - make_test!( - str_searcher_empty_needle_ascii_haystack, - "", - "abbcbbd", - [ - Match(0, 0), - Reject(0, 1), - Match(1, 1), - Reject(1, 2), - Match(2, 2), - Reject(2, 3), - Match(3, 3), - Reject(3, 4), - Match(4, 4), - Reject(4, 5), - Match(5, 5), - Reject(5, 6), - Match(6, 6), - Reject(6, 7), - Match(7, 7), - ] - ); - make_test!( - str_searcher_multibyte_haystack, - " ", - "├──", - [Reject(0, 3), Reject(3, 6), Reject(6, 9),] - ); - make_test!( - str_searcher_empty_needle_multibyte_haystack, - "", - "├──", - [ - Match(0, 0), - Reject(0, 3), - Match(3, 3), - Reject(3, 6), - Match(6, 6), - Reject(6, 9), - Match(9, 9), - ] - ); + make_test!(str_searcher_ascii_haystack, "bb", "abbcbbd", [ + Reject(0, 1), + Match(1, 3), + Reject(3, 4), + Match(4, 6), + Reject(6, 7), + ]); + make_test!(str_searcher_ascii_haystack_seq, "bb", "abbcbbbbd", [ + Reject(0, 1), + Match(1, 3), + Reject(3, 4), + Match(4, 6), + Match(6, 8), + Reject(8, 9), + ]); + make_test!(str_searcher_empty_needle_ascii_haystack, "", "abbcbbd", [ + Match(0, 0), + Reject(0, 1), + Match(1, 1), + Reject(1, 2), + Match(2, 2), + Reject(2, 3), + Match(3, 3), + Reject(3, 4), + Match(4, 4), + Reject(4, 5), + Match(5, 5), + Reject(5, 6), + Match(6, 6), + Reject(6, 7), + Match(7, 7), + ]); + make_test!(str_searcher_multibyte_haystack, " ", "├──", [ + Reject(0, 3), + Reject(3, 6), + Reject(6, 9), + ]); + make_test!(str_searcher_empty_needle_multibyte_haystack, "", "├──", [ + Match(0, 0), + Reject(0, 3), + Match(3, 3), + Reject(3, 6), + Match(6, 6), + Reject(6, 9), + Match(9, 9), + ]); make_test!(str_searcher_empty_needle_empty_haystack, "", "", [Match(0, 0),]); make_test!(str_searcher_nonempty_needle_empty_haystack, "├", "", []); - make_test!( - char_searcher_ascii_haystack, - 'b', - "abbcbbd", - [ - Reject(0, 1), - Match(1, 2), - Match(2, 3), - Reject(3, 4), - Match(4, 5), - Match(5, 6), - Reject(6, 7), - ] - ); - make_test!( - char_searcher_multibyte_haystack, - ' ', - "├──", - [Reject(0, 3), Reject(3, 6), Reject(6, 9),] - ); - make_test!( - char_searcher_short_haystack, - '\u{1F4A9}', - "* \t", - [Reject(0, 1), Reject(1, 2), Reject(2, 3),] - ); + make_test!(char_searcher_ascii_haystack, 'b', "abbcbbd", [ + Reject(0, 1), + Match(1, 2), + Match(2, 3), + Reject(3, 4), + Match(4, 5), + Match(5, 6), + Reject(6, 7), + ]); + make_test!(char_searcher_multibyte_haystack, ' ', "├──", [ + Reject(0, 3), + Reject(3, 6), + Reject(6, 9), + ]); + make_test!(char_searcher_short_haystack, '\u{1F4A9}', "* \t", [ + Reject(0, 1), + Reject(1, 2), + Reject(2, 3), + ]); // See #85462 #[test] diff --git a/library/alloc/tests/string.rs b/library/alloc/tests/string.rs index d996c55f94660..1c8bff1564db2 100644 --- a/library/alloc/tests/string.rs +++ b/library/alloc/tests/string.rs @@ -154,28 +154,19 @@ fn test_fromutf8error_into_lossy() { #[test] fn test_from_utf16() { let pairs = [ - ( - String::from("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"), - vec![ - 0xd800, 0xdf45, 0xd800, 0xdf3f, 0xd800, 0xdf3b, 0xd800, 0xdf46, 0xd800, 0xdf39, - 0xd800, 0xdf3b, 0xd800, 0xdf30, 0x000a, - ], - ), - ( - String::from("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"), - vec![ - 0xd801, 0xdc12, 0xd801, 0xdc49, 0xd801, 0xdc2e, 0xd801, 0xdc40, 0xd801, 0xdc32, - 0xd801, 0xdc4b, 0x0020, 0xd801, 0xdc0f, 0xd801, 0xdc32, 0xd801, 0xdc4d, 0x000a, - ], - ), - ( - String::from("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"), - vec![ - 0xd800, 0xdf00, 0xd800, 0xdf16, 0xd800, 0xdf0b, 0xd800, 0xdf04, 0xd800, 0xdf11, - 0xd800, 0xdf09, 0x00b7, 0xd800, 0xdf0c, 0xd800, 0xdf04, 0xd800, 0xdf15, 0xd800, - 0xdf04, 0xd800, 0xdf0b, 0xd800, 0xdf09, 0xd800, 0xdf11, 0x000a, - ], - ), + (String::from("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"), vec![ + 0xd800, 0xdf45, 0xd800, 0xdf3f, 0xd800, 0xdf3b, 0xd800, 0xdf46, 0xd800, 0xdf39, 0xd800, + 0xdf3b, 0xd800, 0xdf30, 0x000a, + ]), + (String::from("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"), vec![ + 0xd801, 0xdc12, 0xd801, 0xdc49, 0xd801, 0xdc2e, 0xd801, 0xdc40, 0xd801, 0xdc32, 0xd801, + 0xdc4b, 0x0020, 0xd801, 0xdc0f, 0xd801, 0xdc32, 0xd801, 0xdc4d, 0x000a, + ]), + (String::from("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"), vec![ + 0xd800, 0xdf00, 0xd800, 0xdf16, 0xd800, 0xdf0b, 0xd800, 0xdf04, 0xd800, 0xdf11, 0xd800, + 0xdf09, 0x00b7, 0xd800, 0xdf0c, 0xd800, 0xdf04, 0xd800, 0xdf15, 0xd800, 0xdf04, 0xd800, + 0xdf0b, 0xd800, 0xdf09, 0xd800, 0xdf11, 0x000a, + ]), ( String::from("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"), vec![ diff --git a/library/alloc/tests/vec.rs b/library/alloc/tests/vec.rs index cf2ca4f0d657c..f508a3e4c22e2 100644 --- a/library/alloc/tests/vec.rs +++ b/library/alloc/tests/vec.rs @@ -14,7 +14,7 @@ use std::fmt::Debug; use std::iter::InPlaceIterable; use std::mem::{size_of, swap}; use std::ops::Bound::*; -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::rc::Rc; use std::sync::atomic::{AtomicU32, Ordering}; use std::vec::{Drain, IntoIter}; diff --git a/library/alloc/tests/vec_deque.rs b/library/alloc/tests/vec_deque.rs index 0891d99fe666b..4b8d3c735f72b 100644 --- a/library/alloc/tests/vec_deque.rs +++ b/library/alloc/tests/vec_deque.rs @@ -3,12 +3,12 @@ use core::num::NonZero; use std::assert_matches::assert_matches; -use std::collections::vec_deque::Drain; use std::collections::TryReserveErrorKind::*; use std::collections::VecDeque; +use std::collections::vec_deque::Drain; use std::fmt::Debug; use std::ops::Bound::*; -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use Taggy::*; use Taggypar::*; diff --git a/library/alloc/tests/vec_deque_alloc_error.rs b/library/alloc/tests/vec_deque_alloc_error.rs index c41d8266eb457..21a9118a05bd6 100644 --- a/library/alloc/tests/vec_deque_alloc_error.rs +++ b/library/alloc/tests/vec_deque_alloc_error.rs @@ -1,8 +1,8 @@ #![feature(alloc_error_hook, allocator_api)] -use std::alloc::{set_alloc_error_hook, AllocError, Allocator, Layout, System}; +use std::alloc::{AllocError, Allocator, Layout, System, set_alloc_error_hook}; use std::collections::VecDeque; -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::ptr::NonNull; #[test] diff --git a/library/core/benches/any.rs b/library/core/benches/any.rs index f6be41bcdbfa7..6b150432f874d 100644 --- a/library/core/benches/any.rs +++ b/library/core/benches/any.rs @@ -1,6 +1,6 @@ use core::any::*; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn bench_downcast_ref(b: &mut Bencher) { diff --git a/library/core/benches/array.rs b/library/core/benches/array.rs index b1a41a088c493..751f3235a5f34 100644 --- a/library/core/benches/array.rs +++ b/library/core/benches/array.rs @@ -1,4 +1,4 @@ -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; macro_rules! map_array { ($func_name:ident, $start_item: expr, $map_item: expr, $arr_size: expr) => { diff --git a/library/core/benches/ascii.rs b/library/core/benches/ascii.rs index 61bf8bbf411d5..3fe45aa360bf0 100644 --- a/library/core/benches/ascii.rs +++ b/library/core/benches/ascii.rs @@ -65,7 +65,7 @@ macro_rules! benches { use std::fmt::Write; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; const ASCII_CASE_MASK: u8 = 0b0010_0000; diff --git a/library/core/benches/ascii/is_ascii.rs b/library/core/benches/ascii/is_ascii.rs index 05f60a46f8be2..4b2920c5eb45f 100644 --- a/library/core/benches/ascii/is_ascii.rs +++ b/library/core/benches/ascii/is_ascii.rs @@ -1,4 +1,4 @@ -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; use super::{LONG, MEDIUM, SHORT}; diff --git a/library/core/benches/char/methods.rs b/library/core/benches/char/methods.rs index 5d4df1ac8bd58..ed71920a4fc2a 100644 --- a/library/core/benches/char/methods.rs +++ b/library/core/benches/char/methods.rs @@ -1,4 +1,4 @@ -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; const CHARS: [char; 9] = ['0', 'x', '2', '5', 'A', 'f', '7', '8', '9']; const RADIX: [u32; 5] = [2, 8, 10, 16, 32]; diff --git a/library/core/benches/fmt.rs b/library/core/benches/fmt.rs index 906d7ac3eef28..4baefd5578808 100644 --- a/library/core/benches/fmt.rs +++ b/library/core/benches/fmt.rs @@ -1,7 +1,7 @@ use std::fmt::{self, Write as FmtWrite}; use std::io::{self, Write as IoWrite}; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn write_vec_value(bh: &mut Bencher) { diff --git a/library/core/benches/hash/sip.rs b/library/core/benches/hash/sip.rs index 8e8c07b6ee4c3..c6562d3c01187 100644 --- a/library/core/benches/hash/sip.rs +++ b/library/core/benches/hash/sip.rs @@ -2,7 +2,7 @@ use core::hash::*; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; fn hash_bytes(mut s: H, x: &[u8]) -> u64 { Hasher::write(&mut s, x); diff --git a/library/core/benches/iter.rs b/library/core/benches/iter.rs index 24469ba0c4262..e14f26b729032 100644 --- a/library/core/benches/iter.rs +++ b/library/core/benches/iter.rs @@ -4,7 +4,7 @@ use core::mem; use core::num::Wrapping; use core::ops::Range; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn bench_rposition(b: &mut Bencher) { diff --git a/library/core/benches/net/addr_parser.rs b/library/core/benches/net/addr_parser.rs index b9406a9779dc6..bbf2ea3eb9796 100644 --- a/library/core/benches/net/addr_parser.rs +++ b/library/core/benches/net/addr_parser.rs @@ -1,7 +1,7 @@ use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; use core::str::FromStr; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; const IPV4_STR: &str = "192.168.0.1"; const IPV4_STR_PORT: &str = "192.168.0.1:8080"; diff --git a/library/core/benches/num/dec2flt/mod.rs b/library/core/benches/num/dec2flt/mod.rs index fb4a786b27e3d..bad211f240ca1 100644 --- a/library/core/benches/num/dec2flt/mod.rs +++ b/library/core/benches/num/dec2flt/mod.rs @@ -1,4 +1,4 @@ -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn bench_0(b: &mut Bencher) { diff --git a/library/core/benches/num/flt2dec/mod.rs b/library/core/benches/num/flt2dec/mod.rs index 6c7de5dcd2286..428d0bbbbfbfa 100644 --- a/library/core/benches/num/flt2dec/mod.rs +++ b/library/core/benches/num/flt2dec/mod.rs @@ -3,10 +3,10 @@ mod strategy { mod grisu; } -use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded, MAX_SIG_DIGITS}; +use core::num::flt2dec::{DecodableFloat, Decoded, FullDecoded, MAX_SIG_DIGITS, decode}; use std::io::Write; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; pub fn decode_finite(v: T) -> Decoded { match decode(v).1 { diff --git a/library/core/benches/num/int_log/mod.rs b/library/core/benches/num/int_log/mod.rs index 3807cd5d76cfc..e5874ddf03b5b 100644 --- a/library/core/benches/num/int_log/mod.rs +++ b/library/core/benches/num/int_log/mod.rs @@ -1,5 +1,5 @@ use rand::Rng; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; macro_rules! int_log10_bench { ($t:ty, $predictable:ident, $random:ident, $random_small:ident) => { diff --git a/library/core/benches/num/int_pow/mod.rs b/library/core/benches/num/int_pow/mod.rs index 063d722bdd1b5..6cf9021358283 100644 --- a/library/core/benches/num/int_pow/mod.rs +++ b/library/core/benches/num/int_pow/mod.rs @@ -1,5 +1,5 @@ use rand::Rng; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; const ITERATIONS: usize = 128; // Uses an ITERATIONS * 20 Byte stack allocation type IntType = i128; // Hardest native type to multiply diff --git a/library/core/benches/num/int_sqrt/mod.rs b/library/core/benches/num/int_sqrt/mod.rs index 3c9d173e456a1..e47b92e866eff 100644 --- a/library/core/benches/num/int_sqrt/mod.rs +++ b/library/core/benches/num/int_sqrt/mod.rs @@ -1,5 +1,5 @@ use rand::Rng; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; macro_rules! int_sqrt_bench { ($t:ty, $predictable:ident, $random:ident, $random_small:ident, $random_uniform:ident) => { diff --git a/library/core/benches/num/mod.rs b/library/core/benches/num/mod.rs index 7ff7443cfa7fe..b36100e59a97a 100644 --- a/library/core/benches/num/mod.rs +++ b/library/core/benches/num/mod.rs @@ -6,7 +6,7 @@ mod int_sqrt; use std::str::FromStr; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; const ASCII_NUMBERS: [&str; 19] = [ "0", diff --git a/library/core/benches/pattern.rs b/library/core/benches/pattern.rs index 0d60b005feb32..b0f8b39c22e16 100644 --- a/library/core/benches/pattern.rs +++ b/library/core/benches/pattern.rs @@ -1,4 +1,4 @@ -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn starts_with_char(b: &mut Bencher) { diff --git a/library/core/benches/slice.rs b/library/core/benches/slice.rs index 2741dbd53f14c..29a66b6219976 100644 --- a/library/core/benches/slice.rs +++ b/library/core/benches/slice.rs @@ -1,6 +1,6 @@ use core::ptr::NonNull; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; enum Cache { L1, diff --git a/library/core/benches/str.rs b/library/core/benches/str.rs index a8178f9c18752..2f7d9d56a70b7 100644 --- a/library/core/benches/str.rs +++ b/library/core/benches/str.rs @@ -1,6 +1,6 @@ use std::str; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; mod char_count; mod corpora; diff --git a/library/core/benches/str/char_count.rs b/library/core/benches/str/char_count.rs index b87ad0f6adf24..343e23dcf41c5 100644 --- a/library/core/benches/str/char_count.rs +++ b/library/core/benches/str/char_count.rs @@ -1,4 +1,4 @@ -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; use super::corpora::*; diff --git a/library/core/benches/str/debug.rs b/library/core/benches/str/debug.rs index 6dbf4e92c084b..e41d4fa110a63 100644 --- a/library/core/benches/str/debug.rs +++ b/library/core/benches/str/debug.rs @@ -5,7 +5,7 @@ use std::fmt::{self, Write}; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[derive(Default)] struct CountingWriter { diff --git a/library/core/benches/str/iter.rs b/library/core/benches/str/iter.rs index f6e73e48d8e7d..d2586cef25871 100644 --- a/library/core/benches/str/iter.rs +++ b/library/core/benches/str/iter.rs @@ -1,4 +1,4 @@ -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; use super::corpora; diff --git a/library/core/benches/tuple.rs b/library/core/benches/tuple.rs index d9ff9d0dd9378..dcda7c641aa21 100644 --- a/library/core/benches/tuple.rs +++ b/library/core/benches/tuple.rs @@ -1,5 +1,5 @@ use rand::prelude::*; -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; #[bench] fn bench_tuple_comparison(b: &mut Bencher) { diff --git a/library/core/src/array/mod.rs b/library/core/src/array/mod.rs index c63f261edabfa..24c42bc85dd91 100644 --- a/library/core/src/array/mod.rs +++ b/library/core/src/array/mod.rs @@ -10,7 +10,7 @@ use crate::convert::Infallible; use crate::error::Error; use crate::fmt; use crate::hash::{self, Hash}; -use crate::iter::{repeat_n, UncheckedIterator}; +use crate::iter::{UncheckedIterator, repeat_n}; use crate::mem::{self, MaybeUninit}; use crate::ops::{ ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try, diff --git a/library/core/src/async_iter/mod.rs b/library/core/src/async_iter/mod.rs index e1f1c9075823d..a5b03b7dd4f14 100644 --- a/library/core/src/async_iter/mod.rs +++ b/library/core/src/async_iter/mod.rs @@ -125,4 +125,4 @@ mod async_iter; mod from_iter; pub use async_iter::{AsyncIterator, IntoAsyncIterator}; -pub use from_iter::{from_iter, FromIter}; +pub use from_iter::{FromIter, from_iter}; diff --git a/library/core/src/cell.rs b/library/core/src/cell.rs index a3a471a57c7aa..a3e91bc067090 100644 --- a/library/core/src/cell.rs +++ b/library/core/src/cell.rs @@ -1577,10 +1577,10 @@ impl<'b, T: ?Sized> Ref<'b, T> { { let (a, b) = f(&*orig); let borrow = orig.borrow.clone(); - ( - Ref { value: NonNull::from(a), borrow }, - Ref { value: NonNull::from(b), borrow: orig.borrow }, - ) + (Ref { value: NonNull::from(a), borrow }, Ref { + value: NonNull::from(b), + borrow: orig.borrow, + }) } /// Converts into a reference to the underlying data. @@ -1745,10 +1745,11 @@ impl<'b, T: ?Sized> RefMut<'b, T> { { let borrow = orig.borrow.clone(); let (a, b) = f(&mut *orig); - ( - RefMut { value: NonNull::from(a), borrow, marker: PhantomData }, - RefMut { value: NonNull::from(b), borrow: orig.borrow, marker: PhantomData }, - ) + (RefMut { value: NonNull::from(a), borrow, marker: PhantomData }, RefMut { + value: NonNull::from(b), + borrow: orig.borrow, + marker: PhantomData, + }) } /// Converts into a mutable reference to the underlying data. diff --git a/library/core/src/char/methods.rs b/library/core/src/char/methods.rs index 092d427eceae7..55e67e5c255e9 100644 --- a/library/core/src/char/methods.rs +++ b/library/core/src/char/methods.rs @@ -606,6 +606,7 @@ impl char { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")] #[inline] + #[must_use] pub const fn len_utf8(self) -> usize { len_utf8(self as u32) } @@ -637,9 +638,9 @@ impl char { #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_char_len_utf", since = "1.52.0")] #[inline] + #[must_use] pub const fn len_utf16(self) -> usize { - let ch = self as u32; - if (ch & 0xFFFF) == ch { 1 } else { 2 } + len_utf16(self as u32) } /// Encodes this character as UTF-8 into the provided byte buffer, @@ -709,8 +710,9 @@ impl char { /// '𝕊'.encode_utf16(&mut b); /// ``` #[stable(feature = "unicode_encode_char", since = "1.15.0")] + #[rustc_const_unstable(feature = "const_char_encode_utf16", issue = "130660")] #[inline] - pub fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] { + pub const fn encode_utf16(self, dst: &mut [u16]) -> &mut [u16] { encode_utf16_raw(self as u32, dst) } @@ -1279,8 +1281,9 @@ impl char { /// /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] + #[rustc_const_unstable(feature = "const_make_ascii", issue = "130698")] #[inline] - pub fn make_ascii_uppercase(&mut self) { + pub const fn make_ascii_uppercase(&mut self) { *self = self.to_ascii_uppercase(); } @@ -1304,8 +1307,9 @@ impl char { /// /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] + #[rustc_const_unstable(feature = "const_make_ascii", issue = "130698")] #[inline] - pub fn make_ascii_lowercase(&mut self) { + pub const fn make_ascii_lowercase(&mut self) { *self = self.to_ascii_lowercase(); } @@ -1736,6 +1740,7 @@ impl EscapeDebugExtArgs { } #[inline] +#[must_use] const fn len_utf8(code: u32) -> usize { match code { ..MAX_ONE_B => 1, @@ -1745,7 +1750,13 @@ const fn len_utf8(code: u32) -> usize { } } -/// Encodes a raw u32 value as UTF-8 into the provided byte buffer, +#[inline] +#[must_use] +const fn len_utf16(code: u32) -> usize { + if (code & 0xFFFF) == code { 1 } else { 2 } +} + +/// Encodes a raw `u32` value as UTF-8 into the provided byte buffer, /// and then returns the subslice of the buffer that contains the encoded character. /// /// Unlike `char::encode_utf8`, this method also handles codepoints in the surrogate range. @@ -1799,7 +1810,7 @@ pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] { unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) } } -/// Encodes a raw u32 value as UTF-16 into the provided `u16` buffer, +/// Encodes a raw `u32` value as UTF-16 into the provided `u16` buffer, /// and then returns the subslice of the buffer that contains the encoded character. /// /// Unlike `char::encode_utf16`, this method also handles codepoints in the surrogate range. @@ -1810,28 +1821,33 @@ pub const fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> &mut [u8] { /// Panics if the buffer is not large enough. /// A buffer of length 2 is large enough to encode any `char`. #[unstable(feature = "char_internals", reason = "exposed only for libstd", issue = "none")] +#[rustc_const_unstable(feature = "const_char_encode_utf16", issue = "130660")] #[doc(hidden)] #[inline] -pub fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] { - // SAFETY: each arm checks whether there are enough bits to write into - unsafe { - if (code & 0xFFFF) == code && !dst.is_empty() { - // The BMP falls through - *dst.get_unchecked_mut(0) = code as u16; - slice::from_raw_parts_mut(dst.as_mut_ptr(), 1) - } else if dst.len() >= 2 { - // Supplementary planes break into surrogates. +pub const fn encode_utf16_raw(mut code: u32, dst: &mut [u16]) -> &mut [u16] { + const fn panic_at_const(_code: u32, _len: usize, _dst_len: usize) { + // Note that we cannot format in constant expressions. + panic!("encode_utf16: buffer does not have enough bytes to encode code point"); + } + fn panic_at_rt(code: u32, len: usize, dst_len: usize) { + panic!( + "encode_utf16: need {len} bytes to encode U+{code:04X} but buffer has just {dst_len}", + ); + } + let len = len_utf16(code); + match (len, &mut *dst) { + (1, [a, ..]) => { + *a = code as u16; + } + (2, [a, b, ..]) => { code -= 0x1_0000; - *dst.get_unchecked_mut(0) = 0xD800 | ((code >> 10) as u16); - *dst.get_unchecked_mut(1) = 0xDC00 | ((code as u16) & 0x3FF); - slice::from_raw_parts_mut(dst.as_mut_ptr(), 2) - } else { - panic!( - "encode_utf16: need {} units to encode U+{:X}, but the buffer has {}", - char::from_u32_unchecked(code).len_utf16(), - code, - dst.len(), - ) + + *a = (code >> 10) as u16 | 0xD800; + *b = (code & 0x3FF) as u16 | 0xDC00; } - } + // FIXME(const-hack): We would prefer to have streamlined panics when formatters become const-friendly. + _ => const_eval_select((code, len, dst.len()), panic_at_const, panic_at_rt), + }; + // SAFETY: `<&mut [u16]>::as_mut_ptr` is guaranteed to return a valid pointer and `len` has been tested to be within bounds. + unsafe { slice::from_raw_parts_mut(dst.as_mut_ptr(), len) } } diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index 7808d42ab5de4..930f8a7662079 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -5,7 +5,7 @@ use crate::error::Error; use crate::ffi::c_char; use crate::iter::FusedIterator; use crate::marker::PhantomData; -use crate::ptr::{addr_of, NonNull}; +use crate::ptr::{NonNull, addr_of}; use crate::slice::memchr; use crate::{fmt, intrinsics, ops, slice, str}; diff --git a/library/core/src/fmt/mod.rs b/library/core/src/fmt/mod.rs index 8fc43cb1875e3..4cbcfb07795bd 100644 --- a/library/core/src/fmt/mod.rs +++ b/library/core/src/fmt/mod.rs @@ -33,10 +33,10 @@ pub enum Alignment { Center, } -#[unstable(feature = "debug_closure_helpers", issue = "117729")] -pub use self::builders::{from_fn, FromFn}; #[stable(feature = "debug_builders", since = "1.2.0")] pub use self::builders::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; +#[unstable(feature = "debug_closure_helpers", issue = "117729")] +pub use self::builders::{FromFn, from_fn}; /// The type returned by formatter methods. /// diff --git a/library/core/src/future/async_drop.rs b/library/core/src/future/async_drop.rs index 16ac77fa15045..7de5fe67cd096 100644 --- a/library/core/src/future/async_drop.rs +++ b/library/core/src/future/async_drop.rs @@ -6,7 +6,7 @@ use crate::intrinsics::discriminant_value; use crate::marker::{DiscriminantKind, PhantomPinned}; use crate::mem::MaybeUninit; use crate::pin::Pin; -use crate::task::{ready, Context, Poll}; +use crate::task::{Context, Poll, ready}; /// Asynchronously drops a value by running `AsyncDrop::async_drop` /// on a value and its fields recursively. diff --git a/library/core/src/future/join.rs b/library/core/src/future/join.rs index 3f35179ddc29b..18bc8d9658678 100644 --- a/library/core/src/future/join.rs +++ b/library/core/src/future/join.rs @@ -1,10 +1,10 @@ #![allow(unused_imports, unused_macros)] // items are used by the macro use crate::cell::UnsafeCell; -use crate::future::{poll_fn, Future}; +use crate::future::{Future, poll_fn}; use crate::mem; use crate::pin::Pin; -use crate::task::{ready, Context, Poll}; +use crate::task::{Context, Poll, ready}; /// Polls multiple futures simultaneously, returning a tuple /// of all results once complete. diff --git a/library/core/src/future/mod.rs b/library/core/src/future/mod.rs index d188f1c713079..e5a368796ec93 100644 --- a/library/core/src/future/mod.rs +++ b/library/core/src/future/mod.rs @@ -21,15 +21,15 @@ mod poll_fn; mod ready; #[unstable(feature = "async_drop", issue = "126482")] -pub use async_drop::{async_drop, async_drop_in_place, AsyncDrop, AsyncDropInPlace}; +pub use async_drop::{AsyncDrop, AsyncDropInPlace, async_drop, async_drop_in_place}; #[stable(feature = "into_future", since = "1.64.0")] pub use into_future::IntoFuture; #[stable(feature = "future_readiness_fns", since = "1.48.0")] -pub use pending::{pending, Pending}; +pub use pending::{Pending, pending}; #[stable(feature = "future_poll_fn", since = "1.64.0")] -pub use poll_fn::{poll_fn, PollFn}; +pub use poll_fn::{PollFn, poll_fn}; #[stable(feature = "future_readiness_fns", since = "1.48.0")] -pub use ready::{ready, Ready}; +pub use ready::{Ready, ready}; #[stable(feature = "futures_api", since = "1.36.0")] pub use self::future::Future; diff --git a/library/core/src/intrinsics.rs b/library/core/src/intrinsics.rs index 7870a62ea81cd..881a89f4d1091 100644 --- a/library/core/src/intrinsics.rs +++ b/library/core/src/intrinsics.rs @@ -2733,7 +2733,7 @@ extern "rust-intrinsic" { /// Lexicographically compare `[left, left + bytes)` and `[right, right + bytes)` /// as unsigned bytes, returning negative if `left` is less, zero if all the - /// bytes match, or positive if `right` is greater. + /// bytes match, or positive if `left` is greater. /// /// This underlies things like `<[u8]>::cmp`, and will usually lower to `memcmp`. /// @@ -3286,13 +3286,13 @@ pub const fn ptr_metadata + ?Sized, M>(_ptr: *cons #[doc(alias = "memcpy")] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_allowed_through_unstable_modules] -#[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] +#[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_diagnostic_item = "ptr_copy_nonoverlapping"] pub const unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize) { extern "rust-intrinsic" { - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[rustc_nounwind] pub fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); } @@ -3388,13 +3388,13 @@ pub const unsafe fn copy_nonoverlapping(src: *const T, dst: *mut T, count: us #[doc(alias = "memmove")] #[stable(feature = "rust1", since = "1.0.0")] #[rustc_allowed_through_unstable_modules] -#[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] +#[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_diagnostic_item = "ptr_copy"] pub const unsafe fn copy(src: *const T, dst: *mut T, count: usize) { extern "rust-intrinsic" { - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[rustc_nounwind] fn copy(src: *const T, dst: *mut T, count: usize); } diff --git a/library/core/src/iter/adapters/fuse.rs b/library/core/src/iter/adapters/fuse.rs index 7781ed088b76c..e9765f911a252 100644 --- a/library/core/src/iter/adapters/fuse.rs +++ b/library/core/src/iter/adapters/fuse.rs @@ -1,6 +1,6 @@ use crate::intrinsics; -use crate::iter::adapters::zip::try_get_unchecked; use crate::iter::adapters::SourceIter; +use crate::iter::adapters::zip::try_get_unchecked; use crate::iter::{ FusedIterator, TrustedFused, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, }; diff --git a/library/core/src/iter/adapters/map_while.rs b/library/core/src/iter/adapters/map_while.rs index 4e7327938d72a..c047c40de050e 100644 --- a/library/core/src/iter/adapters/map_while.rs +++ b/library/core/src/iter/adapters/map_while.rs @@ -1,6 +1,6 @@ use crate::fmt; -use crate::iter::adapters::SourceIter; use crate::iter::InPlaceIterable; +use crate::iter::adapters::SourceIter; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/library/core/src/iter/adapters/mod.rs b/library/core/src/iter/adapters/mod.rs index 96158c43318ea..6d30f350337aa 100644 --- a/library/core/src/iter/adapters/mod.rs +++ b/library/core/src/iter/adapters/mod.rs @@ -48,12 +48,12 @@ pub use self::map_while::MapWhile; pub use self::map_windows::MapWindows; #[stable(feature = "iterator_step_by", since = "1.28.0")] pub use self::step_by::StepBy; -#[stable(feature = "iter_zip", since = "1.59.0")] -pub use self::zip::zip; #[unstable(feature = "trusted_random_access", issue = "none")] pub use self::zip::TrustedRandomAccess; #[unstable(feature = "trusted_random_access", issue = "none")] pub use self::zip::TrustedRandomAccessNoCoerce; +#[stable(feature = "iter_zip", since = "1.59.0")] +pub use self::zip::zip; #[stable(feature = "rust1", since = "1.0.0")] pub use self::{ chain::Chain, cycle::Cycle, enumerate::Enumerate, filter::Filter, filter_map::FilterMap, diff --git a/library/core/src/iter/adapters/scan.rs b/library/core/src/iter/adapters/scan.rs index 7ba7ed2fdd0d5..e12375c94e067 100644 --- a/library/core/src/iter/adapters/scan.rs +++ b/library/core/src/iter/adapters/scan.rs @@ -1,6 +1,6 @@ use crate::fmt; -use crate::iter::adapters::SourceIter; use crate::iter::InPlaceIterable; +use crate::iter::adapters::SourceIter; use crate::num::NonZero; use crate::ops::{ControlFlow, Try}; diff --git a/library/core/src/iter/adapters/skip.rs b/library/core/src/iter/adapters/skip.rs index 8ba2e2a8f2dd7..55c4a7f14fbd6 100644 --- a/library/core/src/iter/adapters/skip.rs +++ b/library/core/src/iter/adapters/skip.rs @@ -1,6 +1,6 @@ use crate::intrinsics::unlikely; -use crate::iter::adapters::zip::try_get_unchecked; use crate::iter::adapters::SourceIter; +use crate::iter::adapters::zip::try_get_unchecked; use crate::iter::{ FusedIterator, InPlaceIterable, TrustedFused, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, diff --git a/library/core/src/iter/adapters/step_by.rs b/library/core/src/iter/adapters/step_by.rs index 72eb72a76c66c..2d0f210420317 100644 --- a/library/core/src/iter/adapters/step_by.rs +++ b/library/core/src/iter/adapters/step_by.rs @@ -1,5 +1,5 @@ use crate::intrinsics; -use crate::iter::{from_fn, TrustedLen, TrustedRandomAccess}; +use crate::iter::{TrustedLen, TrustedRandomAccess, from_fn}; use crate::num::NonZero; use crate::ops::{Range, Try}; diff --git a/library/core/src/iter/mod.rs b/library/core/src/iter/mod.rs index 387963d0afd01..635e14e769a84 100644 --- a/library/core/src/iter/mod.rs +++ b/library/core/src/iter/mod.rs @@ -380,11 +380,6 @@ macro_rules! impl_fold_via_try_fold { }; } -#[unstable(feature = "iter_chain", reason = "recently added", issue = "125964")] -pub use self::adapters::chain; -pub(crate) use self::adapters::try_process; -#[stable(feature = "iter_zip", since = "1.59.0")] -pub use self::adapters::zip; #[unstable(feature = "iter_array_chunks", reason = "recently added", issue = "100450")] pub use self::adapters::ArrayChunks; #[unstable(feature = "std_internals", issue = "none")] @@ -407,6 +402,11 @@ pub use self::adapters::StepBy; pub use self::adapters::TrustedRandomAccess; #[unstable(feature = "trusted_random_access", issue = "none")] pub use self::adapters::TrustedRandomAccessNoCoerce; +#[unstable(feature = "iter_chain", reason = "recently added", issue = "125964")] +pub use self::adapters::chain; +pub(crate) use self::adapters::try_process; +#[stable(feature = "iter_zip", since = "1.59.0")] +pub use self::adapters::zip; #[stable(feature = "rust1", since = "1.0.0")] pub use self::adapters::{ Chain, Cycle, Enumerate, Filter, FilterMap, FlatMap, Fuse, Inspect, Map, Peekable, Rev, Scan, @@ -427,21 +427,21 @@ pub use self::range::Step; )] pub use self::sources::from_coroutine; #[stable(feature = "iter_empty", since = "1.2.0")] -pub use self::sources::{empty, Empty}; +pub use self::sources::{Empty, empty}; #[stable(feature = "iter_from_fn", since = "1.34.0")] -pub use self::sources::{from_fn, FromFn}; +pub use self::sources::{FromFn, from_fn}; #[stable(feature = "iter_once", since = "1.2.0")] -pub use self::sources::{once, Once}; +pub use self::sources::{Once, once}; #[stable(feature = "iter_once_with", since = "1.43.0")] -pub use self::sources::{once_with, OnceWith}; +pub use self::sources::{OnceWith, once_with}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::sources::{repeat, Repeat}; +pub use self::sources::{Repeat, repeat}; #[stable(feature = "iter_repeat_n", since = "1.82.0")] -pub use self::sources::{repeat_n, RepeatN}; +pub use self::sources::{RepeatN, repeat_n}; #[stable(feature = "iterator_repeat_with", since = "1.28.0")] -pub use self::sources::{repeat_with, RepeatWith}; +pub use self::sources::{RepeatWith, repeat_with}; #[stable(feature = "iter_successors", since = "1.34.0")] -pub use self::sources::{successors, Successors}; +pub use self::sources::{Successors, successors}; #[stable(feature = "fused", since = "1.26.0")] pub use self::traits::FusedIterator; #[unstable(issue = "none", feature = "inplace_iteration")] diff --git a/library/core/src/iter/sources.rs b/library/core/src/iter/sources.rs index 2c726fbca8760..c635992dfbd1b 100644 --- a/library/core/src/iter/sources.rs +++ b/library/core/src/iter/sources.rs @@ -9,7 +9,7 @@ mod repeat_with; mod successors; #[stable(feature = "iter_empty", since = "1.2.0")] -pub use self::empty::{empty, Empty}; +pub use self::empty::{Empty, empty}; #[unstable( feature = "iter_from_coroutine", issue = "43122", @@ -17,16 +17,16 @@ pub use self::empty::{empty, Empty}; )] pub use self::from_coroutine::from_coroutine; #[stable(feature = "iter_from_fn", since = "1.34.0")] -pub use self::from_fn::{from_fn, FromFn}; +pub use self::from_fn::{FromFn, from_fn}; #[stable(feature = "iter_once", since = "1.2.0")] -pub use self::once::{once, Once}; +pub use self::once::{Once, once}; #[stable(feature = "iter_once_with", since = "1.43.0")] -pub use self::once_with::{once_with, OnceWith}; +pub use self::once_with::{OnceWith, once_with}; #[stable(feature = "rust1", since = "1.0.0")] -pub use self::repeat::{repeat, Repeat}; +pub use self::repeat::{Repeat, repeat}; #[stable(feature = "iter_repeat_n", since = "1.82.0")] -pub use self::repeat_n::{repeat_n, RepeatN}; +pub use self::repeat_n::{RepeatN, repeat_n}; #[stable(feature = "iterator_repeat_with", since = "1.28.0")] -pub use self::repeat_with::{repeat_with, RepeatWith}; +pub use self::repeat_with::{RepeatWith, repeat_with}; #[stable(feature = "iter_successors", since = "1.34.0")] -pub use self::successors::{successors, Successors}; +pub use self::successors::{Successors, successors}; diff --git a/library/core/src/iter/traits/iterator.rs b/library/core/src/iter/traits/iterator.rs index f53beeb007d1f..7963459bfb5d9 100644 --- a/library/core/src/iter/traits/iterator.rs +++ b/library/core/src/iter/traits/iterator.rs @@ -1,8 +1,8 @@ use super::super::{ - try_process, ArrayChunks, ByRefSized, Chain, Cloned, Copied, Cycle, Enumerate, Filter, - FilterMap, FlatMap, Flatten, Fuse, Inspect, Intersperse, IntersperseWith, Map, MapWhile, - MapWindows, Peekable, Product, Rev, Scan, Skip, SkipWhile, StepBy, Sum, Take, TakeWhile, - TrustedRandomAccessNoCoerce, Zip, + ArrayChunks, ByRefSized, Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, FlatMap, + Flatten, Fuse, Inspect, Intersperse, IntersperseWith, Map, MapWhile, MapWindows, Peekable, + Product, Rev, Scan, Skip, SkipWhile, StepBy, Sum, Take, TakeWhile, TrustedRandomAccessNoCoerce, + Zip, try_process, }; use crate::array; use crate::cmp::{self, Ordering}; diff --git a/library/core/src/lib.rs b/library/core/src/lib.rs index 8826bf52b412f..01cadd78cc09d 100644 --- a/library/core/src/lib.rs +++ b/library/core/src/lib.rs @@ -119,6 +119,7 @@ #![feature(const_bigint_helper_methods)] #![feature(const_black_box)] #![feature(const_cell_into_inner)] +#![feature(const_char_encode_utf16)] #![feature(const_char_encode_utf8)] #![feature(const_eval_select)] #![feature(const_exact_div)] @@ -127,11 +128,11 @@ #![feature(const_hash)] #![feature(const_heap)] #![feature(const_index_range_slice_index)] -#![feature(const_intrinsic_copy)] #![feature(const_intrinsic_forget)] #![feature(const_ipv4)] #![feature(const_ipv6)] #![feature(const_likely)] +#![feature(const_make_ascii)] #![feature(const_maybe_uninit_assume_init)] #![feature(const_nonnull_new)] #![feature(const_num_midpoint)] @@ -150,6 +151,7 @@ #![feature(const_slice_from_raw_parts_mut)] #![feature(const_slice_from_ref)] #![feature(const_slice_split_at_mut)] +#![feature(const_str_as_mut)] #![feature(const_str_from_utf8_unchecked_mut)] #![feature(const_strict_overflow_ops)] #![feature(const_swap)] @@ -393,6 +395,8 @@ pub mod panicking; #[unstable(feature = "core_pattern_types", issue = "123646")] pub mod pat; pub mod pin; +#[unstable(feature = "random", issue = "130703")] +pub mod random; #[unstable(feature = "new_range_api", issue = "125687")] pub mod range; pub mod result; diff --git a/library/core/src/num/dec2flt/decimal.rs b/library/core/src/num/dec2flt/decimal.rs index 350f64bb4f7a3..be9c0eccd5eb8 100644 --- a/library/core/src/num/dec2flt/decimal.rs +++ b/library/core/src/num/dec2flt/decimal.rs @@ -9,7 +9,7 @@ //! algorithm can be found in "ParseNumberF64 by Simple Decimal Conversion", //! available online: . -use crate::num::dec2flt::common::{is_8digits, ByteSlice}; +use crate::num::dec2flt::common::{ByteSlice, is_8digits}; #[derive(Clone)] pub struct Decimal { diff --git a/library/core/src/num/dec2flt/parse.rs b/library/core/src/num/dec2flt/parse.rs index 975bb8ad6bc1f..06ee8e95fbc47 100644 --- a/library/core/src/num/dec2flt/parse.rs +++ b/library/core/src/num/dec2flt/parse.rs @@ -1,6 +1,6 @@ //! Functions to parse floating-point numbers. -use crate::num::dec2flt::common::{is_8digits, ByteSlice}; +use crate::num::dec2flt::common::{ByteSlice, is_8digits}; use crate::num::dec2flt::float::RawFloat; use crate::num::dec2flt::number::Number; diff --git a/library/core/src/num/dec2flt/slow.rs b/library/core/src/num/dec2flt/slow.rs index bf1044033e69e..85d4b13284b7d 100644 --- a/library/core/src/num/dec2flt/slow.rs +++ b/library/core/src/num/dec2flt/slow.rs @@ -1,7 +1,7 @@ //! Slow, fallback algorithm for cases the Eisel-Lemire algorithm cannot round. use crate::num::dec2flt::common::BiasedFp; -use crate::num::dec2flt::decimal::{parse_decimal, Decimal}; +use crate::num::dec2flt::decimal::{Decimal, parse_decimal}; use crate::num::dec2flt::float::RawFloat; /// Parse the significant digits and biased, binary exponent of a float. diff --git a/library/core/src/num/flt2dec/decoder.rs b/library/core/src/num/flt2dec/decoder.rs index 5763860540aa4..40b3aae24a536 100644 --- a/library/core/src/num/flt2dec/decoder.rs +++ b/library/core/src/num/flt2dec/decoder.rs @@ -1,7 +1,7 @@ //! Decodes a floating-point value into individual parts and error ranges. -use crate::num::dec2flt::float::RawFloat; use crate::num::FpCategory; +use crate::num::dec2flt::float::RawFloat; /// Decoded unsigned finite value, such that: /// diff --git a/library/core/src/num/flt2dec/mod.rs b/library/core/src/num/flt2dec/mod.rs index 7d923a2652f28..d6413fadc3381 100644 --- a/library/core/src/num/flt2dec/mod.rs +++ b/library/core/src/num/flt2dec/mod.rs @@ -122,7 +122,7 @@ functions. issue = "none" )] -pub use self::decoder::{decode, DecodableFloat, Decoded, FullDecoded}; +pub use self::decoder::{DecodableFloat, Decoded, FullDecoded, decode}; use super::fmt::{Formatted, Part}; use crate::mem::MaybeUninit; diff --git a/library/core/src/num/flt2dec/strategy/dragon.rs b/library/core/src/num/flt2dec/strategy/dragon.rs index f8db6370653ab..e801f07b3bc0e 100644 --- a/library/core/src/num/flt2dec/strategy/dragon.rs +++ b/library/core/src/num/flt2dec/strategy/dragon.rs @@ -8,7 +8,7 @@ use crate::cmp::Ordering; use crate::mem::MaybeUninit; use crate::num::bignum::{Big32x40 as Big, Digit32 as Digit}; use crate::num::flt2dec::estimator::estimate_scaling_factor; -use crate::num::flt2dec::{round_up, Decoded, MAX_SIG_DIGITS}; +use crate::num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; static POW10: [Digit; 10] = [1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000]; diff --git a/library/core/src/num/flt2dec/strategy/grisu.rs b/library/core/src/num/flt2dec/strategy/grisu.rs index b9f0d114c6a14..bdf544a4133bb 100644 --- a/library/core/src/num/flt2dec/strategy/grisu.rs +++ b/library/core/src/num/flt2dec/strategy/grisu.rs @@ -7,7 +7,7 @@ use crate::mem::MaybeUninit; use crate::num::diy_float::Fp; -use crate::num::flt2dec::{round_up, Decoded, MAX_SIG_DIGITS}; +use crate::num::flt2dec::{Decoded, MAX_SIG_DIGITS, round_up}; // see the comments in `format_shortest_opt` for the rationale. #[doc(hidden)] diff --git a/library/core/src/num/mod.rs b/library/core/src/num/mod.rs index 15de4fa15c481..31e35015d2de1 100644 --- a/library/core/src/num/mod.rs +++ b/library/core/src/num/mod.rs @@ -75,9 +75,9 @@ pub use nonzero::NonZero; )] pub use nonzero::ZeroablePrimitive; #[stable(feature = "signed_nonzero", since = "1.34.0")] -pub use nonzero::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize}; +pub use nonzero::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize}; #[stable(feature = "nonzero", since = "1.28.0")] -pub use nonzero::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize}; +pub use nonzero::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize}; #[stable(feature = "saturating_int_impl", since = "1.74.0")] pub use saturating::Saturating; #[stable(feature = "rust1", since = "1.0.0")] @@ -624,8 +624,9 @@ impl u8 { /// /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] + #[rustc_const_unstable(feature = "const_make_ascii", issue = "130698")] #[inline] - pub fn make_ascii_uppercase(&mut self) { + pub const fn make_ascii_uppercase(&mut self) { *self = self.to_ascii_uppercase(); } @@ -649,8 +650,9 @@ impl u8 { /// /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] + #[rustc_const_unstable(feature = "const_make_ascii", issue = "130698")] #[inline] - pub fn make_ascii_lowercase(&mut self) { + pub const fn make_ascii_lowercase(&mut self) { *self = self.to_ascii_lowercase(); } diff --git a/library/core/src/ops/async_function.rs b/library/core/src/ops/async_function.rs index 37fac2b126fac..4b230b15a1e6f 100644 --- a/library/core/src/ops/async_function.rs +++ b/library/core/src/ops/async_function.rs @@ -79,7 +79,10 @@ mod impls { where F: AsyncFn, { - type CallRefFuture<'a> = F::CallRefFuture<'a> where Self: 'a; + type CallRefFuture<'a> + = F::CallRefFuture<'a> + where + Self: 'a; extern "rust-call" fn async_call_mut(&mut self, args: A) -> Self::CallRefFuture<'_> { F::async_call(*self, args) @@ -104,7 +107,10 @@ mod impls { where F: AsyncFnMut, { - type CallRefFuture<'a> = F::CallRefFuture<'a> where Self: 'a; + type CallRefFuture<'a> + = F::CallRefFuture<'a> + where + Self: 'a; extern "rust-call" fn async_call_mut(&mut self, args: A) -> Self::CallRefFuture<'_> { F::async_call_mut(*self, args) diff --git a/library/core/src/ops/mod.rs b/library/core/src/ops/mod.rs index 98d41b71e8eb8..25c4b87f4e76b 100644 --- a/library/core/src/ops/mod.rs +++ b/library/core/src/ops/mod.rs @@ -172,9 +172,9 @@ pub use self::deref::DerefPure; pub use self::deref::Receiver; #[stable(feature = "rust1", since = "1.0.0")] pub use self::deref::{Deref, DerefMut}; -pub(crate) use self::drop::fallback_surface_drop; #[stable(feature = "rust1", since = "1.0.0")] pub use self::drop::Drop; +pub(crate) use self::drop::fallback_surface_drop; #[stable(feature = "rust1", since = "1.0.0")] pub use self::function::{Fn, FnMut, FnOnce}; #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/option.rs b/library/core/src/option.rs index 5ba13969605fc..30c667e2494b2 100644 --- a/library/core/src/option.rs +++ b/library/core/src/option.rs @@ -2538,6 +2538,7 @@ impl Option> { #[stable(feature = "option_flattening", since = "1.40.0")] #[rustc_const_unstable(feature = "const_option", issue = "67441")] pub const fn flatten(self) -> Option { + // FIXME(const-hack): could be written with `and_then` match self { Some(inner) => inner, None => None, diff --git a/library/core/src/primitive.rs b/library/core/src/primitive.rs index 81a72118614dd..b5f97b898878f 100644 --- a/library/core/src/primitive.rs +++ b/library/core/src/primitive.rs @@ -46,7 +46,7 @@ pub use f32; #[stable(feature = "core_primitive", since = "1.43.0")] pub use f64; #[stable(feature = "core_primitive", since = "1.43.0")] -pub use i128; +pub use i8; #[stable(feature = "core_primitive", since = "1.43.0")] pub use i16; #[stable(feature = "core_primitive", since = "1.43.0")] @@ -54,13 +54,13 @@ pub use i32; #[stable(feature = "core_primitive", since = "1.43.0")] pub use i64; #[stable(feature = "core_primitive", since = "1.43.0")] -pub use i8; +pub use i128; #[stable(feature = "core_primitive", since = "1.43.0")] pub use isize; #[stable(feature = "core_primitive", since = "1.43.0")] pub use str; #[stable(feature = "core_primitive", since = "1.43.0")] -pub use u128; +pub use u8; #[stable(feature = "core_primitive", since = "1.43.0")] pub use u16; #[stable(feature = "core_primitive", since = "1.43.0")] @@ -68,6 +68,6 @@ pub use u32; #[stable(feature = "core_primitive", since = "1.43.0")] pub use u64; #[stable(feature = "core_primitive", since = "1.43.0")] -pub use u8; +pub use u128; #[stable(feature = "core_primitive", since = "1.43.0")] pub use usize; diff --git a/library/core/src/ptr/const_ptr.rs b/library/core/src/ptr/const_ptr.rs index 3b45d46b31d5e..1146ca6ef4301 100644 --- a/library/core/src/ptr/const_ptr.rs +++ b/library/core/src/ptr/const_ptr.rs @@ -1192,7 +1192,7 @@ impl *const T { /// See [`ptr::copy`] for safety concerns and examples. /// /// [`ptr::copy`]: crate::ptr::copy() - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces @@ -1212,7 +1212,7 @@ impl *const T { /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples. /// /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping() - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces diff --git a/library/core/src/ptr/mod.rs b/library/core/src/ptr/mod.rs index 08d06cad55d06..cac33a329b991 100644 --- a/library/core/src/ptr/mod.rs +++ b/library/core/src/ptr/mod.rs @@ -467,7 +467,7 @@ pub use crate::intrinsics::write_bytes; mod metadata; #[unstable(feature = "ptr_metadata", issue = "81513")] -pub use metadata::{from_raw_parts, from_raw_parts_mut, metadata, DynMetadata, Pointee, Thin}; +pub use metadata::{DynMetadata, Pointee, Thin, from_raw_parts, from_raw_parts_mut, metadata}; mod non_null; #[stable(feature = "nonnull", since = "1.25.0")] @@ -1516,11 +1516,7 @@ pub const unsafe fn read(src: *const T) -> T { #[inline] #[stable(feature = "ptr_unaligned", since = "1.17.0")] #[rustc_const_stable(feature = "const_ptr_read", since = "1.71.0")] -#[rustc_allow_const_fn_unstable( - const_mut_refs, - const_maybe_uninit_as_mut_ptr, - const_intrinsic_copy -)] +#[cfg_attr(bootstrap, rustc_allow_const_fn_unstable(const_mut_refs))] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[rustc_diagnostic_item = "ptr_read_unaligned"] pub const unsafe fn read_unaligned(src: *const T) -> T { diff --git a/library/core/src/ptr/mut_ptr.rs b/library/core/src/ptr/mut_ptr.rs index 5fa3b9bf61f7f..8e33cf081ba6c 100644 --- a/library/core/src/ptr/mut_ptr.rs +++ b/library/core/src/ptr/mut_ptr.rs @@ -1269,7 +1269,7 @@ impl *mut T { /// See [`ptr::copy`] for safety concerns and examples. /// /// [`ptr::copy`]: crate::ptr::copy() - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces @@ -1289,7 +1289,7 @@ impl *mut T { /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples. /// /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping() - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces @@ -1309,7 +1309,7 @@ impl *mut T { /// See [`ptr::copy`] for safety concerns and examples. /// /// [`ptr::copy`]: crate::ptr::copy() - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces @@ -1329,7 +1329,7 @@ impl *mut T { /// See [`ptr::copy_nonoverlapping`] for safety concerns and examples. /// /// [`ptr::copy_nonoverlapping`]: crate::ptr::copy_nonoverlapping() - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] #[stable(feature = "pointer_methods", since = "1.26.0")] #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces diff --git a/library/core/src/ptr/non_null.rs b/library/core/src/ptr/non_null.rs index 673acc2972fe4..daa40b3c9d2e5 100644 --- a/library/core/src/ptr/non_null.rs +++ b/library/core/src/ptr/non_null.rs @@ -924,7 +924,7 @@ impl NonNull { #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[stable(feature = "non_null_convenience", since = "1.80.0")] - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] pub const unsafe fn copy_to(self, dest: NonNull, count: usize) where T: Sized, @@ -944,7 +944,7 @@ impl NonNull { #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[stable(feature = "non_null_convenience", since = "1.80.0")] - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] pub const unsafe fn copy_to_nonoverlapping(self, dest: NonNull, count: usize) where T: Sized, @@ -964,7 +964,7 @@ impl NonNull { #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[stable(feature = "non_null_convenience", since = "1.80.0")] - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] pub const unsafe fn copy_from(self, src: NonNull, count: usize) where T: Sized, @@ -984,7 +984,7 @@ impl NonNull { #[inline(always)] #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces #[stable(feature = "non_null_convenience", since = "1.80.0")] - #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] + #[rustc_const_stable(feature = "const_intrinsic_copy", since = "CURRENT_RUSTC_VERSION")] pub const unsafe fn copy_from_nonoverlapping(self, src: NonNull, count: usize) where T: Sized, diff --git a/library/core/src/random.rs b/library/core/src/random.rs new file mode 100644 index 0000000000000..051fe26086389 --- /dev/null +++ b/library/core/src/random.rs @@ -0,0 +1,62 @@ +//! Random value generation. +//! +//! The [`Random`] trait allows generating a random value for a type using a +//! given [`RandomSource`]. + +/// A source of randomness. +#[unstable(feature = "random", issue = "130703")] +pub trait RandomSource { + /// Fills `bytes` with random bytes. + fn fill_bytes(&mut self, bytes: &mut [u8]); +} + +/// A trait for getting a random value for a type. +/// +/// **Warning:** Be careful when manipulating random values! The +/// [`random`](Random::random) method on integers samples them with a uniform +/// distribution, so a value of 1 is just as likely as [`i32::MAX`]. By using +/// modulo operations, some of the resulting values can become more likely than +/// others. Use audited crates when in doubt. +#[unstable(feature = "random", issue = "130703")] +pub trait Random: Sized { + /// Generates a random value. + fn random(source: &mut (impl RandomSource + ?Sized)) -> Self; +} + +impl Random for bool { + fn random(source: &mut (impl RandomSource + ?Sized)) -> Self { + u8::random(source) & 1 == 1 + } +} + +macro_rules! impl_primitive { + ($t:ty) => { + impl Random for $t { + /// Generates a random value. + /// + /// **Warning:** Be careful when manipulating the resulting value! This + /// method samples according to a uniform distribution, so a value of 1 is + /// just as likely as [`MAX`](Self::MAX). By using modulo operations, some + /// values can become more likely than others. Use audited crates when in + /// doubt. + fn random(source: &mut (impl RandomSource + ?Sized)) -> Self { + let mut bytes = (0 as Self).to_ne_bytes(); + source.fill_bytes(&mut bytes); + Self::from_ne_bytes(bytes) + } + } + }; +} + +impl_primitive!(u8); +impl_primitive!(i8); +impl_primitive!(u16); +impl_primitive!(i16); +impl_primitive!(u32); +impl_primitive!(i32); +impl_primitive!(u64); +impl_primitive!(i64); +impl_primitive!(u128); +impl_primitive!(i128); +impl_primitive!(usize); +impl_primitive!(isize); diff --git a/library/core/src/range.rs b/library/core/src/range.rs index 408972c267f1a..427526fd14b91 100644 --- a/library/core/src/range.rs +++ b/library/core/src/range.rs @@ -24,9 +24,9 @@ mod iter; #[unstable(feature = "new_range_api", issue = "125687")] pub mod legacy; +use Bound::{Excluded, Included, Unbounded}; #[doc(inline)] pub use iter::{IterRange, IterRangeFrom, IterRangeInclusive}; -use Bound::{Excluded, Included, Unbounded}; #[doc(inline)] pub use crate::iter::Step; diff --git a/library/core/src/range/iter.rs b/library/core/src/range/iter.rs index 4935280df60bc..1e261d8c1d93a 100644 --- a/library/core/src/range/iter.rs +++ b/library/core/src/range/iter.rs @@ -2,7 +2,7 @@ use crate::iter::{ FusedIterator, Step, TrustedLen, TrustedRandomAccess, TrustedRandomAccessNoCoerce, TrustedStep, }; use crate::num::NonZero; -use crate::range::{legacy, Range, RangeFrom, RangeInclusive}; +use crate::range::{Range, RangeFrom, RangeInclusive, legacy}; /// By-value [`Range`] iterator. #[unstable(feature = "new_range_api", issue = "125687")] diff --git a/library/core/src/result.rs b/library/core/src/result.rs index 9edd58259ba0f..610edae48d36b 100644 --- a/library/core/src/result.rs +++ b/library/core/src/result.rs @@ -1676,8 +1676,13 @@ impl Result, E> { /// ``` #[inline] #[unstable(feature = "result_flattening", issue = "70142")] - pub fn flatten(self) -> Result { - self.and_then(convert::identity) + #[rustc_const_unstable(feature = "result_flattening", issue = "70142")] + pub const fn flatten(self) -> Result { + // FIXME(const-hack): could be written with `and_then` + match self { + Ok(inner) => inner, + Err(e) => Err(e), + } } } diff --git a/library/core/src/slice/ascii.rs b/library/core/src/slice/ascii.rs index d1ea52fab6b87..8f8050fdc3aaf 100644 --- a/library/core/src/slice/ascii.rs +++ b/library/core/src/slice/ascii.rs @@ -67,10 +67,15 @@ impl [u8] { /// /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] + #[rustc_const_unstable(feature = "const_make_ascii", issue = "130698")] #[inline] - pub fn make_ascii_uppercase(&mut self) { - for byte in self { + pub const fn make_ascii_uppercase(&mut self) { + // FIXME(const-hack): We would like to simply iterate using `for` loops but this isn't currently allowed in constant expressions. + let mut i = 0; + while i < self.len() { + let byte = &mut self[i]; byte.make_ascii_uppercase(); + i += 1; } } @@ -84,10 +89,15 @@ impl [u8] { /// /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] + #[rustc_const_unstable(feature = "const_make_ascii", issue = "130698")] #[inline] - pub fn make_ascii_lowercase(&mut self) { - for byte in self { + pub const fn make_ascii_lowercase(&mut self) { + // FIXME(const-hack): We would like to simply iterate using `for` loops but this isn't currently allowed in constant expressions. + let mut i = 0; + while i < self.len() { + let byte = &mut self[i]; byte.make_ascii_lowercase(); + i += 1; } } diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index 62b170a87d445..1168f36da1542 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -11,7 +11,7 @@ use crate::iter::{ use crate::marker::PhantomData; use crate::mem::{self, SizedTypeProperties}; use crate::num::NonZero; -use crate::ptr::{self, without_provenance, without_provenance_mut, NonNull}; +use crate::ptr::{self, NonNull, without_provenance, without_provenance_mut}; use crate::{cmp, fmt}; #[stable(feature = "boxed_slice_into_iter", since = "1.80.0")] diff --git a/library/core/src/slice/mod.rs b/library/core/src/slice/mod.rs index cdcca0eee888d..11c9f483f369f 100644 --- a/library/core/src/slice/mod.rs +++ b/library/core/src/slice/mod.rs @@ -39,11 +39,11 @@ mod raw; mod rotate; mod specialize; +#[stable(feature = "inherent_ascii_escape", since = "1.60.0")] +pub use ascii::EscapeAscii; #[unstable(feature = "str_internals", issue = "none")] #[doc(hidden)] pub use ascii::is_ascii_simple; -#[stable(feature = "inherent_ascii_escape", since = "1.60.0")] -pub use ascii::EscapeAscii; #[stable(feature = "slice_get_slice", since = "1.28.0")] pub use index::SliceIndex; #[unstable(feature = "slice_range", issue = "76393")] diff --git a/library/core/src/slice/sort/select.rs b/library/core/src/slice/sort/select.rs index f6529f23bcb3f..3358c03d30a9b 100644 --- a/library/core/src/slice/sort/select.rs +++ b/library/core/src/slice/sort/select.rs @@ -7,6 +7,7 @@ //! better performance than one would get using heapsort as fallback. use crate::mem::{self, SizedTypeProperties}; +#[cfg(not(feature = "optimize_for_size"))] use crate::slice::sort::shared::pivot::choose_pivot; use crate::slice::sort::shared::smallsort::insertion_sort_shift_left; use crate::slice::sort::unstable::quicksort::partition; @@ -40,7 +41,13 @@ where let min_idx = min_index(v, &mut is_less).unwrap(); v.swap(min_idx, index); } else { - partition_at_index_loop(v, index, None, &mut is_less); + cfg_if! { + if #[cfg(feature = "optimize_for_size")] { + median_of_medians(v, &mut is_less, index); + } else { + partition_at_index_loop(v, index, None, &mut is_less); + } + } } let (left, right) = v.split_at_mut(index); @@ -53,6 +60,7 @@ where // most once, it doesn't make sense to use something more sophisticated than insertion-sort. const INSERTION_SORT_THRESHOLD: usize = 16; +#[cfg(not(feature = "optimize_for_size"))] fn partition_at_index_loop<'a, T, F>( mut v: &'a mut [T], mut index: usize, @@ -169,6 +177,7 @@ fn median_of_medians bool>(mut v: &mut [T], is_less: &mut if v.len() >= 2 { insertion_sort_shift_left(v, 1, is_less); } + return; } diff --git a/library/core/src/slice/sort/shared/mod.rs b/library/core/src/slice/sort/shared/mod.rs index ad1171bfc6a0a..e0f8d475a2e30 100644 --- a/library/core/src/slice/sort/shared/mod.rs +++ b/library/core/src/slice/sort/shared/mod.rs @@ -1,3 +1,5 @@ +#![cfg_attr(feature = "optimize_for_size", allow(dead_code))] + use crate::marker::Freeze; pub(crate) mod pivot; diff --git a/library/core/src/slice/sort/shared/smallsort.rs b/library/core/src/slice/sort/shared/smallsort.rs index fae628a7c1474..6adf779a72f0c 100644 --- a/library/core/src/slice/sort/shared/smallsort.rs +++ b/library/core/src/slice/sort/shared/smallsort.rs @@ -378,7 +378,12 @@ where /// Swap two values in the slice pointed to by `v_base` at the position `a_pos` and `b_pos` if the /// value at position `b_pos` is less than the one at position `a_pos`. -pub unsafe fn swap_if_less(v_base: *mut T, a_pos: usize, b_pos: usize, is_less: &mut F) +/// +/// Purposefully not marked `#[inline]`, despite us wanting it to be inlined for integers like +/// types. `is_less` could be a huge function and we want to give the compiler an option to +/// not inline this function. For the same reasons that this function is very perf critical +/// it should be in the same module as the functions that use it. +unsafe fn swap_if_less(v_base: *mut T, a_pos: usize, b_pos: usize, is_less: &mut F) where F: FnMut(&T, &T) -> bool, { diff --git a/library/core/src/slice/sort/stable/mod.rs b/library/core/src/slice/sort/stable/mod.rs index a383b0f589ccf..e13fbc37e80c4 100644 --- a/library/core/src/slice/sort/stable/mod.rs +++ b/library/core/src/slice/sort/stable/mod.rs @@ -1,15 +1,24 @@ //! This module contains the entry points for `slice::sort`. +#[cfg(not(feature = "optimize_for_size"))] +use crate::cmp; +use crate::intrinsics; use crate::mem::{self, MaybeUninit, SizedTypeProperties}; +#[cfg(not(feature = "optimize_for_size"))] use crate::slice::sort::shared::smallsort::{ - insertion_sort_shift_left, StableSmallSortTypeImpl, SMALL_SORT_GENERAL_SCRATCH_LEN, + SMALL_SORT_GENERAL_SCRATCH_LEN, StableSmallSortTypeImpl, insertion_sort_shift_left, }; -use crate::{cmp, intrinsics}; -pub(crate) mod drift; pub(crate) mod merge; + +#[cfg(not(feature = "optimize_for_size"))] +pub(crate) mod drift; +#[cfg(not(feature = "optimize_for_size"))] pub(crate) mod quicksort; +#[cfg(feature = "optimize_for_size")] +pub(crate) mod tiny; + /// Stable sort called driftsort by Orson Peters and Lukas Bergdoll. /// Design document: /// @@ -30,25 +39,53 @@ pub fn sort bool, BufT: BufGuard>(v: &mut [T], is_less return; } - // More advanced sorting methods than insertion sort are faster if called in - // a hot loop for small inputs, but for general-purpose code the small - // binary size of insertion sort is more important. The instruction cache in - // modern processors is very valuable, and for a single sort call in general - // purpose code any gains from an advanced method are cancelled by i-cache - // misses during the sort, and thrashing the i-cache for surrounding code. - const MAX_LEN_ALWAYS_INSERTION_SORT: usize = 20; - if intrinsics::likely(len <= MAX_LEN_ALWAYS_INSERTION_SORT) { - insertion_sort_shift_left(v, 1, is_less); - return; - } + cfg_if! { + if #[cfg(any(feature = "optimize_for_size", target_pointer_width = "16"))] { + let alloc_len = len / 2; + + cfg_if! { + if #[cfg(target_pointer_width = "16")] { + let heap_buf = BufT::with_capacity(alloc_len); + let scratch = heap_buf.as_uninit_slice_mut(); + } else { + // For small inputs 4KiB of stack storage suffices, which allows us to avoid + // calling the (de-)allocator. Benchmarks showed this was quite beneficial. + let mut stack_buf = AlignedStorage::::new(); + let stack_scratch = stack_buf.as_uninit_slice_mut(); + let mut heap_buf; + let scratch = if stack_scratch.len() >= alloc_len { + stack_scratch + } else { + heap_buf = BufT::with_capacity(alloc_len); + heap_buf.as_uninit_slice_mut() + }; + } + } - driftsort_main::(v, is_less); + tiny::mergesort(v, scratch, is_less); + } else { + // More advanced sorting methods than insertion sort are faster if called in + // a hot loop for small inputs, but for general-purpose code the small + // binary size of insertion sort is more important. The instruction cache in + // modern processors is very valuable, and for a single sort call in general + // purpose code any gains from an advanced method are cancelled by i-cache + // misses during the sort, and thrashing the i-cache for surrounding code. + const MAX_LEN_ALWAYS_INSERTION_SORT: usize = 20; + if intrinsics::likely(len <= MAX_LEN_ALWAYS_INSERTION_SORT) { + insertion_sort_shift_left(v, 1, is_less); + return; + } + + driftsort_main::(v, is_less); + } + } } /// See [`sort`] /// /// Deliberately don't inline the main sorting routine entrypoint to ensure the /// inlined insertion sort i-cache footprint remains minimal. +#[cfg(not(feature = "optimize_for_size"))] #[inline(never)] fn driftsort_main bool, BufT: BufGuard>(v: &mut [T], is_less: &mut F) { // By allocating n elements of memory we can ensure the entire input can diff --git a/library/core/src/slice/sort/stable/quicksort.rs b/library/core/src/slice/sort/stable/quicksort.rs index 3319d67ab52fa..0c8308bfce00e 100644 --- a/library/core/src/slice/sort/stable/quicksort.rs +++ b/library/core/src/slice/sort/stable/quicksort.rs @@ -1,9 +1,9 @@ //! This module contains a stable quicksort and partition implementation. use crate::mem::{self, ManuallyDrop, MaybeUninit}; +use crate::slice::sort::shared::FreezeMarker; use crate::slice::sort::shared::pivot::choose_pivot; use crate::slice::sort::shared::smallsort::StableSmallSortTypeImpl; -use crate::slice::sort::shared::FreezeMarker; use crate::{intrinsics, ptr}; /// Sorts `v` recursively using quicksort. diff --git a/library/core/src/slice/sort/stable/tiny.rs b/library/core/src/slice/sort/stable/tiny.rs new file mode 100644 index 0000000000000..071ab8e107fe3 --- /dev/null +++ b/library/core/src/slice/sort/stable/tiny.rs @@ -0,0 +1,41 @@ +//! Binary-size optimized mergesort inspired by https://github.com/voultapher/tiny-sort-rs. + +use crate::mem::MaybeUninit; +use crate::ptr; +use crate::slice::sort::stable::merge; + +/// Tiny recursive top-down merge sort optimized for binary size. It has no adaptiveness whatsoever, +/// no run detection, etc. +#[inline(always)] +pub fn mergesort bool>( + v: &mut [T], + scratch: &mut [MaybeUninit], + is_less: &mut F, +) { + let len = v.len(); + + if len > 2 { + let mid = len / 2; + + // SAFETY: mid is in-bounds. + unsafe { + // Sort the left half recursively. + mergesort(v.get_unchecked_mut(..mid), scratch, is_less); + // Sort the right half recursively. + mergesort(v.get_unchecked_mut(mid..), scratch, is_less); + } + + merge::merge(v, scratch, mid, is_less); + } else if len == 2 { + // SAFETY: We checked the len, the pointers we create are valid and don't overlap. + unsafe { + let v_base = v.as_mut_ptr(); + let v_a = v_base; + let v_b = v_base.add(1); + + if is_less(&*v_b, &*v_a) { + ptr::swap_nonoverlapping(v_a, v_b, 1); + } + } + } +} diff --git a/library/core/src/slice/sort/unstable/heapsort.rs b/library/core/src/slice/sort/unstable/heapsort.rs index 27e2ad588ea09..85231779d031f 100644 --- a/library/core/src/slice/sort/unstable/heapsort.rs +++ b/library/core/src/slice/sort/unstable/heapsort.rs @@ -1,46 +1,46 @@ //! This module contains a branchless heapsort as fallback for unstable quicksort. -use crate::{intrinsics, ptr}; +use crate::{cmp, intrinsics, ptr}; /// Sorts `v` using heapsort, which guarantees *O*(*n* \* log(*n*)) worst-case. /// /// Never inline this, it sits the main hot-loop in `recurse` and is meant as unlikely algorithmic /// fallback. -/// -/// SAFETY: The caller has to guarantee that `v.len()` >= 2. #[inline(never)] -pub(crate) unsafe fn heapsort(v: &mut [T], is_less: &mut F) +pub(crate) fn heapsort(v: &mut [T], is_less: &mut F) where F: FnMut(&T, &T) -> bool, { - // SAFETY: See function safety. - unsafe { - intrinsics::assume(v.len() >= 2); - - // Build the heap in linear time. - for i in (0..v.len() / 2).rev() { - sift_down(v, i, is_less); - } + let len = v.len(); - // Pop maximal elements from the heap. - for i in (1..v.len()).rev() { + for i in (0..len + len / 2).rev() { + let sift_idx = if i >= len { + i - len + } else { v.swap(0, i); - sift_down(&mut v[..i], 0, is_less); + 0 + }; + + // SAFETY: The above calculation ensures that `sift_idx` is either 0 or + // `(len..(len + (len / 2))) - len`, which simplifies to `0..(len / 2)`. + // This guarantees the required `sift_idx <= len`. + unsafe { + sift_down(&mut v[..cmp::min(i, len)], sift_idx, is_less); } } } // This binary heap respects the invariant `parent >= child`. // -// SAFETY: The caller has to guarantee that node < `v.len()`. -#[inline(never)] +// SAFETY: The caller has to guarantee that `node <= v.len()`. +#[inline(always)] unsafe fn sift_down(v: &mut [T], mut node: usize, is_less: &mut F) where F: FnMut(&T, &T) -> bool, { // SAFETY: See function safety. unsafe { - intrinsics::assume(node < v.len()); + intrinsics::assume(node <= v.len()); } let len = v.len(); @@ -69,9 +69,7 @@ where break; } - // Swap `node` with the greater child, move one step down, and continue sifting. This - // could be ptr::swap_nonoverlapping but that adds a significant amount of binary-size. - ptr::swap(v_base.add(node), v_base.add(child)); + ptr::swap_nonoverlapping(v_base.add(node), v_base.add(child), 1); } node = child; diff --git a/library/core/src/slice/sort/unstable/mod.rs b/library/core/src/slice/sort/unstable/mod.rs index 932e01f4401e5..8bbd85443d478 100644 --- a/library/core/src/slice/sort/unstable/mod.rs +++ b/library/core/src/slice/sort/unstable/mod.rs @@ -2,7 +2,9 @@ use crate::intrinsics; use crate::mem::SizedTypeProperties; +#[cfg(not(feature = "optimize_for_size"))] use crate::slice::sort::shared::find_existing_run; +#[cfg(not(feature = "optimize_for_size"))] use crate::slice::sort::shared::smallsort::insertion_sort_shift_left; pub(crate) mod heapsort; @@ -28,25 +30,32 @@ pub fn sort bool>(v: &mut [T], is_less: &mut F) { return; } - // More advanced sorting methods than insertion sort are faster if called in - // a hot loop for small inputs, but for general-purpose code the small - // binary size of insertion sort is more important. The instruction cache in - // modern processors is very valuable, and for a single sort call in general - // purpose code any gains from an advanced method are cancelled by i-cache - // misses during the sort, and thrashing the i-cache for surrounding code. - const MAX_LEN_ALWAYS_INSERTION_SORT: usize = 20; - if intrinsics::likely(len <= MAX_LEN_ALWAYS_INSERTION_SORT) { - insertion_sort_shift_left(v, 1, is_less); - return; - } + cfg_if! { + if #[cfg(any(feature = "optimize_for_size", target_pointer_width = "16"))] { + heapsort::heapsort(v, is_less); + } else { + // More advanced sorting methods than insertion sort are faster if called in + // a hot loop for small inputs, but for general-purpose code the small + // binary size of insertion sort is more important. The instruction cache in + // modern processors is very valuable, and for a single sort call in general + // purpose code any gains from an advanced method are cancelled by i-cache + // misses during the sort, and thrashing the i-cache for surrounding code. + const MAX_LEN_ALWAYS_INSERTION_SORT: usize = 20; + if intrinsics::likely(len <= MAX_LEN_ALWAYS_INSERTION_SORT) { + insertion_sort_shift_left(v, 1, is_less); + return; + } - ipnsort(v, is_less); + ipnsort(v, is_less); + } + } } /// See [`sort`] /// /// Deliberately don't inline the main sorting routine entrypoint to ensure the /// inlined insertion sort i-cache footprint remains minimal. +#[cfg(not(feature = "optimize_for_size"))] #[inline(never)] fn ipnsort(v: &mut [T], is_less: &mut F) where diff --git a/library/core/src/slice/sort/unstable/quicksort.rs b/library/core/src/slice/sort/unstable/quicksort.rs index cd53656e9b4b8..4feef5deeb0fb 100644 --- a/library/core/src/slice/sort/unstable/quicksort.rs +++ b/library/core/src/slice/sort/unstable/quicksort.rs @@ -1,8 +1,12 @@ //! This module contains an unstable quicksort and two partition implementations. use crate::mem::{self, ManuallyDrop}; +#[cfg(not(feature = "optimize_for_size"))] use crate::slice::sort::shared::pivot::choose_pivot; +#[cfg(not(feature = "optimize_for_size"))] use crate::slice::sort::shared::smallsort::UnstableSmallSortTypeImpl; +#[cfg(not(feature = "optimize_for_size"))] +use crate::slice::sort::unstable::heapsort; use crate::{intrinsics, ptr}; /// Sorts `v` recursively. @@ -11,6 +15,7 @@ use crate::{intrinsics, ptr}; /// /// `limit` is the number of allowed imbalanced partitions before switching to `heapsort`. If zero, /// this function will immediately switch to heapsort. +#[cfg(not(feature = "optimize_for_size"))] pub(crate) fn quicksort<'a, T, F>( mut v: &'a mut [T], mut ancestor_pivot: Option<&'a T>, @@ -28,10 +33,7 @@ pub(crate) fn quicksort<'a, T, F>( // If too many bad pivot choices were made, simply fall back to heapsort in order to // guarantee `O(N x log(N))` worst-case. if limit == 0 { - // SAFETY: We assume the `small_sort` threshold is at least 1. - unsafe { - crate::slice::sort::unstable::heapsort::heapsort(v, is_less); - } + heapsort::heapsort(v, is_less); return; } @@ -98,13 +100,15 @@ where return 0; } - // Allows for panic-free code-gen by proving this property to the compiler. if pivot >= len { intrinsics::abort(); } - // Place the pivot at the beginning of slice. - v.swap(0, pivot); + // SAFETY: We checked that `pivot` is in-bounds. + unsafe { + // Place the pivot at the beginning of slice. + v.swap_unchecked(0, pivot); + } let (pivot, v_without_pivot) = v.split_at_mut(1); // Assuming that Rust generates noalias LLVM IR we can be sure that a partition function @@ -118,8 +122,15 @@ where // compile-time by only instantiating the code that is needed. Idea by Frank Steffahn. let num_lt = (const { inst_partition::() })(v_without_pivot, pivot, is_less); - // Place the pivot between the two partitions. - v.swap(0, num_lt); + if num_lt >= len { + intrinsics::abort(); + } + + // SAFETY: We checked that `num_lt` is in-bounds. + unsafe { + // Place the pivot between the two partitions. + v.swap_unchecked(0, num_lt); + } num_lt } @@ -129,7 +140,13 @@ const fn inst_partition bool>() -> fn(&mut [T], &T, &mut if mem::size_of::() <= MAX_BRANCHLESS_PARTITION_SIZE { // Specialize for types that are relatively cheap to copy, where branchless optimizations // have large leverage e.g. `u64` and `String`. - partition_lomuto_branchless_cyclic:: + cfg_if! { + if #[cfg(feature = "optimize_for_size")] { + partition_lomuto_branchless_simple:: + } else { + partition_lomuto_branchless_cyclic:: + } + } } else { partition_hoare_branchy_cyclic:: } @@ -215,6 +232,7 @@ where } } +#[cfg(not(feature = "optimize_for_size"))] struct PartitionState { // The current element that is being looked at, scans left to right through slice. right: *mut T, @@ -225,6 +243,7 @@ struct PartitionState { gap: GapGuardRaw, } +#[cfg(not(feature = "optimize_for_size"))] fn partition_lomuto_branchless_cyclic(v: &mut [T], pivot: &T, is_less: &mut F) -> usize where F: FnMut(&T, &T) -> bool, @@ -316,6 +335,27 @@ where } } +#[cfg(feature = "optimize_for_size")] +fn partition_lomuto_branchless_simple bool>( + v: &mut [T], + pivot: &T, + is_less: &mut F, +) -> usize { + let mut left = 0; + + for right in 0..v.len() { + // SAFETY: `left` can at max be incremented by 1 each loop iteration, which implies that + // left <= right and that both are in-bounds. + unsafe { + let right_is_lt = is_less(v.get_unchecked(right), pivot); + v.swap_unchecked(left, right); + left += right_is_lt as usize; + } + } + + left +} + struct GapGuard { pos: *mut T, value: ManuallyDrop, @@ -333,11 +373,13 @@ impl Drop for GapGuard { /// Ideally this wouldn't be needed and we could just use the regular GapGuard. /// See comment in [`partition_lomuto_branchless_cyclic`]. +#[cfg(not(feature = "optimize_for_size"))] struct GapGuardRaw { pos: *mut T, value: *mut T, } +#[cfg(not(feature = "optimize_for_size"))] impl Drop for GapGuardRaw { fn drop(&mut self) { // SAFETY: `self` MUST be constructed in a way that makes copying the gap value into diff --git a/library/core/src/str/converts.rs b/library/core/src/str/converts.rs index dcddc40ba4b99..d6459607221ae 100644 --- a/library/core/src/str/converts.rs +++ b/library/core/src/str/converts.rs @@ -1,7 +1,7 @@ //! Ways to create a `str` from bytes slice. -use super::validations::run_utf8_validation; use super::Utf8Error; +use super::validations::run_utf8_validation; use crate::{mem, ptr}; /// Converts a slice of bytes to a string slice. diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index d9301a8a66ea2..425c4eaee28ee 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -3,8 +3,8 @@ use super::pattern::{DoubleEndedSearcher, Pattern, ReverseSearcher, Searcher}; use super::validations::{next_code_point, next_code_point_reverse}; use super::{ - from_utf8_unchecked, BytesIsNotEmpty, CharEscapeDebugContinue, CharEscapeDefault, - CharEscapeUnicode, IsAsciiWhitespace, IsNotEmpty, IsWhitespace, LinesMap, UnsafeBytesToStr, + BytesIsNotEmpty, CharEscapeDebugContinue, CharEscapeDefault, CharEscapeUnicode, + IsAsciiWhitespace, IsNotEmpty, IsWhitespace, LinesMap, UnsafeBytesToStr, from_utf8_unchecked, }; use crate::fmt::{self, Write}; use crate::iter::{ diff --git a/library/core/src/str/mod.rs b/library/core/src/str/mod.rs index 712bf011c273e..3d535214637f6 100644 --- a/library/core/src/str/mod.rs +++ b/library/core/src/str/mod.rs @@ -2473,8 +2473,9 @@ impl str { /// assert_eq!("GRüßE, JüRGEN ❤", s); /// ``` #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] + #[rustc_const_unstable(feature = "const_make_ascii", issue = "130698")] #[inline] - pub fn make_ascii_uppercase(&mut self) { + pub const fn make_ascii_uppercase(&mut self) { // SAFETY: changing ASCII letters only does not invalidate UTF-8. let me = unsafe { self.as_bytes_mut() }; me.make_ascii_uppercase() @@ -2500,8 +2501,9 @@ impl str { /// assert_eq!("grÜße, jÜrgen ❤", s); /// ``` #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] + #[rustc_const_unstable(feature = "const_make_ascii", issue = "130698")] #[inline] - pub fn make_ascii_lowercase(&mut self) { + pub const fn make_ascii_lowercase(&mut self) { // SAFETY: changing ASCII letters only does not invalidate UTF-8. let me = unsafe { self.as_bytes_mut() }; me.make_ascii_lowercase() @@ -2740,6 +2742,17 @@ impl str { pub fn substr_range(&self, substr: &str) -> Option> { self.as_bytes().subslice_range(substr.as_bytes()) } + + /// Returns the same string as a string slice `&str`. + /// + /// This method is redundant when used directly on `&str`, but + /// it helps dereferencing other string-like types to string slices, + /// for example references to `Box` or `Arc`. + #[inline] + #[unstable(feature = "str_as_str", issue = "130366")] + pub fn as_str(&self) -> &str { + self + } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/core/src/task/wake.rs b/library/core/src/task/wake.rs index a5103499c8a0d..fc549abd43365 100644 --- a/library/core/src/task/wake.rs +++ b/library/core/src/task/wake.rs @@ -2,7 +2,7 @@ use crate::any::Any; use crate::marker::PhantomData; -use crate::mem::{transmute, ManuallyDrop}; +use crate::mem::{ManuallyDrop, transmute}; use crate::panic::AssertUnwindSafe; use crate::{fmt, ptr}; diff --git a/library/core/tests/error.rs b/library/core/tests/error.rs index 5e20c34ca6ced..996566d3848bd 100644 --- a/library/core/tests/error.rs +++ b/library/core/tests/error.rs @@ -1,4 +1,4 @@ -use core::error::{request_ref, request_value, Request}; +use core::error::{Request, request_ref, request_value}; // Test the `Request` API. #[derive(Debug)] diff --git a/library/core/tests/future.rs b/library/core/tests/future.rs index 93aca72d59082..ebfe5a0a66dc5 100644 --- a/library/core/tests/future.rs +++ b/library/core/tests/future.rs @@ -1,4 +1,4 @@ -use std::future::{join, Future}; +use std::future::{Future, join}; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll, Wake}; diff --git a/library/core/tests/iter/adapters/map_windows.rs b/library/core/tests/iter/adapters/map_windows.rs index 01cebc9b27fd8..b677f1cfd55e7 100644 --- a/library/core/tests/iter/adapters/map_windows.rs +++ b/library/core/tests/iter/adapters/map_windows.rs @@ -159,10 +159,11 @@ fn output_n2() { >::new(), ); assert_eq!("ab".chars().map_windows(|a: &[_; 2]| *a).collect::>(), vec![['a', 'b']]); - assert_eq!( - "abcd".chars().map_windows(|a: &[_; 2]| *a).collect::>(), - vec![['a', 'b'], ['b', 'c'], ['c', 'd']], - ); + assert_eq!("abcd".chars().map_windows(|a: &[_; 2]| *a).collect::>(), vec![ + ['a', 'b'], + ['b', 'c'], + ['c', 'd'] + ],); } #[test] diff --git a/library/core/tests/iter/adapters/zip.rs b/library/core/tests/iter/adapters/zip.rs index 94b49bac45337..70392dca0fa17 100644 --- a/library/core/tests/iter/adapters/zip.rs +++ b/library/core/tests/iter/adapters/zip.rs @@ -240,7 +240,7 @@ fn test_zip_trusted_random_access_composition() { #[test] #[cfg(panic = "unwind")] fn test_zip_trusted_random_access_next_back_drop() { - use std::panic::{catch_unwind, AssertUnwindSafe}; + use std::panic::{AssertUnwindSafe, catch_unwind}; let mut counter = 0; diff --git a/library/core/tests/lib.rs b/library/core/tests/lib.rs index 5315ac856f692..604c0d4874362 100644 --- a/library/core/tests/lib.rs +++ b/library/core/tests/lib.rs @@ -21,7 +21,6 @@ #![feature(const_cell_into_inner)] #![feature(const_hash)] #![feature(const_heap)] -#![feature(const_intrinsic_copy)] #![feature(const_ip)] #![feature(const_ipv4)] #![feature(const_ipv6)] diff --git a/library/core/tests/num/bignum.rs b/library/core/tests/num/bignum.rs index 416e7cea7a67b..f213fd5366cbf 100644 --- a/library/core/tests/num/bignum.rs +++ b/library/core/tests/num/bignum.rs @@ -1,5 +1,5 @@ -use core::num::bignum::tests::Big8x3 as Big; use core::num::bignum::Big32x40; +use core::num::bignum::tests::Big8x3 as Big; #[test] #[should_panic] diff --git a/library/core/tests/num/flt2dec/mod.rs b/library/core/tests/num/flt2dec/mod.rs index 070a53edc2e0f..3d82522481316 100644 --- a/library/core/tests/num/flt2dec/mod.rs +++ b/library/core/tests/num/flt2dec/mod.rs @@ -1,6 +1,6 @@ use core::num::flt2dec::{ - decode, round_up, to_exact_exp_str, to_exact_fixed_str, to_shortest_exp_str, to_shortest_str, - DecodableFloat, Decoded, FullDecoded, Sign, MAX_SIG_DIGITS, + DecodableFloat, Decoded, FullDecoded, MAX_SIG_DIGITS, Sign, decode, round_up, to_exact_exp_str, + to_exact_fixed_str, to_shortest_exp_str, to_shortest_str, }; use core::num::fmt::{Formatted, Part}; use std::mem::MaybeUninit; diff --git a/library/core/tests/num/flt2dec/random.rs b/library/core/tests/num/flt2dec/random.rs index 4817a66638391..99fc23af7ea9d 100644 --- a/library/core/tests/num/flt2dec/random.rs +++ b/library/core/tests/num/flt2dec/random.rs @@ -1,7 +1,7 @@ #![cfg(not(target_arch = "wasm32"))] use core::num::flt2dec::strategy::grisu::{format_exact_opt, format_shortest_opt}; -use core::num::flt2dec::{decode, DecodableFloat, Decoded, FullDecoded, MAX_SIG_DIGITS}; +use core::num::flt2dec::{DecodableFloat, Decoded, FullDecoded, MAX_SIG_DIGITS, decode}; use std::mem::MaybeUninit; use std::str; diff --git a/library/core/tests/num/mod.rs b/library/core/tests/num/mod.rs index b14fe0b22c311..6da9b9a13293a 100644 --- a/library/core/tests/num/mod.rs +++ b/library/core/tests/num/mod.rs @@ -1,5 +1,5 @@ use core::fmt::Debug; -use core::num::{can_not_overflow, IntErrorKind, ParseIntError, TryFromIntError}; +use core::num::{IntErrorKind, ParseIntError, TryFromIntError, can_not_overflow}; use core::ops::{Add, Div, Mul, Rem, Sub}; use core::str::FromStr; diff --git a/library/core/tests/pin_macro.rs b/library/core/tests/pin_macro.rs index 36c6972515a96..43542397a6136 100644 --- a/library/core/tests/pin_macro.rs +++ b/library/core/tests/pin_macro.rs @@ -2,7 +2,7 @@ use core::marker::PhantomPinned; use core::mem::{drop as stuff, transmute}; -use core::pin::{pin, Pin}; +use core::pin::{Pin, pin}; #[test] fn basic() { diff --git a/library/core/tests/slice.rs b/library/core/tests/slice.rs index cdefb5d3eb201..7197f3812e542 100644 --- a/library/core/tests/slice.rs +++ b/library/core/tests/slice.rs @@ -1857,8 +1857,8 @@ fn sort_unstable() { fn select_nth_unstable() { use core::cmp::Ordering::{Equal, Greater, Less}; - use rand::seq::SliceRandom; use rand::Rng; + use rand::seq::SliceRandom; let mut rng = crate::test_rng(); diff --git a/library/core/tests/waker.rs b/library/core/tests/waker.rs index 8f6bf0565fc35..4889b8959ece4 100644 --- a/library/core/tests/waker.rs +++ b/library/core/tests/waker.rs @@ -22,7 +22,7 @@ static WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new( // https://github.com/rust-lang/rust/issues/102012#issuecomment-1915282956 mod nop_waker { - use core::future::{ready, Future}; + use core::future::{Future, ready}; use core::pin::Pin; use core::task::{Context, Poll, RawWaker, RawWakerVTable, Waker}; diff --git a/library/panic_unwind/src/emcc.rs b/library/panic_unwind/src/emcc.rs index 86a43184fb529..a4cbb1875d534 100644 --- a/library/panic_unwind/src/emcc.rs +++ b/library/panic_unwind/src/emcc.rs @@ -98,14 +98,11 @@ pub unsafe fn panic(data: Box) -> u32 { if exception.is_null() { return uw::_URC_FATAL_PHASE1_ERROR as u32; } - ptr::write( - exception, - Exception { - canary: &EXCEPTION_TYPE_INFO, - caught: AtomicBool::new(false), - data: Some(data), - }, - ); + ptr::write(exception, Exception { + canary: &EXCEPTION_TYPE_INFO, + caught: AtomicBool::new(false), + data: Some(data), + }); __cxa_throw(exception as *mut _, &EXCEPTION_TYPE_INFO, exception_cleanup); } diff --git a/library/portable-simd/crates/core_simd/src/lib.rs b/library/portable-simd/crates/core_simd/src/lib.rs index 331b66262490c..cc6246b4a0d41 100644 --- a/library/portable-simd/crates/core_simd/src/lib.rs +++ b/library/portable-simd/crates/core_simd/src/lib.rs @@ -1,8 +1,6 @@ #![no_std] #![feature( - const_intrinsic_copy, const_refs_to_cell, - const_maybe_uninit_as_mut_ptr, const_mut_refs, convert_float_to_int, core_intrinsics, diff --git a/library/proc_macro/src/lib.rs b/library/proc_macro/src/lib.rs index 72b53c60f7439..5522d556a5975 100644 --- a/library/proc_macro/src/lib.rs +++ b/library/proc_macro/src/lib.rs @@ -54,7 +54,7 @@ use std::{error, fmt}; #[unstable(feature = "proc_macro_diagnostic", issue = "54140")] pub use diagnostic::{Diagnostic, Level, MultiSpan}; -use crate::escape::{escape_bytes, EscapeOptions}; +use crate::escape::{EscapeOptions, escape_bytes}; /// Determines whether proc_macro has been made accessible to the currently /// running program. @@ -371,7 +371,7 @@ impl Extend for TokenStream { /// Public implementation details for the `TokenStream` type, such as iterators. #[stable(feature = "proc_macro_lib2", since = "1.29.0")] pub mod token_stream { - use crate::{bridge, Group, Ident, Literal, Punct, TokenStream, TokenTree}; + use crate::{Group, Ident, Literal, Punct, TokenStream, TokenTree, bridge}; /// An iterator over `TokenStream`'s `TokenTree`s. /// The iteration is "shallow", e.g., the iterator doesn't recurse into delimited groups, diff --git a/library/std/Cargo.toml b/library/std/Cargo.toml index 9a31fd21dc71a..ea11586f9a519 100644 --- a/library/std/Cargo.toml +++ b/library/std/Cargo.toml @@ -23,6 +23,10 @@ unwind = { path = "../unwind" } hashbrown = { version = "0.14", default-features = false, features = [ 'rustc-dep-of-std', ] } +# FIXME(#127890): `object` depends on `memchr`, but `memchr` > v2.5 causes +# issues with LTO. This dependency is not used directly, but pin it here so +# it resolves to 2.5. To be removed once rust-lang/rust#127890 is fixed. +memchr = { version = "=2.5.0", default-features = false, features = ["rustc-dep-of-std"] } std_detect = { path = "../stdarch/crates/std_detect", default-features = false, features = [ 'rustc-dep-of-std', ] } diff --git a/library/std/src/ascii.rs b/library/std/src/ascii.rs index 3a2880fd50904..3813f3237fb34 100644 --- a/library/std/src/ascii.rs +++ b/library/std/src/ascii.rs @@ -16,7 +16,7 @@ #[unstable(feature = "ascii_char", issue = "110998")] pub use core::ascii::Char; #[stable(feature = "rust1", since = "1.0.0")] -pub use core::ascii::{escape_default, EscapeDefault}; +pub use core::ascii::{EscapeDefault, escape_default}; /// Extension methods for ASCII-subset only operations. /// diff --git a/library/std/src/backtrace.rs b/library/std/src/backtrace.rs index 7df9a8a14b00c..fc333d7ff3f95 100644 --- a/library/std/src/backtrace.rs +++ b/library/std/src/backtrace.rs @@ -91,9 +91,9 @@ mod tests; use crate::backtrace_rs::{self, BytesOrWideString}; use crate::ffi::c_void; use crate::panic::UnwindSafe; +use crate::sync::LazyLock; use crate::sync::atomic::AtomicU8; use crate::sync::atomic::Ordering::Relaxed; -use crate::sync::LazyLock; use crate::sys::backtrace::{lock, output_filename, set_image_base}; use crate::{env, fmt}; diff --git a/library/std/src/collections/hash/map/tests.rs b/library/std/src/collections/hash/map/tests.rs index 6641197c3724a..c28dd7b6b5059 100644 --- a/library/std/src/collections/hash/map/tests.rs +++ b/library/std/src/collections/hash/map/tests.rs @@ -947,7 +947,7 @@ fn test_raw_entry() { mod test_extract_if { use super::*; - use crate::panic::{catch_unwind, AssertUnwindSafe}; + use crate::panic::{AssertUnwindSafe, catch_unwind}; use crate::sync::atomic::{AtomicUsize, Ordering}; trait EqSorted: Iterator { diff --git a/library/std/src/collections/hash/set/tests.rs b/library/std/src/collections/hash/set/tests.rs index 4e6351652721f..7aa2167e21321 100644 --- a/library/std/src/collections/hash/set/tests.rs +++ b/library/std/src/collections/hash/set/tests.rs @@ -1,8 +1,8 @@ use super::HashSet; use crate::hash::RandomState; -use crate::panic::{catch_unwind, AssertUnwindSafe}; -use crate::sync::atomic::{AtomicU32, Ordering}; +use crate::panic::{AssertUnwindSafe, catch_unwind}; use crate::sync::Arc; +use crate::sync::atomic::{AtomicU32, Ordering}; #[test] fn test_zero_capacities() { diff --git a/library/std/src/collections/mod.rs b/library/std/src/collections/mod.rs index 21bebff96b956..889ed3c538035 100644 --- a/library/std/src/collections/mod.rs +++ b/library/std/src/collections/mod.rs @@ -418,13 +418,13 @@ pub use alloc_crate::collections::TryReserveError; )] pub use alloc_crate::collections::TryReserveErrorKind; #[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::collections::{binary_heap, btree_map, btree_set}; -#[stable(feature = "rust1", since = "1.0.0")] -pub use alloc_crate::collections::{linked_list, vec_deque}; -#[stable(feature = "rust1", since = "1.0.0")] pub use alloc_crate::collections::{BTreeMap, BTreeSet, BinaryHeap}; #[stable(feature = "rust1", since = "1.0.0")] pub use alloc_crate::collections::{LinkedList, VecDeque}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::collections::{binary_heap, btree_map, btree_set}; +#[stable(feature = "rust1", since = "1.0.0")] +pub use alloc_crate::collections::{linked_list, vec_deque}; #[stable(feature = "rust1", since = "1.0.0")] #[doc(inline)] diff --git a/library/std/src/error.rs b/library/std/src/error.rs index 3e17431af45b0..b3e63aaf1c567 100644 --- a/library/std/src/error.rs +++ b/library/std/src/error.rs @@ -7,7 +7,7 @@ mod tests; #[stable(feature = "rust1", since = "1.0.0")] pub use core::error::Error; #[unstable(feature = "error_generic_member_access", issue = "99301")] -pub use core::error::{request_ref, request_value, Request}; +pub use core::error::{Request, request_ref, request_value}; use crate::backtrace::Backtrace; use crate::fmt::{self, Write}; diff --git a/library/std/src/f32.rs b/library/std/src/f32.rs index cafbe9761da19..fa0b3ef6484f7 100644 --- a/library/std/src/f32.rs +++ b/library/std/src/f32.rs @@ -18,8 +18,8 @@ mod tests; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::f32::{ - consts, DIGITS, EPSILON, INFINITY, MANTISSA_DIGITS, MAX, MAX_10_EXP, MAX_EXP, MIN, MIN_10_EXP, - MIN_EXP, MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, + DIGITS, EPSILON, INFINITY, MANTISSA_DIGITS, MAX, MAX_10_EXP, MAX_EXP, MIN, MIN_10_EXP, MIN_EXP, + MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, consts, }; #[cfg(not(test))] diff --git a/library/std/src/f64.rs b/library/std/src/f64.rs index fba283e3a44bc..9fa43a6742ea6 100644 --- a/library/std/src/f64.rs +++ b/library/std/src/f64.rs @@ -18,8 +18,8 @@ mod tests; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::f64::{ - consts, DIGITS, EPSILON, INFINITY, MANTISSA_DIGITS, MAX, MAX_10_EXP, MAX_EXP, MIN, MIN_10_EXP, - MIN_EXP, MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, + DIGITS, EPSILON, INFINITY, MANTISSA_DIGITS, MAX, MAX_10_EXP, MAX_EXP, MIN, MIN_10_EXP, MIN_EXP, + MIN_POSITIVE, NAN, NEG_INFINITY, RADIX, consts, }; #[cfg(not(test))] diff --git a/library/std/src/ffi/mod.rs b/library/std/src/ffi/mod.rs index 2b67750c2f0a9..469136be8838a 100644 --- a/library/std/src/ffi/mod.rs +++ b/library/std/src/ffi/mod.rs @@ -166,11 +166,6 @@ pub mod c_str; #[stable(feature = "core_c_void", since = "1.30.0")] pub use core::ffi::c_void; -#[stable(feature = "core_ffi_c", since = "1.64.0")] -pub use core::ffi::{ - c_char, c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, - c_ulong, c_ulonglong, c_ushort, -}; #[unstable( feature = "c_variadic", reason = "the `c_variadic` feature has not been properly tested on \ @@ -178,6 +173,11 @@ pub use core::ffi::{ issue = "44930" )] pub use core::ffi::{VaList, VaListImpl}; +#[stable(feature = "core_ffi_c", since = "1.64.0")] +pub use core::ffi::{ + c_char, c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, + c_ulong, c_ulonglong, c_ushort, +}; #[doc(no_inline)] #[stable(feature = "cstr_from_bytes_until_nul", since = "1.69.0")] diff --git a/library/std/src/fs/tests.rs b/library/std/src/fs/tests.rs index fb8dd2b0ca149..412603ddea3d1 100644 --- a/library/std/src/fs/tests.rs +++ b/library/std/src/fs/tests.rs @@ -11,10 +11,10 @@ use crate::os::unix::fs::symlink as symlink_file; #[cfg(unix)] use crate::os::unix::fs::symlink as junction_point; #[cfg(windows)] -use crate::os::windows::fs::{junction_point, symlink_dir, symlink_file, OpenOptionsExt}; +use crate::os::windows::fs::{OpenOptionsExt, junction_point, symlink_dir, symlink_file}; use crate::path::Path; use crate::sync::Arc; -use crate::sys_common::io::test::{tmpdir, TempDir}; +use crate::sys_common::io::test::{TempDir, tmpdir}; use crate::time::{Duration, Instant, SystemTime}; use crate::{env, str, thread}; diff --git a/library/std/src/hash/random.rs b/library/std/src/hash/random.rs index 8ef45172eac40..40f3a90f60c8a 100644 --- a/library/std/src/hash/random.rs +++ b/library/std/src/hash/random.rs @@ -10,7 +10,8 @@ #[allow(deprecated)] use super::{BuildHasher, Hasher, SipHasher13}; use crate::cell::Cell; -use crate::{fmt, sys}; +use crate::fmt; +use crate::sys::random::hashmap_random_keys; /// `RandomState` is the default state for [`HashMap`] types. /// @@ -65,7 +66,7 @@ impl RandomState { // increment one of the seeds on every RandomState creation, giving // every corresponding HashMap a different iteration order. thread_local!(static KEYS: Cell<(u64, u64)> = { - Cell::new(sys::hashmap_random_keys()) + Cell::new(hashmap_random_keys()) }); KEYS.with(|keys| { diff --git a/library/std/src/io/buffered/bufreader.rs b/library/std/src/io/buffered/bufreader.rs index 7dcca2707ba10..e51dde994de45 100644 --- a/library/std/src/io/buffered/bufreader.rs +++ b/library/std/src/io/buffered/bufreader.rs @@ -4,8 +4,8 @@ use buffer::Buffer; use crate::fmt; use crate::io::{ - self, uninlined_slow_read_byte, BorrowedCursor, BufRead, IoSliceMut, Read, Seek, SeekFrom, - SizeHint, SpecReadByte, DEFAULT_BUF_SIZE, + self, BorrowedCursor, BufRead, DEFAULT_BUF_SIZE, IoSliceMut, Read, Seek, SeekFrom, SizeHint, + SpecReadByte, uninlined_slow_read_byte, }; /// The `BufReader` struct adds buffering to any reader. diff --git a/library/std/src/io/buffered/bufwriter.rs b/library/std/src/io/buffered/bufwriter.rs index 21650d467446e..13516d3b961f1 100644 --- a/library/std/src/io/buffered/bufwriter.rs +++ b/library/std/src/io/buffered/bufwriter.rs @@ -1,5 +1,5 @@ use crate::io::{ - self, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write, DEFAULT_BUF_SIZE, + self, DEFAULT_BUF_SIZE, ErrorKind, IntoInnerError, IoSlice, Seek, SeekFrom, Write, }; use crate::mem::{self, ManuallyDrop}; use crate::{error, fmt, ptr}; diff --git a/library/std/src/io/copy.rs b/library/std/src/io/copy.rs index d49866345cbf6..8d733325b3be7 100644 --- a/library/std/src/io/copy.rs +++ b/library/std/src/io/copy.rs @@ -1,4 +1,4 @@ -use super::{BorrowedBuf, BufReader, BufWriter, Read, Result, Write, DEFAULT_BUF_SIZE}; +use super::{BorrowedBuf, BufReader, BufWriter, DEFAULT_BUF_SIZE, Read, Result, Write}; use crate::alloc::Allocator; use crate::cmp; use crate::collections::VecDeque; diff --git a/library/std/src/io/copy/tests.rs b/library/std/src/io/copy/tests.rs index 7e08826a7e1d8..2e0eb6cdce666 100644 --- a/library/std/src/io/copy/tests.rs +++ b/library/std/src/io/copy/tests.rs @@ -122,8 +122,8 @@ mod io_benches { use test::Bencher; use crate::fs::{File, OpenOptions}; - use crate::io::prelude::*; use crate::io::BufReader; + use crate::io::prelude::*; #[bench] fn bench_copy_buf_reader(b: &mut Bencher) { diff --git a/library/std/src/io/error.rs b/library/std/src/io/error.rs index 6ecd9469c1740..795cc64e957da 100644 --- a/library/std/src/io/error.rs +++ b/library/std/src/io/error.rs @@ -400,6 +400,11 @@ pub enum ErrorKind { #[stable(feature = "out_of_memory_error", since = "1.54.0")] OutOfMemory, + /// The operation was partially successful and needs to be checked + /// later on due to not blocking. + #[unstable(feature = "io_error_inprogress", issue = "none")] + InProgress, + // "Unusual" error kinds which do not correspond simply to (sets // of) OS error codes, should be added just above this comment. // `Other` and `Uncategorized` should remain at the end: @@ -449,6 +454,7 @@ impl ErrorKind { FilesystemQuotaExceeded => "filesystem quota exceeded", HostUnreachable => "host unreachable", Interrupted => "operation interrupted", + InProgress => "in progress", InvalidData => "invalid data", InvalidFilename => "invalid filename", InvalidInput => "invalid input parameter", diff --git a/library/std/src/io/error/repr_bitpacked.rs b/library/std/src/io/error/repr_bitpacked.rs index 9d3ade46bd929..80ba8455df347 100644 --- a/library/std/src/io/error/repr_bitpacked.rs +++ b/library/std/src/io/error/repr_bitpacked.rs @@ -348,6 +348,7 @@ fn kind_from_prim(ek: u32) -> Option { UnexpectedEof, Unsupported, OutOfMemory, + InProgress, Uncategorized, }) } diff --git a/library/std/src/io/error/tests.rs b/library/std/src/io/error/tests.rs index 064e2e36b7a1d..00d04984a3854 100644 --- a/library/std/src/io/error/tests.rs +++ b/library/std/src/io/error/tests.rs @@ -1,4 +1,4 @@ -use super::{const_io_error, Custom, Error, ErrorData, ErrorKind, Repr, SimpleMessage}; +use super::{Custom, Error, ErrorData, ErrorKind, Repr, SimpleMessage, const_io_error}; use crate::assert_matches::assert_matches; use crate::mem::size_of; use crate::sys::decode_error_kind; diff --git a/library/std/src/io/mod.rs b/library/std/src/io/mod.rs index 2a4262b236780..0b57d01f27346 100644 --- a/library/std/src/io/mod.rs +++ b/library/std/src/io/mod.rs @@ -307,9 +307,9 @@ pub(crate) use error::const_io_error; pub use self::buffered::WriterPanicked; #[unstable(feature = "raw_os_error_ty", issue = "107792")] pub use self::error::RawOsError; -pub(crate) use self::stdio::attempt_print_to_stderr; #[stable(feature = "is_terminal", since = "1.70.0")] pub use self::stdio::IsTerminal; +pub(crate) use self::stdio::attempt_print_to_stderr; #[unstable(feature = "print_internals", issue = "none")] #[doc(hidden)] pub use self::stdio::{_eprint, _print}; @@ -322,8 +322,8 @@ pub use self::{ copy::copy, cursor::Cursor, error::{Error, ErrorKind, Result}, - stdio::{stderr, stdin, stdout, Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock}, - util::{empty, repeat, sink, Empty, Repeat, Sink}, + stdio::{Stderr, StderrLock, Stdin, StdinLock, Stdout, StdoutLock, stderr, stdin, stdout}, + util::{Empty, Repeat, Sink, empty, repeat, sink}, }; use crate::mem::take; use crate::ops::{Deref, DerefMut}; @@ -398,8 +398,7 @@ where // - avoid passing large buffers to readers that always initialize the free capacity if they perform short reads (#23815, #23820) // - pass large buffers to readers that do not initialize the spare capacity. this can amortize per-call overheads // - and finally pass not-too-small and not-too-large buffers to Windows read APIs because they manage to suffer from both problems -// at the same time, i.e. small reads suffer from syscall overhead, all reads incur initialization cost -// proportional to buffer size (#110650) +// at the same time, i.e. small reads suffer from syscall overhead, all reads incur costs proportional to buffer size (#110650) // pub(crate) fn default_read_to_end( r: &mut R, @@ -444,6 +443,8 @@ pub(crate) fn default_read_to_end( } } + let mut consecutive_short_reads = 0; + loop { if buf.len() == buf.capacity() && buf.capacity() == start_cap { // The buffer might be an exact fit. Let's read into a probe buffer @@ -489,6 +490,12 @@ pub(crate) fn default_read_to_end( return Ok(buf.len() - start_len); } + if bytes_read < buf_len { + consecutive_short_reads += 1; + } else { + consecutive_short_reads = 0; + } + // store how much was initialized but not filled initialized = unfilled_but_initialized; @@ -503,7 +510,10 @@ pub(crate) fn default_read_to_end( // The reader is returning short reads but it doesn't call ensure_init(). // In that case we no longer need to restrict read sizes to avoid // initialization costs. - if !was_fully_initialized { + // When reading from disk we usually don't get any short reads except at EOF. + // So we wait for at least 2 short reads before uncapping the read buffer; + // this helps with the Windows issue. + if !was_fully_initialized && consecutive_short_reads > 1 { max_read_size = usize::MAX; } diff --git a/library/std/src/io/stdio/tests.rs b/library/std/src/io/stdio/tests.rs index f89fd27ce6c23..ea76a271d12bf 100644 --- a/library/std/src/io/stdio/tests.rs +++ b/library/std/src/io/stdio/tests.rs @@ -159,8 +159,7 @@ where assert_eq!(rx2.recv().unwrap(), Release2); // release th2 th2.join().unwrap(); th1.join().unwrap(); - assert_eq!( - *log.lock().unwrap(), - [Start1, Acquire1, Start2, Release1, Acquire2, Release2, Acquire1, Release1] - ); + assert_eq!(*log.lock().unwrap(), [ + Start1, Acquire1, Start2, Release1, Acquire2, Release2, Acquire1, Release1 + ]); } diff --git a/library/std/src/io/tests.rs b/library/std/src/io/tests.rs index 24e5a1dfd5c00..f551dcd401efc 100644 --- a/library/std/src/io/tests.rs +++ b/library/std/src/io/tests.rs @@ -1,7 +1,7 @@ -use super::{repeat, BorrowedBuf, Cursor, SeekFrom}; +use super::{BorrowedBuf, Cursor, SeekFrom, repeat}; use crate::cmp::{self, min}; use crate::io::{ - self, BufRead, BufReader, IoSlice, IoSliceMut, Read, Seek, Write, DEFAULT_BUF_SIZE, + self, BufRead, BufReader, DEFAULT_BUF_SIZE, IoSlice, IoSliceMut, Read, Seek, Write, }; use crate::mem::MaybeUninit; use crate::ops::Deref; diff --git a/library/std/src/io/util/tests.rs b/library/std/src/io/util/tests.rs index 1dff3f3832bd7..0599a881af179 100644 --- a/library/std/src/io/util/tests.rs +++ b/library/std/src/io/util/tests.rs @@ -1,5 +1,5 @@ use crate::io::prelude::*; -use crate::io::{empty, repeat, sink, BorrowedBuf, Empty, Repeat, SeekFrom, Sink}; +use crate::io::{BorrowedBuf, Empty, Repeat, SeekFrom, Sink, empty, repeat, sink}; use crate::mem::MaybeUninit; #[test] diff --git a/library/std/src/lib.rs b/library/std/src/lib.rs index e4ba5e47613b2..4d93af6ea652e 100644 --- a/library/std/src/lib.rs +++ b/library/std/src/lib.rs @@ -32,13 +32,17 @@ //! //! Once you are familiar with the contents of the standard library you may //! begin to find the verbosity of the prose distracting. At this stage in your -//! development you may want to press the `[-]` button near the top of the -//! page to collapse it into a more skimmable view. -//! -//! While you are looking at that `[-]` button also notice the `source` -//! link. Rust's API documentation comes with the source code and you are -//! encouraged to read it. The standard library source is generally high -//! quality and a peek behind the curtains is often enlightening. +//! development you may want to press the +//! +//! Summary button near the +//! top of the page to collapse it into a more skimmable view. +//! +//! While you are looking at the top of the page, also notice the +//! source link. Rust's API documentation comes with the source +//! code and you are encouraged to read it. The standard library source is +//! generally high quality and a peek behind the curtains is +//! often enlightening. //! //! # What is in the standard library documentation? //! @@ -318,6 +322,7 @@ // // Library features (core): // tidy-alphabetical-start +#![feature(array_chunks)] #![feature(c_str_module)] #![feature(char_internals)] #![feature(clone_to_uninit)] @@ -348,6 +353,7 @@ #![feature(prelude_2024)] #![feature(ptr_as_uninit)] #![feature(ptr_mask)] +#![feature(random)] #![feature(slice_internals)] #![feature(slice_ptr_get)] #![feature(slice_range)] @@ -493,9 +499,9 @@ pub use core::default; pub use core::future; #[stable(feature = "core_hint", since = "1.27.0")] pub use core::hint; -#[stable(feature = "i128", since = "1.26.0")] +#[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] -pub use core::i128; +pub use core::i8; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::i16; @@ -505,9 +511,9 @@ pub use core::i32; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::i64; -#[stable(feature = "rust1", since = "1.0.0")] +#[stable(feature = "i128", since = "1.26.0")] #[allow(deprecated, deprecated_in_future)] -pub use core::i8; +pub use core::i128; #[stable(feature = "rust1", since = "1.0.0")] pub use core::intrinsics; #[stable(feature = "rust1", since = "1.0.0")] @@ -529,9 +535,9 @@ pub use core::pin; pub use core::ptr; #[stable(feature = "rust1", since = "1.0.0")] pub use core::result; -#[stable(feature = "i128", since = "1.26.0")] +#[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] -pub use core::u128; +pub use core::u8; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::u16; @@ -541,9 +547,9 @@ pub use core::u32; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::u64; -#[stable(feature = "rust1", since = "1.0.0")] +#[stable(feature = "i128", since = "1.26.0")] #[allow(deprecated, deprecated_in_future)] -pub use core::u8; +pub use core::u128; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated, deprecated_in_future)] pub use core::usize; @@ -595,6 +601,8 @@ pub mod path; #[unstable(feature = "anonymous_pipe", issue = "127154")] pub mod pipe; pub mod process; +#[unstable(feature = "random", issue = "130703")] +pub mod random; pub mod sync; pub mod time; @@ -649,9 +657,9 @@ pub mod arch { #[stable(feature = "simd_x86", since = "1.27.0")] pub use std_detect::is_x86_feature_detected; #[unstable(feature = "stdarch_mips_feature_detection", issue = "111188")] - pub use std_detect::{is_mips64_feature_detected, is_mips_feature_detected}; + pub use std_detect::{is_mips_feature_detected, is_mips64_feature_detected}; #[unstable(feature = "stdarch_powerpc_feature_detection", issue = "111191")] - pub use std_detect::{is_powerpc64_feature_detected, is_powerpc_feature_detected}; + pub use std_detect::{is_powerpc_feature_detected, is_powerpc64_feature_detected}; } // This was stabilized in the crate root so we have to keep it there. diff --git a/library/std/src/net/ip_addr/tests.rs b/library/std/src/net/ip_addr/tests.rs index ab99c0c2fcc16..7bed6f8a0f523 100644 --- a/library/std/src/net/ip_addr/tests.rs +++ b/library/std/src/net/ip_addr/tests.rs @@ -1,5 +1,5 @@ -use crate::net::test::{sa4, tsa}; use crate::net::Ipv4Addr; +use crate::net::test::{sa4, tsa}; #[test] fn to_socket_addr_socketaddr() { diff --git a/library/std/src/net/tcp.rs b/library/std/src/net/tcp.rs index 22d2dfe65a249..06ed4f6a03d43 100644 --- a/library/std/src/net/tcp.rs +++ b/library/std/src/net/tcp.rs @@ -8,7 +8,7 @@ use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::iter::FusedIterator; use crate::net::{Shutdown, SocketAddr, ToSocketAddrs}; -use crate::sys_common::{net as net_imp, AsInner, FromInner, IntoInner}; +use crate::sys_common::{AsInner, FromInner, IntoInner, net as net_imp}; use crate::time::Duration; /// A TCP stream between a local and a remote socket. diff --git a/library/std/src/net/udp.rs b/library/std/src/net/udp.rs index 32e9086003d6b..d4252cb87ac22 100644 --- a/library/std/src/net/udp.rs +++ b/library/std/src/net/udp.rs @@ -4,7 +4,7 @@ mod tests; use crate::fmt; use crate::io::{self, ErrorKind}; use crate::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; -use crate::sys_common::{net as net_imp, AsInner, FromInner, IntoInner}; +use crate::sys_common::{AsInner, FromInner, IntoInner, net as net_imp}; use crate::time::Duration; /// A UDP socket. diff --git a/library/std/src/num.rs b/library/std/src/num.rs index c1e6e7e628c83..d2f679e7dde54 100644 --- a/library/std/src/num.rs +++ b/library/std/src/num.rs @@ -26,9 +26,9 @@ pub use core::num::ZeroablePrimitive; #[stable(feature = "rust1", since = "1.0.0")] pub use core::num::{FpCategory, ParseFloatError, ParseIntError, TryFromIntError}; #[stable(feature = "signed_nonzero", since = "1.34.0")] -pub use core::num::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize}; +pub use core::num::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize}; #[stable(feature = "nonzero", since = "1.28.0")] -pub use core::num::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize}; +pub use core::num::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize}; #[cfg(test)] use crate::fmt; diff --git a/library/std/src/os/fortanix_sgx/mod.rs b/library/std/src/os/fortanix_sgx/mod.rs index 64f4d97ca95e2..2b5ccbe98f1b3 100644 --- a/library/std/src/os/fortanix_sgx/mod.rs +++ b/library/std/src/os/fortanix_sgx/mod.rs @@ -22,12 +22,12 @@ pub mod usercalls { /// Lowest-level interfaces to usercalls and usercall ABI type definitions. pub mod raw { pub use crate::sys::abi::usercalls::raw::{ - accept_stream, alloc, async_queues, bind_stream, close, connect_stream, do_usercall, - exit, flush, free, insecure_time, launch_thread, read, read_alloc, send, wait, write, - ByteBuffer, Cancel, Error, Fd, FifoDescriptor, Register, RegisterArgument, Result, - Return, ReturnValue, Tcs, Usercall, Usercalls as UsercallNrs, EV_RETURNQ_NOT_EMPTY, - EV_UNPARK, EV_USERCALLQ_NOT_FULL, FD_STDERR, FD_STDIN, FD_STDOUT, RESULT_SUCCESS, - USERCALL_USER_DEFINED, WAIT_INDEFINITE, WAIT_NO, + ByteBuffer, Cancel, EV_RETURNQ_NOT_EMPTY, EV_UNPARK, EV_USERCALLQ_NOT_FULL, Error, + FD_STDERR, FD_STDIN, FD_STDOUT, Fd, FifoDescriptor, RESULT_SUCCESS, Register, + RegisterArgument, Result, Return, ReturnValue, Tcs, USERCALL_USER_DEFINED, Usercall, + Usercalls as UsercallNrs, WAIT_INDEFINITE, WAIT_NO, accept_stream, alloc, async_queues, + bind_stream, close, connect_stream, do_usercall, exit, flush, free, insecure_time, + launch_thread, read, read_alloc, send, wait, write, }; } } diff --git a/library/std/src/os/unix/net/ancillary.rs b/library/std/src/os/unix/net/ancillary.rs index 9b487a6298247..c34a3b4e184a4 100644 --- a/library/std/src/os/unix/net/ancillary.rs +++ b/library/std/src/os/unix/net/ancillary.rs @@ -1,6 +1,6 @@ // FIXME: This is currently disabled on *BSD. -use super::{sockaddr_un, SocketAddr}; +use super::{SocketAddr, sockaddr_un}; use crate::io::{self, IoSlice, IoSliceMut}; use crate::marker::PhantomData; use crate::mem::zeroed; diff --git a/library/std/src/os/unix/net/datagram.rs b/library/std/src/os/unix/net/datagram.rs index a605c3d4a2602..48aaddd2d5295 100644 --- a/library/std/src/os/unix/net/datagram.rs +++ b/library/std/src/os/unix/net/datagram.rs @@ -12,9 +12,9 @@ ))] use libc::MSG_NOSIGNAL; +use super::{SocketAddr, sockaddr_un}; #[cfg(any(doc, target_os = "android", target_os = "linux"))] -use super::{recv_vectored_with_ancillary_from, send_vectored_with_ancillary_to, SocketAncillary}; -use super::{sockaddr_un, SocketAddr}; +use super::{SocketAncillary, recv_vectored_with_ancillary_from, send_vectored_with_ancillary_to}; #[cfg(any(doc, target_os = "android", target_os = "linux"))] use crate::io::{IoSlice, IoSliceMut}; use crate::net::Shutdown; diff --git a/library/std/src/os/unix/net/listener.rs b/library/std/src/os/unix/net/listener.rs index a55199c82fc10..440408eb13fa4 100644 --- a/library/std/src/os/unix/net/listener.rs +++ b/library/std/src/os/unix/net/listener.rs @@ -1,4 +1,4 @@ -use super::{sockaddr_un, SocketAddr, UnixStream}; +use super::{SocketAddr, UnixStream, sockaddr_un}; use crate::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}; use crate::path::Path; use crate::sys::cvt; diff --git a/library/std/src/os/unix/net/stream.rs b/library/std/src/os/unix/net/stream.rs index 19fc7b3d8532f..4967c5b89ecce 100644 --- a/library/std/src/os/unix/net/stream.rs +++ b/library/std/src/os/unix/net/stream.rs @@ -1,3 +1,6 @@ +use super::{SocketAddr, sockaddr_un}; +#[cfg(any(doc, target_os = "android", target_os = "linux"))] +use super::{SocketAncillary, recv_vectored_with_ancillary_from, send_vectored_with_ancillary_to}; #[cfg(any( target_os = "android", target_os = "linux", @@ -8,10 +11,7 @@ target_os = "nto", target_vendor = "apple", ))] -use super::{peer_cred, UCred}; -#[cfg(any(doc, target_os = "android", target_os = "linux"))] -use super::{recv_vectored_with_ancillary_from, send_vectored_with_ancillary_to, SocketAncillary}; -use super::{sockaddr_un, SocketAddr}; +use super::{UCred, peer_cred}; use crate::fmt; use crate::io::{self, IoSlice, IoSliceMut}; use crate::net::Shutdown; diff --git a/library/std/src/os/unix/net/ucred.rs b/library/std/src/os/unix/net/ucred.rs index b96e373ad0ae3..c818bd0585868 100644 --- a/library/std/src/os/unix/net/ucred.rs +++ b/library/std/src/os/unix/net/ucred.rs @@ -38,7 +38,7 @@ pub(super) use self::impl_linux::peer_cred; #[cfg(any(target_os = "linux", target_os = "android"))] mod impl_linux { - use libc::{c_void, getsockopt, socklen_t, ucred, SOL_SOCKET, SO_PEERCRED}; + use libc::{SO_PEERCRED, SOL_SOCKET, c_void, getsockopt, socklen_t, ucred}; use super::UCred; use crate::os::unix::io::AsRawFd; @@ -98,7 +98,7 @@ mod impl_bsd { #[cfg(target_vendor = "apple")] mod impl_apple { - use libc::{c_void, getpeereid, getsockopt, pid_t, socklen_t, LOCAL_PEERPID, SOL_LOCAL}; + use libc::{LOCAL_PEERPID, SOL_LOCAL, c_void, getpeereid, getsockopt, pid_t, socklen_t}; use super::UCred; use crate::os::unix::io::AsRawFd; diff --git a/library/std/src/os/xous/ffi/definitions.rs b/library/std/src/os/xous/ffi/definitions.rs index 345005bcc78d7..1b16849af03b0 100644 --- a/library/std/src/os/xous/ffi/definitions.rs +++ b/library/std/src/os/xous/ffi/definitions.rs @@ -126,42 +126,36 @@ impl From for Error { #[stable(feature = "rust1", since = "1.0.0")] impl core::fmt::Display for Error { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - write!( - f, - "{}", - match self { - Error::NoError => "no error occurred", - Error::BadAlignment => "memory was not properly aligned", - Error::BadAddress => "an invalid address was supplied", - Error::OutOfMemory => "the process or service has run out of memory", - Error::MemoryInUse => "the requested address is in use", - Error::InterruptNotFound => - "the requested interrupt does not exist on this platform", - Error::InterruptInUse => "the requested interrupt is currently in use", - Error::InvalidString => "the specified string was not formatted correctly", - Error::ServerExists => "a server with that address already exists", - Error::ServerNotFound => "the requetsed server could not be found", - Error::ProcessNotFound => "the target process does not exist", - Error::ProcessNotChild => - "the requested operation can only be done on child processes", - Error::ProcessTerminated => "the target process has crashed", - Error::Timeout => "the requested operation timed out", - Error::InternalError => "an internal error occurred", - Error::ServerQueueFull => "the server has too many pending messages", - Error::ThreadNotAvailable => "the specified thread does not exist", - Error::UnhandledSyscall => "the kernel did not recognize that syscall", - Error::InvalidSyscall => "the syscall had incorrect parameters", - Error::ShareViolation => "an attempt was made to share memory twice", - Error::InvalidThread => "tried to resume a thread that was not ready", - Error::InvalidPid => "kernel attempted to use a pid that was not valid", - Error::AccessDenied => "no permission to perform the requested operation", - Error::UseBeforeInit => "attempt to use a service before initialization finished", - Error::DoubleFree => "the requested resource was freed twice", - Error::DebugInProgress => "kernel attempted to activate a thread being debugged", - Error::InvalidLimit => "process attempted to adjust an invalid limit", - Error::UnknownError => "an unknown error occurred", - } - ) + write!(f, "{}", match self { + Error::NoError => "no error occurred", + Error::BadAlignment => "memory was not properly aligned", + Error::BadAddress => "an invalid address was supplied", + Error::OutOfMemory => "the process or service has run out of memory", + Error::MemoryInUse => "the requested address is in use", + Error::InterruptNotFound => "the requested interrupt does not exist on this platform", + Error::InterruptInUse => "the requested interrupt is currently in use", + Error::InvalidString => "the specified string was not formatted correctly", + Error::ServerExists => "a server with that address already exists", + Error::ServerNotFound => "the requetsed server could not be found", + Error::ProcessNotFound => "the target process does not exist", + Error::ProcessNotChild => "the requested operation can only be done on child processes", + Error::ProcessTerminated => "the target process has crashed", + Error::Timeout => "the requested operation timed out", + Error::InternalError => "an internal error occurred", + Error::ServerQueueFull => "the server has too many pending messages", + Error::ThreadNotAvailable => "the specified thread does not exist", + Error::UnhandledSyscall => "the kernel did not recognize that syscall", + Error::InvalidSyscall => "the syscall had incorrect parameters", + Error::ShareViolation => "an attempt was made to share memory twice", + Error::InvalidThread => "tried to resume a thread that was not ready", + Error::InvalidPid => "kernel attempted to use a pid that was not valid", + Error::AccessDenied => "no permission to perform the requested operation", + Error::UseBeforeInit => "attempt to use a service before initialization finished", + Error::DoubleFree => "the requested resource was freed twice", + Error::DebugInProgress => "kernel attempted to activate a thread being debugged", + Error::InvalidLimit => "process attempted to adjust an invalid limit", + Error::UnknownError => "an unknown error occurred", + }) } } diff --git a/library/std/src/os/xous/services.rs b/library/std/src/os/xous/services.rs index ddf0236f5ad74..93916750c0547 100644 --- a/library/std/src/os/xous/services.rs +++ b/library/std/src/os/xous/services.rs @@ -19,7 +19,7 @@ pub(crate) use ticktimer::*; mod ns { const NAME_MAX_LENGTH: usize = 64; - use crate::os::xous::ffi::{lend_mut, Connection}; + use crate::os::xous::ffi::{Connection, lend_mut}; // By making this repr(C), the layout of this struct becomes well-defined // and no longer shifts around. // By marking it as `align(4096)` we define that it will be page-aligned, diff --git a/library/std/src/os/xous/services/systime.rs b/library/std/src/os/xous/services/systime.rs index 079ede7aa86c7..de87694b4cdca 100644 --- a/library/std/src/os/xous/services/systime.rs +++ b/library/std/src/os/xous/services/systime.rs @@ -1,6 +1,6 @@ use core::sync::atomic::{AtomicU32, Ordering}; -use crate::os::xous::ffi::{connect, Connection}; +use crate::os::xous::ffi::{Connection, connect}; pub(crate) enum SystimeScalar { GetUtcTimeMs, diff --git a/library/std/src/panic.rs b/library/std/src/panic.rs index 541cf42ab47e6..015cab8948547 100644 --- a/library/std/src/panic.rs +++ b/library/std/src/panic.rs @@ -231,11 +231,11 @@ pub macro panic_2015 { }), } +#[stable(feature = "panic_hooks", since = "1.10.0")] +pub use core::panic::Location; #[doc(hidden)] #[unstable(feature = "edition_panic", issue = "none", reason = "use panic!() instead")] pub use core::panic::panic_2021; -#[stable(feature = "panic_hooks", since = "1.10.0")] -pub use core::panic::Location; #[stable(feature = "catch_unwind", since = "1.9.0")] pub use core::panic::{AssertUnwindSafe, RefUnwindSafe, UnwindSafe}; diff --git a/library/std/src/path.rs b/library/std/src/path.rs index aa9f63d915a24..e3ff7d199ccc8 100644 --- a/library/std/src/path.rs +++ b/library/std/src/path.rs @@ -75,14 +75,14 @@ use core::clone::CloneToUninit; use crate::borrow::{Borrow, Cow}; use crate::collections::TryReserveError; use crate::error::Error; -use crate::ffi::{os_str, OsStr, OsString}; +use crate::ffi::{OsStr, OsString, os_str}; use crate::hash::{Hash, Hasher}; use crate::iter::FusedIterator; use crate::ops::{self, Deref}; use crate::rc::Rc; use crate::str::FromStr; use crate::sync::Arc; -use crate::sys::path::{is_sep_byte, is_verbatim_sep, parse_prefix, MAIN_SEP_STR}; +use crate::sys::path::{MAIN_SEP_STR, is_sep_byte, is_verbatim_sep, parse_prefix}; use crate::{cmp, fmt, fs, io, sys}; //////////////////////////////////////////////////////////////////////////////// diff --git a/library/std/src/pipe.rs b/library/std/src/pipe.rs index aa4c7014fe918..891032e94a669 100644 --- a/library/std/src/pipe.rs +++ b/library/std/src/pipe.rs @@ -12,7 +12,7 @@ //! ``` use crate::io; -use crate::sys::anonymous_pipe::{pipe as pipe_inner, AnonPipe}; +use crate::sys::anonymous_pipe::{AnonPipe, pipe as pipe_inner}; /// Create anonymous pipe that is close-on-exec and blocking. #[unstable(feature = "anonymous_pipe", issue = "127154")] diff --git a/library/std/src/process.rs b/library/std/src/process.rs index 60d452465dad1..c84a5c652639f 100644 --- a/library/std/src/process.rs +++ b/library/std/src/process.rs @@ -157,7 +157,7 @@ use crate::io::prelude::*; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::num::NonZero; use crate::path::Path; -use crate::sys::pipe::{read2, AnonPipe}; +use crate::sys::pipe::{AnonPipe, read2}; use crate::sys::process as imp; #[stable(feature = "command_access", since = "1.57.0")] pub use crate::sys_common::process::CommandEnvs; diff --git a/library/std/src/process/tests.rs b/library/std/src/process/tests.rs index f8e8e0dea553b..88cc95caf4073 100644 --- a/library/std/src/process/tests.rs +++ b/library/std/src/process/tests.rs @@ -437,7 +437,7 @@ fn test_proc_thread_attributes() { use crate::mem; use crate::os::windows::io::AsRawHandle; use crate::os::windows::process::CommandExt; - use crate::sys::c::{CloseHandle, BOOL, HANDLE}; + use crate::sys::c::{BOOL, CloseHandle, HANDLE}; use crate::sys::cvt; #[repr(C)] diff --git a/library/std/src/random.rs b/library/std/src/random.rs new file mode 100644 index 0000000000000..ecbf02eee8430 --- /dev/null +++ b/library/std/src/random.rs @@ -0,0 +1,104 @@ +//! Random value generation. +//! +//! The [`Random`] trait allows generating a random value for a type using a +//! given [`RandomSource`]. + +#[unstable(feature = "random", issue = "130703")] +pub use core::random::*; + +use crate::sys::random as sys; + +/// The default random source. +/// +/// This asks the system for random data suitable for cryptographic purposes +/// such as key generation. If security is a concern, consult the platform +/// documentation below for the specific guarantees your target provides. +/// +/// The high quality of randomness provided by this source means it can be quite +/// slow on some targets. If you need a large quantity of random numbers and +/// security is not a concern, consider using an alternative random number +/// generator (potentially seeded from this one). +/// +/// # Underlying sources +/// +/// Platform | Source +/// -----------------------|--------------------------------------------------------------- +/// Linux | [`getrandom`] or [`/dev/urandom`] after polling `/dev/random` +/// Windows | [`ProcessPrng`](https://learn.microsoft.com/en-us/windows/win32/seccng/processprng) +/// Apple | `CCRandomGenerateBytes` +/// DragonFly | [`arc4random_buf`](https://man.dragonflybsd.org/?command=arc4random) +/// ESP-IDF | [`esp_fill_random`](https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html#_CPPv415esp_fill_randomPv6size_t) +/// FreeBSD | [`arc4random_buf`](https://man.freebsd.org/cgi/man.cgi?query=arc4random) +/// Fuchsia | [`cprng_draw`](https://fuchsia.dev/reference/syscalls/cprng_draw) +/// Haiku | `arc4random_buf` +/// Illumos | [`arc4random_buf`](https://www.illumos.org/man/3C/arc4random) +/// NetBSD | [`arc4random_buf`](https://man.netbsd.org/arc4random.3) +/// OpenBSD | [`arc4random_buf`](https://man.openbsd.org/arc4random.3) +/// Solaris | [`arc4random_buf`](https://docs.oracle.com/cd/E88353_01/html/E37843/arc4random-3c.html) +/// Vita | `arc4random_buf` +/// Hermit | `read_entropy` +/// Horizon | `getrandom` shim +/// Hurd, L4Re, QNX | `/dev/urandom` +/// Redox | `/scheme/rand` +/// SGX | [`rdrand`](https://en.wikipedia.org/wiki/RDRAND) +/// SOLID | `SOLID_RNG_SampleRandomBytes` +/// TEEOS | `TEE_GenerateRandom` +/// UEFI | [`EFI_RNG_PROTOCOL`](https://uefi.org/specs/UEFI/2.10/37_Secure_Technologies.html#random-number-generator-protocol) +/// VxWorks | `randABytes` after waiting for `randSecure` to become ready +/// WASI | [`random_get`](https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#-random_getbuf-pointeru8-buf_len-size---result-errno) +/// ZKVM | `sys_rand` +/// +/// Note that the sources used might change over time. +/// +/// Consult the documentation for the underlying operations on your supported +/// targets to determine whether they provide any particular desired properties, +/// such as support for reseeding on VM fork operations. +/// +/// [`getrandom`]: https://www.man7.org/linux/man-pages/man2/getrandom.2.html +/// [`/dev/urandom`]: https://www.man7.org/linux/man-pages/man4/random.4.html +#[derive(Default, Debug, Clone, Copy)] +#[unstable(feature = "random", issue = "130703")] +pub struct DefaultRandomSource; + +#[unstable(feature = "random", issue = "130703")] +impl RandomSource for DefaultRandomSource { + fn fill_bytes(&mut self, bytes: &mut [u8]) { + sys::fill_bytes(bytes) + } +} + +/// Generates a random value with the default random source. +/// +/// This is a convenience function for `T::random(&mut DefaultRandomSource)` and +/// will sample according to the same distribution as the underlying [`Random`] +/// trait implementation. +/// +/// **Warning:** Be careful when manipulating random values! The +/// [`random`](Random::random) method on integers samples them with a uniform +/// distribution, so a value of 1 is just as likely as [`i32::MAX`]. By using +/// modulo operations, some of the resulting values can become more likely than +/// others. Use audited crates when in doubt. +/// +/// # Examples +/// +/// Generating a [version 4/variant 1 UUID] represented as text: +/// ``` +/// #![feature(random)] +/// +/// use std::random::random; +/// +/// let bits: u128 = random(); +/// let g1 = (bits >> 96) as u32; +/// let g2 = (bits >> 80) as u16; +/// let g3 = (0x4000 | (bits >> 64) & 0x0fff) as u16; +/// let g4 = (0x8000 | (bits >> 48) & 0x3fff) as u16; +/// let g5 = (bits & 0xffffffffffff) as u64; +/// let uuid = format!("{g1:08x}-{g2:04x}-{g3:04x}-{g4:04x}-{g5:012x}"); +/// println!("{uuid}"); +/// ``` +/// +/// [version 4/variant 1 UUID]: https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random) +#[unstable(feature = "random", issue = "130703")] +pub fn random() -> T { + T::random(&mut DefaultRandomSource) +} diff --git a/library/std/src/sync/barrier/tests.rs b/library/std/src/sync/barrier/tests.rs index 834a3e75158a7..c5620cd91d851 100644 --- a/library/std/src/sync/barrier/tests.rs +++ b/library/std/src/sync/barrier/tests.rs @@ -1,4 +1,4 @@ -use crate::sync::mpsc::{channel, TryRecvError}; +use crate::sync::mpsc::{TryRecvError, channel}; use crate::sync::{Arc, Barrier}; use crate::thread; diff --git a/library/std/src/sync/condvar.rs b/library/std/src/sync/condvar.rs index e41cbc1a65c0f..44ffcb528d937 100644 --- a/library/std/src/sync/condvar.rs +++ b/library/std/src/sync/condvar.rs @@ -2,7 +2,7 @@ mod tests; use crate::fmt; -use crate::sync::{mutex, poison, LockResult, MutexGuard, PoisonError}; +use crate::sync::{LockResult, MutexGuard, PoisonError, mutex, poison}; use crate::sys::sync as sys; use crate::time::{Duration, Instant}; diff --git a/library/std/src/sync/mod.rs b/library/std/src/sync/mod.rs index 70b419a1e33d1..0fb8e669bf86e 100644 --- a/library/std/src/sync/mod.rs +++ b/library/std/src/sync/mod.rs @@ -161,10 +161,10 @@ #![stable(feature = "rust1", since = "1.0.0")] -#[stable(feature = "rust1", since = "1.0.0")] -pub use core::sync::atomic; #[unstable(feature = "exclusive_wrapper", issue = "98407")] pub use core::sync::Exclusive; +#[stable(feature = "rust1", since = "1.0.0")] +pub use core::sync::atomic; #[stable(feature = "rust1", since = "1.0.0")] pub use alloc_crate::sync::{Arc, Weak}; @@ -181,7 +181,7 @@ pub use self::mutex::MappedMutexGuard; pub use self::mutex::{Mutex, MutexGuard}; #[stable(feature = "rust1", since = "1.0.0")] #[allow(deprecated)] -pub use self::once::{Once, OnceState, ONCE_INIT}; +pub use self::once::{ONCE_INIT, Once, OnceState}; #[stable(feature = "once_cell", since = "1.70.0")] pub use self::once_lock::OnceLock; #[stable(feature = "rust1", since = "1.0.0")] diff --git a/library/std/src/sync/mpmc/context.rs b/library/std/src/sync/mpmc/context.rs index 8db3c9896eb77..2371d32d4ea0d 100644 --- a/library/std/src/sync/mpmc/context.rs +++ b/library/std/src/sync/mpmc/context.rs @@ -4,8 +4,8 @@ use super::select::Selected; use super::waker::current_thread_id; use crate::cell::Cell; use crate::ptr; -use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use crate::sync::Arc; +use crate::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; use crate::thread::{self, Thread}; use crate::time::Instant; diff --git a/library/std/src/sync/mpmc/waker.rs b/library/std/src/sync/mpmc/waker.rs index fb877887f9c9d..1895466f95d45 100644 --- a/library/std/src/sync/mpmc/waker.rs +++ b/library/std/src/sync/mpmc/waker.rs @@ -3,8 +3,8 @@ use super::context::Context; use super::select::{Operation, Selected}; use crate::ptr; -use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sync::Mutex; +use crate::sync::atomic::{AtomicBool, Ordering}; /// Represents a thread blocked on a specific channel operation. pub(crate) struct Entry { diff --git a/library/std/src/sync/mpmc/zero.rs b/library/std/src/sync/mpmc/zero.rs index 2b82eeda3d5fb..2451d7b79d198 100644 --- a/library/std/src/sync/mpmc/zero.rs +++ b/library/std/src/sync/mpmc/zero.rs @@ -9,8 +9,8 @@ use super::utils::Backoff; use super::waker::Waker; use crate::cell::UnsafeCell; use crate::marker::PhantomData; -use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sync::Mutex; +use crate::sync::atomic::{AtomicBool, Ordering}; use crate::time::Instant; use crate::{fmt, ptr}; diff --git a/library/std/src/sync/mutex.rs b/library/std/src/sync/mutex.rs index d417034f5af85..f3de1f7bf495e 100644 --- a/library/std/src/sync/mutex.rs +++ b/library/std/src/sync/mutex.rs @@ -7,7 +7,7 @@ use crate::marker::PhantomData; use crate::mem::ManuallyDrop; use crate::ops::{Deref, DerefMut}; use crate::ptr::NonNull; -use crate::sync::{poison, LockResult, TryLockError, TryLockResult}; +use crate::sync::{LockResult, TryLockError, TryLockResult, poison}; use crate::sys::sync as sys; /// A mutual exclusion primitive useful for protecting shared data diff --git a/library/std/src/sync/once_lock/tests.rs b/library/std/src/sync/once_lock/tests.rs index 176830c6748b2..1fff3273d2021 100644 --- a/library/std/src/sync/once_lock/tests.rs +++ b/library/std/src/sync/once_lock/tests.rs @@ -1,7 +1,7 @@ +use crate::sync::OnceLock; use crate::sync::atomic::AtomicUsize; use crate::sync::atomic::Ordering::SeqCst; use crate::sync::mpsc::channel; -use crate::sync::OnceLock; use crate::{panic, thread}; fn spawn_and_wait(f: impl FnOnce() -> R + Send + 'static) -> R { diff --git a/library/std/src/sync/reentrant_lock.rs b/library/std/src/sync/reentrant_lock.rs index 0b23681e90726..39f23a14441c2 100644 --- a/library/std/src/sync/reentrant_lock.rs +++ b/library/std/src/sync/reentrant_lock.rs @@ -8,7 +8,7 @@ use crate::fmt; use crate::ops::Deref; use crate::panic::{RefUnwindSafe, UnwindSafe}; use crate::sys::sync as sys; -use crate::thread::{current_id, ThreadId}; +use crate::thread::{ThreadId, current_id}; /// A re-entrant mutual exclusion lock /// diff --git a/library/std/src/sync/rwlock.rs b/library/std/src/sync/rwlock.rs index d995a16e056d6..143bdef736d25 100644 --- a/library/std/src/sync/rwlock.rs +++ b/library/std/src/sync/rwlock.rs @@ -7,7 +7,7 @@ use crate::marker::PhantomData; use crate::mem::ManuallyDrop; use crate::ops::{Deref, DerefMut}; use crate::ptr::NonNull; -use crate::sync::{poison, LockResult, TryLockError, TryLockResult}; +use crate::sync::{LockResult, TryLockError, TryLockResult, poison}; use crate::sys::sync as sys; /// A reader-writer lock diff --git a/library/std/src/sys/alloc/solid.rs b/library/std/src/sys/alloc/solid.rs index abb534a1c5cf4..47cfa2eb1162b 100644 --- a/library/std/src/sys/alloc/solid.rs +++ b/library/std/src/sys/alloc/solid.rs @@ -1,4 +1,4 @@ -use super::{realloc_fallback, MIN_ALIGN}; +use super::{MIN_ALIGN, realloc_fallback}; use crate::alloc::{GlobalAlloc, Layout, System}; #[stable(feature = "alloc_system_type", since = "1.28.0")] diff --git a/library/std/src/sys/alloc/unix.rs b/library/std/src/sys/alloc/unix.rs index 46ed7de7162f8..266b69cdc1e3e 100644 --- a/library/std/src/sys/alloc/unix.rs +++ b/library/std/src/sys/alloc/unix.rs @@ -1,4 +1,4 @@ -use super::{realloc_fallback, MIN_ALIGN}; +use super::{MIN_ALIGN, realloc_fallback}; use crate::alloc::{GlobalAlloc, Layout, System}; use crate::ptr; diff --git a/library/std/src/sys/alloc/windows.rs b/library/std/src/sys/alloc/windows.rs index e91956966aa73..a77dda6e817ba 100644 --- a/library/std/src/sys/alloc/windows.rs +++ b/library/std/src/sys/alloc/windows.rs @@ -1,4 +1,4 @@ -use super::{realloc_fallback, MIN_ALIGN}; +use super::{MIN_ALIGN, realloc_fallback}; use crate::alloc::{GlobalAlloc, Layout, System}; use crate::ffi::c_void; use crate::mem::MaybeUninit; diff --git a/library/std/src/sys/dbg.rs b/library/std/src/sys/dbg.rs index a6e78db3c86f0..383ed84cfa251 100644 --- a/library/std/src/sys/dbg.rs +++ b/library/std/src/sys/dbg.rs @@ -34,7 +34,7 @@ mod os { #[cfg(any(target_vendor = "apple", target_os = "freebsd"))] mod os { - use libc::{c_int, sysctl, CTL_KERN, KERN_PROC, KERN_PROC_PID}; + use libc::{CTL_KERN, KERN_PROC, KERN_PROC_PID, c_int, sysctl}; use super::DebuggerPresence; use crate::io::{Cursor, Read, Seek, SeekFrom}; diff --git a/library/std/src/sys/mod.rs b/library/std/src/sys/mod.rs index 96d6f2c87c4c1..df25b84fbbe5a 100644 --- a/library/std/src/sys/mod.rs +++ b/library/std/src/sys/mod.rs @@ -15,6 +15,7 @@ pub mod dbg; pub mod exit_guard; pub mod os_str; pub mod path; +pub mod random; pub mod sync; pub mod thread_local; diff --git a/library/std/src/sys/os_str/wtf8.rs b/library/std/src/sys/os_str/wtf8.rs index 433237aa6e7bf..6fbbec7a9458f 100644 --- a/library/std/src/sys/os_str/wtf8.rs +++ b/library/std/src/sys/os_str/wtf8.rs @@ -7,7 +7,7 @@ use crate::borrow::Cow; use crate::collections::TryReserveError; use crate::rc::Rc; use crate::sync::Arc; -use crate::sys_common::wtf8::{check_utf8_boundary, Wtf8, Wtf8Buf}; +use crate::sys_common::wtf8::{Wtf8, Wtf8Buf, check_utf8_boundary}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::{fmt, mem}; diff --git a/library/std/src/sys/pal/hermit/args.rs b/library/std/src/sys/pal/hermit/args.rs index 51afe3434aedc..4402426027730 100644 --- a/library/std/src/sys/pal/hermit/args.rs +++ b/library/std/src/sys/pal/hermit/args.rs @@ -1,4 +1,4 @@ -use crate::ffi::{c_char, CStr, OsString}; +use crate::ffi::{CStr, OsString, c_char}; use crate::os::hermit::ffi::OsStringExt; use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sync::atomic::{AtomicIsize, AtomicPtr}; diff --git a/library/std/src/sys/pal/hermit/fs.rs b/library/std/src/sys/pal/hermit/fs.rs index aaf1a044d0613..70f6981f7175b 100644 --- a/library/std/src/sys/pal/hermit/fs.rs +++ b/library/std/src/sys/pal/hermit/fs.rs @@ -1,7 +1,7 @@ use super::fd::FileDesc; use super::hermit_abi::{ - self, dirent64, stat as stat_struct, DT_DIR, DT_LNK, DT_REG, DT_UNKNOWN, O_APPEND, O_CREAT, - O_DIRECTORY, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, S_IFDIR, S_IFLNK, S_IFMT, S_IFREG, + self, DT_DIR, DT_LNK, DT_REG, DT_UNKNOWN, O_APPEND, O_CREAT, O_DIRECTORY, O_EXCL, O_RDONLY, + O_RDWR, O_TRUNC, O_WRONLY, S_IFDIR, S_IFLNK, S_IFMT, S_IFREG, dirent64, stat as stat_struct, }; use crate::ffi::{CStr, OsStr, OsString}; use crate::io::{self, BorrowedCursor, Error, ErrorKind, IoSlice, IoSliceMut, SeekFrom}; diff --git a/library/std/src/sys/pal/hermit/mod.rs b/library/std/src/sys/pal/hermit/mod.rs index 1f2e5d9469f5c..f49ef94717499 100644 --- a/library/std/src/sys/pal/hermit/mod.rs +++ b/library/std/src/sys/pal/hermit/mod.rs @@ -52,20 +52,6 @@ pub fn abort_internal() -> ! { unsafe { hermit_abi::abort() } } -pub fn hashmap_random_keys() -> (u64, u64) { - let mut buf = [0; 16]; - let mut slice = &mut buf[..]; - while !slice.is_empty() { - let res = cvt(unsafe { hermit_abi::read_entropy(slice.as_mut_ptr(), slice.len(), 0) }) - .expect("failed to generate random hashmap keys"); - slice = &mut slice[res as usize..]; - } - - let key1 = buf[..8].try_into().unwrap(); - let key2 = buf[8..].try_into().unwrap(); - (u64::from_ne_bytes(key1), u64::from_ne_bytes(key2)) -} - // This function is needed by the panic runtime. The symbol is named in // pre-link args for the target specification, so keep that in sync. #[cfg(not(test))] diff --git a/library/std/src/sys/pal/hermit/time.rs b/library/std/src/sys/pal/hermit/time.rs index 2c87c4860a27a..99166b15602a9 100644 --- a/library/std/src/sys/pal/hermit/time.rs +++ b/library/std/src/sys/pal/hermit/time.rs @@ -2,7 +2,7 @@ use core::hash::{Hash, Hasher}; -use super::hermit_abi::{self, timespec, CLOCK_MONOTONIC, CLOCK_REALTIME}; +use super::hermit_abi::{self, CLOCK_MONOTONIC, CLOCK_REALTIME, timespec}; use crate::cmp::Ordering; use crate::ops::{Add, AddAssign, Sub, SubAssign}; use crate::time::Duration; diff --git a/library/std/src/sys/pal/itron/task.rs b/library/std/src/sys/pal/itron/task.rs index 5da0c5917885f..49c420baca2f3 100644 --- a/library/std/src/sys/pal/itron/task.rs +++ b/library/std/src/sys/pal/itron/task.rs @@ -1,5 +1,5 @@ use super::abi; -use super::error::{fail, fail_aborting, ItronError}; +use super::error::{ItronError, fail, fail_aborting}; use crate::mem::MaybeUninit; /// Gets the ID of the task in Running state. Panics on failure. diff --git a/library/std/src/sys/pal/itron/thread.rs b/library/std/src/sys/pal/itron/thread.rs index 01e69afa99e13..04095e1a7cf99 100644 --- a/library/std/src/sys/pal/itron/thread.rs +++ b/library/std/src/sys/pal/itron/thread.rs @@ -1,7 +1,7 @@ //! Thread implementation backed by μITRON tasks. Assumes `acre_tsk` and //! `exd_tsk` are available. -use super::error::{expect_success, expect_success_aborting, ItronError}; +use super::error::{ItronError, expect_success, expect_success_aborting}; use super::time::dur2reltims; use super::{abi, task}; use crate::cell::UnsafeCell; diff --git a/library/std/src/sys/pal/itron/time/tests.rs b/library/std/src/sys/pal/itron/time/tests.rs index d14035d9da49f..28db4f8b6799f 100644 --- a/library/std/src/sys/pal/itron/time/tests.rs +++ b/library/std/src/sys/pal/itron/time/tests.rs @@ -8,26 +8,24 @@ fn reltim2dur(t: u64) -> Duration { fn test_dur2reltims() { assert_eq!(dur2reltims(reltim2dur(0)).collect::>(), vec![]); assert_eq!(dur2reltims(reltim2dur(42)).collect::>(), vec![42]); - assert_eq!( - dur2reltims(reltim2dur(abi::TMAX_RELTIM as u64)).collect::>(), - vec![abi::TMAX_RELTIM] - ); - assert_eq!( - dur2reltims(reltim2dur(abi::TMAX_RELTIM as u64 + 10000)).collect::>(), - vec![abi::TMAX_RELTIM, 10000] - ); + assert_eq!(dur2reltims(reltim2dur(abi::TMAX_RELTIM as u64)).collect::>(), vec![ + abi::TMAX_RELTIM + ]); + assert_eq!(dur2reltims(reltim2dur(abi::TMAX_RELTIM as u64 + 10000)).collect::>(), vec![ + abi::TMAX_RELTIM, + 10000 + ]); } #[test] fn test_dur2tmos() { assert_eq!(dur2tmos(reltim2dur(0)).collect::>(), vec![0]); assert_eq!(dur2tmos(reltim2dur(42)).collect::>(), vec![42]); - assert_eq!( - dur2tmos(reltim2dur(abi::TMAX_RELTIM as u64)).collect::>(), - vec![abi::TMAX_RELTIM] - ); - assert_eq!( - dur2tmos(reltim2dur(abi::TMAX_RELTIM as u64 + 10000)).collect::>(), - vec![abi::TMAX_RELTIM, 10000] - ); + assert_eq!(dur2tmos(reltim2dur(abi::TMAX_RELTIM as u64)).collect::>(), vec![ + abi::TMAX_RELTIM + ]); + assert_eq!(dur2tmos(reltim2dur(abi::TMAX_RELTIM as u64 + 10000)).collect::>(), vec![ + abi::TMAX_RELTIM, + 10000 + ]); } diff --git a/library/std/src/sys/pal/sgx/abi/usercalls/mod.rs b/library/std/src/sys/pal/sgx/abi/usercalls/mod.rs index def1ccdf81ac0..90b9b59471a52 100644 --- a/library/std/src/sys/pal/sgx/abi/usercalls/mod.rs +++ b/library/std/src/sys/pal/sgx/abi/usercalls/mod.rs @@ -1,6 +1,6 @@ use crate::cmp; use crate::io::{Error as IoError, ErrorKind, IoSlice, IoSliceMut, Result as IoResult}; -use crate::sys::rand::rdrand64; +use crate::random::{DefaultRandomSource, Random}; use crate::time::{Duration, Instant}; pub(crate) mod alloc; @@ -164,7 +164,7 @@ pub fn wait(event_mask: u64, mut timeout: u64) -> IoResult { // trusted to ensure accurate timeouts. if let Ok(timeout_signed) = i64::try_from(timeout) { let tenth = timeout_signed / 10; - let deviation = (rdrand64() as i64).checked_rem(tenth).unwrap_or(0); + let deviation = i64::random(&mut DefaultRandomSource).checked_rem(tenth).unwrap_or(0); timeout = timeout_signed.saturating_add(deviation) as _; } } diff --git a/library/std/src/sys/pal/sgx/abi/usercalls/tests.rs b/library/std/src/sys/pal/sgx/abi/usercalls/tests.rs index ef824d35f4a16..5978ae5a0fac9 100644 --- a/library/std/src/sys/pal/sgx/abi/usercalls/tests.rs +++ b/library/std/src/sys/pal/sgx/abi/usercalls/tests.rs @@ -1,4 +1,4 @@ -use super::alloc::{copy_from_userspace, copy_to_userspace, User}; +use super::alloc::{User, copy_from_userspace, copy_to_userspace}; #[test] fn test_copy_to_userspace_function() { diff --git a/library/std/src/sys/pal/sgx/mod.rs b/library/std/src/sys/pal/sgx/mod.rs index 8d29b2ec6193e..586ccd18c2f57 100644 --- a/library/std/src/sys/pal/sgx/mod.rs +++ b/library/std/src/sys/pal/sgx/mod.rs @@ -132,24 +132,6 @@ pub extern "C" fn __rust_abort() { abort_internal(); } -pub mod rand { - pub fn rdrand64() -> u64 { - unsafe { - let mut ret: u64 = 0; - for _ in 0..10 { - if crate::arch::x86_64::_rdrand64_step(&mut ret) == 1 { - return ret; - } - } - rtabort!("Failed to obtain random data"); - } - } -} - -pub fn hashmap_random_keys() -> (u64, u64) { - (self::rand::rdrand64(), self::rand::rdrand64()) -} - pub use crate::sys_common::{AsInner, FromInner, IntoInner}; pub trait TryIntoInner: Sized { diff --git a/library/std/src/sys/pal/sgx/net.rs b/library/std/src/sys/pal/sgx/net.rs index f2e751c51194d..44913ffe3a9ff 100644 --- a/library/std/src/sys/pal/sgx/net.rs +++ b/library/std/src/sys/pal/sgx/net.rs @@ -3,7 +3,7 @@ use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr, ToSocketAddrs}; use crate::sync::Arc; use crate::sys::fd::FileDesc; -use crate::sys::{sgx_ineffective, unsupported, AsInner, FromInner, IntoInner, TryIntoInner}; +use crate::sys::{AsInner, FromInner, IntoInner, TryIntoInner, sgx_ineffective, unsupported}; use crate::time::Duration; use crate::{error, fmt}; diff --git a/library/std/src/sys/pal/sgx/waitqueue/mod.rs b/library/std/src/sys/pal/sgx/waitqueue/mod.rs index bd114523fe80b..41d1413fcdee9 100644 --- a/library/std/src/sys/pal/sgx/waitqueue/mod.rs +++ b/library/std/src/sys/pal/sgx/waitqueue/mod.rs @@ -16,9 +16,9 @@ mod tests; mod spin_mutex; mod unsafe_list; -use fortanix_sgx_abi::{Tcs, EV_UNPARK, WAIT_INDEFINITE}; +use fortanix_sgx_abi::{EV_UNPARK, Tcs, WAIT_INDEFINITE}; -pub use self::spin_mutex::{try_lock_or_false, SpinMutex, SpinMutexGuard}; +pub use self::spin_mutex::{SpinMutex, SpinMutexGuard, try_lock_or_false}; use self::unsafe_list::{UnsafeList, UnsafeListEntry}; use super::abi::{thread, usercalls}; use crate::num::NonZero; diff --git a/library/std/src/sys/pal/solid/abi/fs.rs b/library/std/src/sys/pal/solid/abi/fs.rs index 394be15b0064b..6864a3e7745b9 100644 --- a/library/std/src/sys/pal/solid/abi/fs.rs +++ b/library/std/src/sys/pal/solid/abi/fs.rs @@ -1,8 +1,8 @@ //! `solid_fs.h` pub use libc::{ - ino_t, off_t, stat, time_t, O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, - SEEK_CUR, SEEK_END, SEEK_SET, S_IFBLK, S_IFCHR, S_IFDIR, S_IFIFO, S_IFMT, S_IFREG, S_IWRITE, + O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY, S_IFBLK, S_IFCHR, S_IFDIR, + S_IFIFO, S_IFMT, S_IFREG, S_IWRITE, SEEK_CUR, SEEK_END, SEEK_SET, ino_t, off_t, stat, time_t, }; use crate::os::raw::{c_char, c_int, c_uchar}; diff --git a/library/std/src/sys/pal/solid/abi/mod.rs b/library/std/src/sys/pal/solid/abi/mod.rs index 62cd86236bbd3..4d09705721748 100644 --- a/library/std/src/sys/pal/solid/abi/mod.rs +++ b/library/std/src/sys/pal/solid/abi/mod.rs @@ -4,7 +4,7 @@ mod fs; pub mod sockets; pub use self::fs::*; // `solid_types.h` -pub use super::itron::abi::{ER, ER_ID, E_TMOUT, ID}; +pub use super::itron::abi::{E_TMOUT, ER, ER_ID, ID}; pub const SOLID_ERR_NOTFOUND: ER = -1000; pub const SOLID_ERR_NOTSUPPORTED: ER = -1001; diff --git a/library/std/src/sys/pal/solid/error.rs b/library/std/src/sys/pal/solid/error.rs index 66c4d8a0ea27a..e092497856d43 100644 --- a/library/std/src/sys/pal/solid/error.rs +++ b/library/std/src/sys/pal/solid/error.rs @@ -1,4 +1,4 @@ -pub use self::itron::error::{expect_success, ItronError as SolidError}; +pub use self::itron::error::{ItronError as SolidError, expect_success}; use super::{abi, itron, net}; use crate::io::ErrorKind; diff --git a/library/std/src/sys/pal/solid/mod.rs b/library/std/src/sys/pal/solid/mod.rs index 6ebcf5b7c48c8..d41042be51844 100644 --- a/library/std/src/sys/pal/solid/mod.rs +++ b/library/std/src/sys/pal/solid/mod.rs @@ -62,13 +62,3 @@ pub fn decode_error_kind(code: i32) -> crate::io::ErrorKind { pub fn abort_internal() -> ! { unsafe { libc::abort() } } - -pub fn hashmap_random_keys() -> (u64, u64) { - unsafe { - let mut out = crate::mem::MaybeUninit::<[u64; 2]>::uninit(); - let result = abi::SOLID_RNG_SampleRandomBytes(out.as_mut_ptr() as *mut u8, 16); - assert_eq!(result, 0, "SOLID_RNG_SampleRandomBytes failed: {result}"); - let [x1, x2] = out.assume_init(); - (x1, x2) - } -} diff --git a/library/std/src/sys/pal/solid/net.rs b/library/std/src/sys/pal/solid/net.rs index b6a31395095d9..c0818ecd856d2 100644 --- a/library/std/src/sys/pal/solid/net.rs +++ b/library/std/src/sys/pal/solid/net.rs @@ -1,6 +1,6 @@ use libc::{c_int, c_void, size_t}; -use self::netc::{sockaddr, socklen_t, MSG_PEEK}; +use self::netc::{MSG_PEEK, sockaddr, socklen_t}; use super::abi; use crate::ffi::CStr; use crate::io::{self, BorrowedBuf, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; diff --git a/library/std/src/sys/pal/teeos/mod.rs b/library/std/src/sys/pal/teeos/mod.rs index 00e3860424006..60a227afb84e3 100644 --- a/library/std/src/sys/pal/teeos/mod.rs +++ b/library/std/src/sys/pal/teeos/mod.rs @@ -6,8 +6,6 @@ #![allow(unused_variables)] #![allow(dead_code)] -pub use self::rand::hashmap_random_keys; - #[path = "../unsupported/args.rs"] pub mod args; #[path = "../unsupported/env.rs"] @@ -23,7 +21,6 @@ pub mod os; pub mod pipe; #[path = "../unsupported/process.rs"] pub mod process; -mod rand; pub mod stdio; pub mod thread; #[allow(non_upper_case_globals)] diff --git a/library/std/src/sys/pal/teeos/rand.rs b/library/std/src/sys/pal/teeos/rand.rs deleted file mode 100644 index b45c3bb40e782..0000000000000 --- a/library/std/src/sys/pal/teeos/rand.rs +++ /dev/null @@ -1,21 +0,0 @@ -pub fn hashmap_random_keys() -> (u64, u64) { - const KEY_LEN: usize = core::mem::size_of::(); - - let mut v = [0u8; KEY_LEN * 2]; - imp::fill_bytes(&mut v); - - let key1 = v[0..KEY_LEN].try_into().unwrap(); - let key2 = v[KEY_LEN..].try_into().unwrap(); - - (u64::from_ne_bytes(key1), u64::from_ne_bytes(key2)) -} - -mod imp { - extern "C" { - fn TEE_GenerateRandom(randomBuffer: *mut core::ffi::c_void, randomBufferLen: libc::size_t); - } - - pub fn fill_bytes(v: &mut [u8]) { - unsafe { TEE_GenerateRandom(v.as_mut_ptr() as _, v.len() * crate::mem::size_of::()) } - } -} diff --git a/library/std/src/sys/pal/uefi/helpers.rs b/library/std/src/sys/pal/uefi/helpers.rs index 4031d33ba8066..bd8a6684b64f9 100644 --- a/library/std/src/sys/pal/uefi/helpers.rs +++ b/library/std/src/sys/pal/uefi/helpers.rs @@ -14,7 +14,7 @@ use r_efi::protocols::{device_path, device_path_to_text}; use crate::ffi::{OsStr, OsString}; use crate::io::{self, const_io_error}; -use crate::mem::{size_of, MaybeUninit}; +use crate::mem::{MaybeUninit, size_of}; use crate::os::uefi::env::boot_services; use crate::os::uefi::ffi::{OsStrExt, OsStringExt}; use crate::os::uefi::{self}; diff --git a/library/std/src/sys/pal/uefi/mod.rs b/library/std/src/sys/pal/uefi/mod.rs index ac22f4ded8855..c0ab52f650aa5 100644 --- a/library/std/src/sys/pal/uefi/mod.rs +++ b/library/std/src/sys/pal/uefi/mod.rs @@ -179,39 +179,6 @@ pub extern "C" fn __rust_abort() { abort_internal(); } -#[inline] -pub fn hashmap_random_keys() -> (u64, u64) { - get_random().unwrap() -} - -fn get_random() -> Option<(u64, u64)> { - use r_efi::protocols::rng; - - let mut buf = [0u8; 16]; - let handles = helpers::locate_handles(rng::PROTOCOL_GUID).ok()?; - for handle in handles { - if let Ok(protocol) = helpers::open_protocol::(handle, rng::PROTOCOL_GUID) { - let r = unsafe { - ((*protocol.as_ptr()).get_rng)( - protocol.as_ptr(), - crate::ptr::null_mut(), - buf.len(), - buf.as_mut_ptr(), - ) - }; - if r.is_error() { - continue; - } else { - return Some(( - u64::from_le_bytes(buf[..8].try_into().ok()?), - u64::from_le_bytes(buf[8..].try_into().ok()?), - )); - } - } - } - None -} - /// Disable access to BootServices if `EVT_SIGNAL_EXIT_BOOT_SERVICES` is signaled extern "efiapi" fn exit_boot_service_handler(_e: r_efi::efi::Event, _ctx: *mut crate::ffi::c_void) { uefi::env::disable_boot_services(); diff --git a/library/std/src/sys/pal/uefi/os.rs b/library/std/src/sys/pal/uefi/os.rs index 4d2d7264704b2..9aee67d622fad 100644 --- a/library/std/src/sys/pal/uefi/os.rs +++ b/library/std/src/sys/pal/uefi/os.rs @@ -1,7 +1,7 @@ -use r_efi::efi::protocols::{device_path, loaded_image_device_path}; use r_efi::efi::Status; +use r_efi::efi::protocols::{device_path, loaded_image_device_path}; -use super::{helpers, unsupported, RawOsError}; +use super::{RawOsError, helpers, unsupported}; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; use crate::marker::PhantomData; diff --git a/library/std/src/sys/pal/unix/fd.rs b/library/std/src/sys/pal/unix/fd.rs index d8e239ee23ed5..135042779ad84 100644 --- a/library/std/src/sys/pal/unix/fd.rs +++ b/library/std/src/sys/pal/unix/fd.rs @@ -3,14 +3,6 @@ #[cfg(test)] mod tests; -#[cfg(any( - target_os = "android", - target_os = "linux", - target_os = "emscripten", - target_os = "l4re", - target_os = "hurd", -))] -use libc::off64_t; #[cfg(not(any( target_os = "linux", target_os = "emscripten", @@ -19,6 +11,14 @@ use libc::off64_t; target_os = "hurd", )))] use libc::off_t as off64_t; +#[cfg(any( + target_os = "android", + target_os = "linux", + target_os = "emscripten", + target_os = "l4re", + target_os = "hurd", +))] +use libc::off64_t; use crate::cmp; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut, Read}; diff --git a/library/std/src/sys/pal/unix/fs.rs b/library/std/src/sys/pal/unix/fs.rs index d09cee2e89c5b..dade6d6bbaeea 100644 --- a/library/std/src/sys/pal/unix/fs.rs +++ b/library/std/src/sys/pal/unix/fs.rs @@ -31,10 +31,6 @@ use libc::fstatat64; all(target_os = "linux", target_env = "musl"), ))] use libc::readdir as readdir64; -#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))] -use libc::readdir64; -#[cfg(any(target_os = "emscripten", target_os = "l4re"))] -use libc::readdir64_r; #[cfg(not(any( target_os = "android", target_os = "linux", @@ -50,6 +46,10 @@ use libc::readdir64_r; target_os = "hurd", )))] use libc::readdir_r as readdir64_r; +#[cfg(any(all(target_os = "linux", not(target_env = "musl")), target_os = "hurd"))] +use libc::readdir64; +#[cfg(any(target_os = "emscripten", target_os = "l4re"))] +use libc::readdir64_r; use libc::{c_int, mode_t}; #[cfg(target_os = "android")] use libc::{ @@ -1866,7 +1866,7 @@ pub fn copy(from: &Path, to: &Path) -> io::Result { let max_len = u64::MAX; let (mut writer, _) = open_to_and_set_permissions(to, reader_metadata)?; - use super::kernel_copy::{copy_regular_files, CopyResult}; + use super::kernel_copy::{CopyResult, copy_regular_files}; match copy_regular_files(reader.as_raw_fd(), writer.as_raw_fd(), max_len) { CopyResult::Ended(bytes) => Ok(bytes), @@ -2008,7 +2008,7 @@ mod remove_dir_impl { #[cfg(all(target_os = "linux", target_env = "gnu"))] use libc::{fdopendir, openat64 as openat, unlinkat}; - use super::{lstat, Dir, DirEntry, InnerReadDir, ReadDir}; + use super::{Dir, DirEntry, InnerReadDir, ReadDir, lstat}; use crate::ffi::CStr; use crate::io; use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd}; diff --git a/library/std/src/sys/pal/unix/mod.rs b/library/std/src/sys/pal/unix/mod.rs index e8428eccb1691..0d63b1119d59a 100644 --- a/library/std/src/sys/pal/unix/mod.rs +++ b/library/std/src/sys/pal/unix/mod.rs @@ -1,6 +1,5 @@ #![allow(missing_docs, nonstandard_style)] -pub use self::rand::hashmap_random_keys; use crate::io::ErrorKind; #[cfg(not(target_os = "espidf"))] @@ -26,7 +25,6 @@ pub use self::l4re::net; pub mod os; pub mod pipe; pub mod process; -pub mod rand; pub mod stack_overflow; pub mod stdio; pub mod thread; @@ -281,6 +279,7 @@ pub fn decode_error_kind(errno: i32) -> ErrorKind { libc::ETIMEDOUT => TimedOut, libc::ETXTBSY => ExecutableFileBusy, libc::EXDEV => CrossesDevices, + libc::EINPROGRESS => InProgress, libc::EACCES | libc::EPERM => PermissionDenied, diff --git a/library/std/src/sys/pal/unix/net.rs b/library/std/src/sys/pal/unix/net.rs index d75a666d350ff..e98232ba89ac4 100644 --- a/library/std/src/sys/pal/unix/net.rs +++ b/library/std/src/sys/pal/unix/net.rs @@ -1,4 +1,4 @@ -use libc::{c_int, c_void, size_t, sockaddr, socklen_t, MSG_PEEK}; +use libc::{MSG_PEEK, c_int, c_void, size_t, sockaddr, socklen_t}; use crate::ffi::CStr; use crate::io::{self, BorrowedBuf, BorrowedCursor, IoSlice, IoSliceMut}; diff --git a/library/std/src/sys/pal/unix/process/process_common.rs b/library/std/src/sys/pal/unix/process/process_common.rs index fec825054195a..d9c41d4348756 100644 --- a/library/std/src/sys/pal/unix/process/process_common.rs +++ b/library/std/src/sys/pal/unix/process/process_common.rs @@ -1,7 +1,7 @@ #[cfg(all(test, not(target_os = "emscripten")))] mod tests; -use libc::{c_char, c_int, gid_t, pid_t, uid_t, EXIT_FAILURE, EXIT_SUCCESS}; +use libc::{EXIT_FAILURE, EXIT_SUCCESS, c_char, c_int, gid_t, pid_t, uid_t}; use crate::collections::BTreeMap; use crate::ffi::{CStr, CString, OsStr, OsString}; diff --git a/library/std/src/sys/pal/unix/process/process_fuchsia.rs b/library/std/src/sys/pal/unix/process/process_fuchsia.rs index f3d5fdec4c291..34ff464aa37f8 100644 --- a/library/std/src/sys/pal/unix/process/process_fuchsia.rs +++ b/library/std/src/sys/pal/unix/process/process_fuchsia.rs @@ -2,7 +2,7 @@ use libc::{c_int, size_t}; use crate::num::NonZero; use crate::sys::process::process_common::*; -use crate::sys::process::zircon::{zx_handle_t, Handle}; +use crate::sys::process::zircon::{Handle, zx_handle_t}; use crate::{fmt, io, mem, ptr}; //////////////////////////////////////////////////////////////////////////////// diff --git a/library/std/src/sys/pal/unix/process/process_unix.rs b/library/std/src/sys/pal/unix/process/process_unix.rs index 4bb22f3670978..d812aa0e02cf1 100644 --- a/library/std/src/sys/pal/unix/process/process_unix.rs +++ b/library/std/src/sys/pal/unix/process/process_unix.rs @@ -1190,8 +1190,8 @@ impl ExitStatusError { mod linux_child_ext { use crate::os::linux::process as os; - use crate::sys::pal::unix::linux::pidfd as imp; use crate::sys::pal::unix::ErrorKind; + use crate::sys::pal::unix::linux::pidfd as imp; use crate::sys_common::FromInner; use crate::{io, mem}; diff --git a/library/std/src/sys/pal/unix/process/process_vxworks.rs b/library/std/src/sys/pal/unix/process/process_vxworks.rs index 0477b3d9a70da..2d9a304c49512 100644 --- a/library/std/src/sys/pal/unix/process/process_vxworks.rs +++ b/library/std/src/sys/pal/unix/process/process_vxworks.rs @@ -1,5 +1,5 @@ #![forbid(unsafe_op_in_unsafe_fn)] -use libc::{self, c_char, c_int, RTP_ID}; +use libc::{self, RTP_ID, c_char, c_int}; use crate::io::{self, ErrorKind}; use crate::num::NonZero; diff --git a/library/std/src/sys/pal/unix/rand.rs b/library/std/src/sys/pal/unix/rand.rs deleted file mode 100644 index cc0852aab4396..0000000000000 --- a/library/std/src/sys/pal/unix/rand.rs +++ /dev/null @@ -1,302 +0,0 @@ -pub fn hashmap_random_keys() -> (u64, u64) { - const KEY_LEN: usize = core::mem::size_of::(); - - let mut v = [0u8; KEY_LEN * 2]; - if let Err(err) = read(&mut v) { - panic!("failed to retrieve random hash map seed: {err}"); - } - - let key1 = v[0..KEY_LEN].try_into().unwrap(); - let key2 = v[KEY_LEN..].try_into().unwrap(); - - (u64::from_ne_bytes(key1), u64::from_ne_bytes(key2)) -} - -cfg_if::cfg_if! { - if #[cfg(any( - target_vendor = "apple", - target_os = "openbsd", - target_os = "emscripten", - target_os = "vita", - all(target_os = "netbsd", not(netbsd10)), - target_os = "fuchsia", - target_os = "vxworks", - ))] { - // Some systems have a syscall that directly retrieves random data. - // If that is guaranteed to be available, use it. - use imp::syscall as read; - } else { - // Otherwise, try the syscall to see if it exists only on some systems - // and fall back to reading from the random device otherwise. - fn read(bytes: &mut [u8]) -> crate::io::Result<()> { - use crate::fs::File; - use crate::io::Read; - use crate::sync::OnceLock; - - #[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "espidf", - target_os = "horizon", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "solaris", - target_os = "illumos", - netbsd10, - ))] - if let Some(res) = imp::syscall(bytes) { - return res; - } - - const PATH: &'static str = if cfg!(target_os = "redox") { - "/scheme/rand" - } else { - "/dev/urandom" - }; - - static FILE: OnceLock = OnceLock::new(); - - FILE.get_or_try_init(|| File::open(PATH))?.read_exact(bytes) - } - } -} - -// All these systems a `getrandom` syscall. -// -// It is not guaranteed to be available, so return None to fallback to the file -// implementation. -#[cfg(any( - target_os = "linux", - target_os = "android", - target_os = "espidf", - target_os = "horizon", - target_os = "freebsd", - target_os = "dragonfly", - target_os = "solaris", - target_os = "illumos", - netbsd10, -))] -mod imp { - use crate::io::{Error, Result}; - use crate::sync::atomic::{AtomicBool, Ordering}; - use crate::sys::os::errno; - - #[cfg(any(target_os = "linux", target_os = "android"))] - fn getrandom(buf: &mut [u8]) -> libc::ssize_t { - use crate::sys::weak::syscall; - - // A weak symbol allows interposition, e.g. for perf measurements that want to - // disable randomness for consistency. Otherwise, we'll try a raw syscall. - // (`getrandom` was added in glibc 2.25, musl 1.1.20, android API level 28) - syscall! { - fn getrandom( - buffer: *mut libc::c_void, - length: libc::size_t, - flags: libc::c_uint - ) -> libc::ssize_t - } - - // This provides the best quality random numbers available at the given moment - // without ever blocking, and is preferable to falling back to /dev/urandom. - static GRND_INSECURE_AVAILABLE: AtomicBool = AtomicBool::new(true); - if GRND_INSECURE_AVAILABLE.load(Ordering::Relaxed) { - let ret = unsafe { getrandom(buf.as_mut_ptr().cast(), buf.len(), libc::GRND_INSECURE) }; - if ret == -1 && errno() as libc::c_int == libc::EINVAL { - GRND_INSECURE_AVAILABLE.store(false, Ordering::Relaxed); - } else { - return ret; - } - } - - unsafe { getrandom(buf.as_mut_ptr().cast(), buf.len(), libc::GRND_NONBLOCK) } - } - - #[cfg(any( - target_os = "dragonfly", - target_os = "espidf", - target_os = "horizon", - target_os = "freebsd", - netbsd10, - target_os = "illumos", - target_os = "solaris" - ))] - fn getrandom(buf: &mut [u8]) -> libc::ssize_t { - unsafe { libc::getrandom(buf.as_mut_ptr().cast(), buf.len(), 0) } - } - - pub fn syscall(v: &mut [u8]) -> Option> { - static GETRANDOM_UNAVAILABLE: AtomicBool = AtomicBool::new(false); - - if GETRANDOM_UNAVAILABLE.load(Ordering::Relaxed) { - return None; - } - - let mut read = 0; - while read < v.len() { - let result = getrandom(&mut v[read..]); - if result == -1 { - let err = errno() as libc::c_int; - if err == libc::EINTR { - continue; - } else if err == libc::ENOSYS || err == libc::EPERM { - // `getrandom` is not supported on the current system. - // - // Also fall back in case it is disabled by something like - // seccomp or inside of docker. - // - // If the `getrandom` syscall is not implemented in the current kernel version it should return an - // `ENOSYS` error. Docker also blocks the whole syscall inside unprivileged containers, and - // returns `EPERM` (instead of `ENOSYS`) when a program tries to invoke the syscall. Because of - // that we need to check for *both* `ENOSYS` and `EPERM`. - // - // Note that Docker's behavior is breaking other projects (notably glibc), so they're planning - // to update their filtering to return `ENOSYS` in a future release: - // - // https://github.com/moby/moby/issues/42680 - // - GETRANDOM_UNAVAILABLE.store(true, Ordering::Relaxed); - return None; - } else if err == libc::EAGAIN { - // getrandom has failed because it would have blocked as the - // non-blocking pool (urandom) has not been initialized in - // the kernel yet due to a lack of entropy. Fallback to - // reading from `/dev/urandom` which will return potentially - // insecure random data to avoid blocking applications which - // could depend on this call without ever knowing they do and - // don't have a work around. - return None; - } else { - return Some(Err(Error::from_raw_os_error(err))); - } - } else { - read += result as usize; - } - } - - Some(Ok(())) - } -} - -#[cfg(any( - target_os = "macos", // Supported since macOS 10.12+. - target_os = "openbsd", - target_os = "emscripten", - target_os = "vita", -))] -mod imp { - use crate::io::{Error, Result}; - - pub fn syscall(v: &mut [u8]) -> Result<()> { - // getentropy(2) permits a maximum buffer size of 256 bytes - for s in v.chunks_mut(256) { - let ret = unsafe { libc::getentropy(s.as_mut_ptr().cast(), s.len()) }; - if ret == -1 { - return Err(Error::last_os_error()); - } - } - - Ok(()) - } -} - -// On Apple platforms, `CCRandomGenerateBytes` and `SecRandomCopyBytes` simply -// call into `CCRandomCopyBytes` with `kCCRandomDefault`. `CCRandomCopyBytes` -// manages a CSPRNG which is seeded from the kernel's CSPRNG and which runs on -// its own thread accessed via GCD. This seems needlessly heavyweight for our purposes -// so we only use it when `getentropy` is blocked, which appears to be the case -// on all platforms except macOS (see #102643). -// -// `CCRandomGenerateBytes` is used instead of `SecRandomCopyBytes` because the former is accessible -// via `libSystem` (libc) while the other needs to link to `Security.framework`. -#[cfg(all(target_vendor = "apple", not(target_os = "macos")))] -mod imp { - use libc::size_t; - - use crate::ffi::{c_int, c_void}; - use crate::io::{Error, Result}; - - pub fn syscall(v: &mut [u8]) -> Result<()> { - extern "C" { - fn CCRandomGenerateBytes(bytes: *mut c_void, count: size_t) -> c_int; - } - - let ret = unsafe { CCRandomGenerateBytes(v.as_mut_ptr().cast(), v.len()) }; - if ret != -1 { Ok(()) } else { Err(Error::last_os_error()) } - } -} - -// FIXME: once the 10.x release becomes the minimum, this can be dropped for simplification. -#[cfg(all(target_os = "netbsd", not(netbsd10)))] -mod imp { - use crate::io::{Error, Result}; - use crate::ptr; - - pub fn syscall(v: &mut [u8]) -> Result<()> { - let mib = [libc::CTL_KERN, libc::KERN_ARND]; - // kern.arandom permits a maximum buffer size of 256 bytes - for s in v.chunks_mut(256) { - let mut s_len = s.len(); - let ret = unsafe { - libc::sysctl( - mib.as_ptr(), - mib.len() as libc::c_uint, - s.as_mut_ptr() as *mut _, - &mut s_len, - ptr::null(), - 0, - ) - }; - if ret == -1 { - return Err(Error::last_os_error()); - } else if s_len != s.len() { - // FIXME(joboet): this can't actually happen, can it? - panic!("read less bytes than requested from kern.arandom"); - } - } - - Ok(()) - } -} - -#[cfg(target_os = "fuchsia")] -mod imp { - use crate::io::Result; - - #[link(name = "zircon")] - extern "C" { - fn zx_cprng_draw(buffer: *mut u8, len: usize); - } - - pub fn syscall(v: &mut [u8]) -> Result<()> { - unsafe { zx_cprng_draw(v.as_mut_ptr(), v.len()) }; - Ok(()) - } -} - -#[cfg(target_os = "vxworks")] -mod imp { - use core::sync::atomic::AtomicBool; - use core::sync::atomic::Ordering::Relaxed; - - use crate::io::{Error, Result}; - - pub fn syscall(v: &mut [u8]) -> Result<()> { - static RNG_INIT: AtomicBool = AtomicBool::new(false); - while !RNG_INIT.load(Relaxed) { - let ret = unsafe { libc::randSecure() }; - if ret < 0 { - return Err(Error::last_os_error()); - } else if ret > 0 { - RNG_INIT.store(true, Relaxed); - break; - } - - unsafe { libc::usleep(10) }; - } - - let ret = unsafe { - libc::randABytes(v.as_mut_ptr() as *mut libc::c_uchar, v.len() as libc::c_int) - }; - if ret >= 0 { Ok(()) } else { Err(Error::last_os_error()) } - } -} diff --git a/library/std/src/sys/pal/unix/stack_overflow.rs b/library/std/src/sys/pal/unix/stack_overflow.rs index 728ce8d60f639..e0a0d0973c65b 100644 --- a/library/std/src/sys/pal/unix/stack_overflow.rs +++ b/library/std/src/sys/pal/unix/stack_overflow.rs @@ -36,21 +36,20 @@ impl Drop for Handler { target_os = "illumos", ))] mod imp { + use libc::{ + MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, PROT_NONE, PROT_READ, PROT_WRITE, SA_ONSTACK, + SA_SIGINFO, SIG_DFL, SIGBUS, SIGSEGV, SS_DISABLE, sigaction, sigaltstack, sighandler_t, + }; #[cfg(not(all(target_os = "linux", target_env = "gnu")))] use libc::{mmap as mmap64, mprotect, munmap}; #[cfg(all(target_os = "linux", target_env = "gnu"))] use libc::{mmap64, mprotect, munmap}; - use libc::{ - sigaction, sigaltstack, sighandler_t, MAP_ANON, MAP_FAILED, MAP_FIXED, MAP_PRIVATE, - PROT_NONE, PROT_READ, PROT_WRITE, SA_ONSTACK, SA_SIGINFO, SIGBUS, SIGSEGV, SIG_DFL, - SS_DISABLE, - }; use super::Handler; use crate::cell::Cell; use crate::ops::Range; - use crate::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use crate::sync::OnceLock; + use crate::sync::atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; use crate::sys::pal::unix::os; use crate::{io, mem, ptr, thread}; diff --git a/library/std/src/sys/pal/unix/thread.rs b/library/std/src/sys/pal/unix/thread.rs index c9dcc5ad97a50..7fe9b6c3e52f4 100644 --- a/library/std/src/sys/pal/unix/thread.rs +++ b/library/std/src/sys/pal/unix/thread.rs @@ -516,7 +516,7 @@ mod cgroups { use crate::borrow::Cow; use crate::ffi::OsString; - use crate::fs::{exists, File}; + use crate::fs::{File, exists}; use crate::io::{BufRead, BufReader, Read}; use crate::os::unix::ffi::OsStringExt; use crate::path::{Path, PathBuf}; diff --git a/library/std/src/sys/pal/unix/thread_parking.rs b/library/std/src/sys/pal/unix/thread_parking.rs index 1da5fce3cd30f..72dd2031479ee 100644 --- a/library/std/src/sys/pal/unix/thread_parking.rs +++ b/library/std/src/sys/pal/unix/thread_parking.rs @@ -2,7 +2,7 @@ // separate modules for each platform. #![cfg(target_os = "netbsd")] -use libc::{_lwp_self, c_long, clockid_t, lwpid_t, time_t, timespec, CLOCK_MONOTONIC}; +use libc::{_lwp_self, CLOCK_MONOTONIC, c_long, clockid_t, lwpid_t, time_t, timespec}; use crate::ffi::{c_int, c_void}; use crate::ptr; diff --git a/library/std/src/sys/pal/unsupported/common.rs b/library/std/src/sys/pal/unsupported/common.rs index 76f80291f0ea8..34a766683830d 100644 --- a/library/std/src/sys/pal/unsupported/common.rs +++ b/library/std/src/sys/pal/unsupported/common.rs @@ -27,7 +27,3 @@ pub fn decode_error_kind(_code: i32) -> crate::io::ErrorKind { pub fn abort_internal() -> ! { core::intrinsics::abort(); } - -pub fn hashmap_random_keys() -> (u64, u64) { - (1, 2) -} diff --git a/library/std/src/sys/pal/wasi/fs.rs b/library/std/src/sys/pal/wasi/fs.rs index e1c61cae9f810..59ecc45b06a1f 100644 --- a/library/std/src/sys/pal/wasi/fs.rs +++ b/library/std/src/sys/pal/wasi/fs.rs @@ -13,7 +13,7 @@ use crate::sys::common::small_c_string::run_path_with_cstr; use crate::sys::time::SystemTime; use crate::sys::unsupported; pub use crate::sys_common::fs::exists; -use crate::sys_common::{ignore_notfound, AsInner, FromInner, IntoInner}; +use crate::sys_common::{AsInner, FromInner, IntoInner, ignore_notfound}; use crate::{fmt, iter, ptr}; pub struct File { diff --git a/library/std/src/sys/pal/wasi/helpers.rs b/library/std/src/sys/pal/wasi/helpers.rs index 37ef17858cb96..404747f0dc756 100644 --- a/library/std/src/sys/pal/wasi/helpers.rs +++ b/library/std/src/sys/pal/wasi/helpers.rs @@ -1,6 +1,6 @@ #![forbid(unsafe_op_in_unsafe_fn)] -use crate::{io as std_io, mem}; +use crate::io as std_io; #[inline] pub fn is_interrupted(errno: i32) -> bool { @@ -108,16 +108,6 @@ pub fn abort_internal() -> ! { unsafe { libc::abort() } } -pub fn hashmap_random_keys() -> (u64, u64) { - let mut ret = (0u64, 0u64); - unsafe { - let base = &mut ret as *mut (u64, u64) as *mut u8; - let len = mem::size_of_val(&ret); - wasi::random_get(base, len).expect("random_get failure"); - } - ret -} - #[inline] pub(crate) fn err2io(err: wasi::Errno) -> std_io::Error { std_io::Error::from_raw_os_error(err.raw().into()) diff --git a/library/std/src/sys/pal/wasi/mod.rs b/library/std/src/sys/pal/wasi/mod.rs index 8051021a58897..5d54c7903065c 100644 --- a/library/std/src/sys/pal/wasi/mod.rs +++ b/library/std/src/sys/pal/wasi/mod.rs @@ -47,4 +47,4 @@ mod helpers; // then the compiler complains about conflicts. use helpers::err2io; -pub use helpers::{abort_internal, decode_error_kind, hashmap_random_keys, is_interrupted}; +pub use helpers::{abort_internal, decode_error_kind, is_interrupted}; diff --git a/library/std/src/sys/pal/wasip2/mod.rs b/library/std/src/sys/pal/wasip2/mod.rs index 546fadbe5011c..17b26543bd75f 100644 --- a/library/std/src/sys/pal/wasip2/mod.rs +++ b/library/std/src/sys/pal/wasip2/mod.rs @@ -50,6 +50,6 @@ mod helpers; // then the compiler complains about conflicts. use helpers::err2io; -pub use helpers::{abort_internal, decode_error_kind, hashmap_random_keys, is_interrupted}; +pub use helpers::{abort_internal, decode_error_kind, is_interrupted}; mod cabi_realloc; diff --git a/library/std/src/sys/pal/windows/args.rs b/library/std/src/sys/pal/windows/args.rs index 77d82678f1dcc..848632ec2a7e3 100644 --- a/library/std/src/sys/pal/windows/args.rs +++ b/library/std/src/sys/pal/windows/args.rs @@ -14,8 +14,8 @@ use crate::path::{Path, PathBuf}; use crate::sys::path::get_long_path; use crate::sys::process::ensure_no_nuls; use crate::sys::{c, to_u16s}; -use crate::sys_common::wstr::WStrUnits; use crate::sys_common::AsInner; +use crate::sys_common::wstr::WStrUnits; use crate::{fmt, io, iter, vec}; /// This is the const equivalent to `NonZero::new(n).unwrap()` diff --git a/library/std/src/sys/pal/windows/args/tests.rs b/library/std/src/sys/pal/windows/args/tests.rs index 484a90ab056df..6d5c953cbd5c6 100644 --- a/library/std/src/sys/pal/windows/args/tests.rs +++ b/library/std/src/sys/pal/windows/args/tests.rs @@ -47,10 +47,10 @@ fn whitespace_behavior() { fn genius_quotes() { chk(r#"EXE "" """#, &["EXE", "", ""]); chk(r#"EXE "" """"#, &["EXE", "", r#"""#]); - chk( - r#"EXE "this is """all""" in the same argument""#, - &["EXE", r#"this is "all" in the same argument"#], - ); + chk(r#"EXE "this is """all""" in the same argument""#, &[ + "EXE", + r#"this is "all" in the same argument"#, + ]); chk(r#"EXE "a"""#, &["EXE", r#"a""#]); chk(r#"EXE "a"" a"#, &["EXE", r#"a" a"#]); // quotes cannot be escaped in command names diff --git a/library/std/src/sys/pal/windows/c.rs b/library/std/src/sys/pal/windows/c.rs index b888eb7d95ca3..b65ad7dbe8c5a 100644 --- a/library/std/src/sys/pal/windows/c.rs +++ b/library/std/src/sys/pal/windows/c.rs @@ -5,7 +5,7 @@ #![unstable(issue = "none", feature = "windows_c")] #![allow(clippy::style)] -use core::ffi::{c_uint, c_ulong, c_ushort, c_void, CStr}; +use core::ffi::{CStr, c_uint, c_ulong, c_ushort, c_void}; use core::{mem, ptr}; mod windows_sys; diff --git a/library/std/src/sys/pal/windows/compat.rs b/library/std/src/sys/pal/windows/compat.rs index 75232dfc0b0f1..c8e25dd0c94ba 100644 --- a/library/std/src/sys/pal/windows/compat.rs +++ b/library/std/src/sys/pal/windows/compat.rs @@ -19,7 +19,7 @@ //! function is called. In the worst case, multiple threads may all end up //! importing the same function unnecessarily. -use crate::ffi::{c_void, CStr}; +use crate::ffi::{CStr, c_void}; use crate::ptr::NonNull; use crate::sys::c; diff --git a/library/std/src/sys/pal/windows/fs.rs b/library/std/src/sys/pal/windows/fs.rs index 5b360640c4e67..be26356bb406e 100644 --- a/library/std/src/sys/pal/windows/fs.rs +++ b/library/std/src/sys/pal/windows/fs.rs @@ -1,9 +1,9 @@ use core::ptr::addr_of; use super::api::{self, WinError}; -use super::{to_u16s, IoResult}; +use super::{IoResult, to_u16s}; use crate::borrow::Cow; -use crate::ffi::{c_void, OsStr, OsString}; +use crate::ffi::{OsStr, OsString, c_void}; use crate::io::{self, BorrowedCursor, Error, IoSlice, IoSliceMut, SeekFrom}; use crate::mem::{self, MaybeUninit}; use crate::os::windows::io::{AsHandle, BorrowedHandle}; @@ -13,7 +13,7 @@ use crate::sync::Arc; use crate::sys::handle::Handle; use crate::sys::path::maybe_verbatim; use crate::sys::time::SystemTime; -use crate::sys::{c, cvt, Align8}; +use crate::sys::{Align8, c, cvt}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::{fmt, ptr, slice}; diff --git a/library/std/src/sys/pal/windows/futex.rs b/library/std/src/sys/pal/windows/futex.rs index 8c5081a607aa3..f16a9f534a3ed 100644 --- a/library/std/src/sys/pal/windows/futex.rs +++ b/library/std/src/sys/pal/windows/futex.rs @@ -1,7 +1,7 @@ use core::ffi::c_void; use core::sync::atomic::{ - AtomicBool, AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicPtr, AtomicU16, - AtomicU32, AtomicU64, AtomicU8, AtomicUsize, + AtomicBool, AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicIsize, AtomicPtr, AtomicU8, + AtomicU16, AtomicU32, AtomicU64, AtomicUsize, }; use core::time::Duration; use core::{mem, ptr}; diff --git a/library/std/src/sys/pal/windows/handle/tests.rs b/library/std/src/sys/pal/windows/handle/tests.rs index d836dae4c305b..0c976ed84e6ba 100644 --- a/library/std/src/sys/pal/windows/handle/tests.rs +++ b/library/std/src/sys/pal/windows/handle/tests.rs @@ -1,4 +1,4 @@ -use crate::sys::pipe::{anon_pipe, Pipes}; +use crate::sys::pipe::{Pipes, anon_pipe}; use crate::{thread, time}; /// Test the synchronous fallback for overlapped I/O. diff --git a/library/std/src/sys/pal/windows/mod.rs b/library/std/src/sys/pal/windows/mod.rs index f5ed3e4628e1f..1ea253e5e5263 100644 --- a/library/std/src/sys/pal/windows/mod.rs +++ b/library/std/src/sys/pal/windows/mod.rs @@ -1,7 +1,6 @@ #![allow(missing_docs, nonstandard_style)] #![forbid(unsafe_op_in_unsafe_fn)] -pub use self::rand::hashmap_random_keys; use crate::ffi::{OsStr, OsString}; use crate::io::ErrorKind; use crate::mem::MaybeUninit; @@ -27,7 +26,6 @@ pub mod net; pub mod os; pub mod pipe; pub mod process; -pub mod rand; pub mod stdio; pub mod thread; pub mod time; diff --git a/library/std/src/sys/pal/windows/net.rs b/library/std/src/sys/pal/windows/net.rs index ce995f5ed5af7..61a4504cf6549 100644 --- a/library/std/src/sys/pal/windows/net.rs +++ b/library/std/src/sys/pal/windows/net.rs @@ -9,7 +9,7 @@ use crate::os::windows::io::{ }; use crate::sync::OnceLock; use crate::sys::c; -use crate::sys_common::{net, AsInner, FromInner, IntoInner}; +use crate::sys_common::{AsInner, FromInner, IntoInner, net}; use crate::time::Duration; use crate::{cmp, mem, ptr, sys}; @@ -27,12 +27,12 @@ pub mod netc { use crate::sys::c::{self, ADDRESS_FAMILY, ADDRINFOA, SOCKADDR, SOCKET}; // re-exports from Windows API bindings. pub use crate::sys::c::{ - bind, connect, freeaddrinfo, getpeername, getsockname, getsockopt, listen, setsockopt, - ADDRESS_FAMILY as sa_family_t, ADDRINFOA as addrinfo, IPPROTO_IP, IPPROTO_IPV6, - IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP, IPV6_MULTICAST_LOOP, IPV6_V6ONLY, - IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TTL, - SOCKADDR as sockaddr, SOCKADDR_STORAGE as sockaddr_storage, SOCK_DGRAM, SOCK_STREAM, - SOL_SOCKET, SO_BROADCAST, SO_RCVTIMEO, SO_SNDTIMEO, + ADDRESS_FAMILY as sa_family_t, ADDRINFOA as addrinfo, IP_ADD_MEMBERSHIP, + IP_DROP_MEMBERSHIP, IP_MULTICAST_LOOP, IP_MULTICAST_TTL, IP_TTL, IPPROTO_IP, IPPROTO_IPV6, + IPV6_ADD_MEMBERSHIP, IPV6_DROP_MEMBERSHIP, IPV6_MULTICAST_LOOP, IPV6_V6ONLY, SO_BROADCAST, + SO_RCVTIMEO, SO_SNDTIMEO, SOCK_DGRAM, SOCK_STREAM, SOCKADDR as sockaddr, + SOCKADDR_STORAGE as sockaddr_storage, SOL_SOCKET, bind, connect, freeaddrinfo, getpeername, + getsockname, getsockopt, listen, setsockopt, }; #[allow(non_camel_case_types)] diff --git a/library/std/src/sys/pal/windows/pipe.rs b/library/std/src/sys/pal/windows/pipe.rs index 7d1b5aca1d5fe..d8200ef9ca460 100644 --- a/library/std/src/sys/pal/windows/pipe.rs +++ b/library/std/src/sys/pal/windows/pipe.rs @@ -2,12 +2,13 @@ use crate::ffi::OsStr; use crate::io::{self, BorrowedCursor, IoSlice, IoSliceMut}; use crate::os::windows::prelude::*; use crate::path::Path; +use crate::random::{DefaultRandomSource, Random}; use crate::sync::atomic::AtomicUsize; use crate::sync::atomic::Ordering::Relaxed; +use crate::sys::c; use crate::sys::fs::{File, OpenOptions}; use crate::sys::handle::Handle; use crate::sys::pal::windows::api::{self, WinError}; -use crate::sys::{c, hashmap_random_keys}; use crate::sys_common::{FromInner, IntoInner}; use crate::{mem, ptr}; @@ -79,7 +80,7 @@ pub fn anon_pipe(ours_readable: bool, their_handle_inheritable: bool) -> io::Res name = format!( r"\\.\pipe\__rust_anonymous_pipe1__.{}.{}", c::GetCurrentProcessId(), - random_number() + random_number(), ); let wide_name = OsStr::new(&name).encode_wide().chain(Some(0)).collect::>(); let mut flags = c::FILE_FLAG_FIRST_PIPE_INSTANCE | c::FILE_FLAG_OVERLAPPED; @@ -214,7 +215,7 @@ fn random_number() -> usize { return N.fetch_add(1, Relaxed); } - N.store(hashmap_random_keys().0 as usize, Relaxed); + N.store(usize::random(&mut DefaultRandomSource), Relaxed); } } diff --git a/library/std/src/sys/pal/windows/process.rs b/library/std/src/sys/pal/windows/process.rs index d40a537e3594a..93a6c45ce3000 100644 --- a/library/std/src/sys/pal/windows/process.rs +++ b/library/std/src/sys/pal/windows/process.rs @@ -22,8 +22,8 @@ use crate::sys::fs::{File, OpenOptions}; use crate::sys::handle::Handle; use crate::sys::pipe::{self, AnonPipe}; use crate::sys::{cvt, path, stdio}; -use crate::sys_common::process::{CommandEnv, CommandEnvs}; use crate::sys_common::IntoInner; +use crate::sys_common::process::{CommandEnv, CommandEnvs}; use crate::{cmp, env, fmt, mem, ptr}; //////////////////////////////////////////////////////////////////////////////// @@ -253,10 +253,10 @@ impl Command { attribute: usize, value: T, ) { - self.proc_thread_attributes.insert( - attribute, - ProcThreadAttributeValue { size: mem::size_of::(), data: Box::new(value) }, - ); + self.proc_thread_attributes.insert(attribute, ProcThreadAttributeValue { + size: mem::size_of::(), + data: Box::new(value), + }); } pub fn spawn( diff --git a/library/std/src/sys/pal/windows/process/tests.rs b/library/std/src/sys/pal/windows/process/tests.rs index 65325fa64a077..b567151b72142 100644 --- a/library/std/src/sys/pal/windows/process/tests.rs +++ b/library/std/src/sys/pal/windows/process/tests.rs @@ -1,4 +1,4 @@ -use super::{make_command_line, Arg}; +use super::{Arg, make_command_line}; use crate::env; use crate::ffi::{OsStr, OsString}; use crate::process::Command; diff --git a/library/std/src/sys/pal/windows/rand.rs b/library/std/src/sys/pal/windows/rand.rs deleted file mode 100644 index e366bb995626a..0000000000000 --- a/library/std/src/sys/pal/windows/rand.rs +++ /dev/null @@ -1,27 +0,0 @@ -use core::{mem, ptr}; - -use crate::sys::c; - -#[cfg(not(target_vendor = "win7"))] -#[inline] -pub fn hashmap_random_keys() -> (u64, u64) { - let mut v = (0, 0); - let ret = unsafe { c::ProcessPrng(ptr::addr_of_mut!(v).cast::(), mem::size_of_val(&v)) }; - // ProcessPrng is documented as always returning `TRUE`. - // https://learn.microsoft.com/en-us/windows/win32/seccng/processprng#return-value - debug_assert_eq!(ret, c::TRUE); - v -} - -#[cfg(target_vendor = "win7")] -pub fn hashmap_random_keys() -> (u64, u64) { - use crate::ffi::c_void; - use crate::io; - - let mut v = (0, 0); - let ret = unsafe { - c::RtlGenRandom(ptr::addr_of_mut!(v).cast::(), mem::size_of_val(&v) as u32) - }; - - if ret != 0 { v } else { panic!("RNG broken: {}", io::Error::last_os_error()) } -} diff --git a/library/std/src/sys/pal/xous/net/dns.rs b/library/std/src/sys/pal/xous/net/dns.rs index 50efe978c4a83..d0083c6183793 100644 --- a/library/std/src/sys/pal/xous/net/dns.rs +++ b/library/std/src/sys/pal/xous/net/dns.rs @@ -3,7 +3,7 @@ use core::convert::{TryFrom, TryInto}; use crate::io; use crate::net::{Ipv4Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; use crate::os::xous::ffi::lend_mut; -use crate::os::xous::services::{dns_server, DnsLendMut}; +use crate::os::xous::services::{DnsLendMut, dns_server}; pub struct DnsError { pub code: u8, diff --git a/library/std/src/sys/pal/xous/stdio.rs b/library/std/src/sys/pal/xous/stdio.rs index 11608964b52e6..dfd47a1775ae2 100644 --- a/library/std/src/sys/pal/xous/stdio.rs +++ b/library/std/src/sys/pal/xous/stdio.rs @@ -4,8 +4,8 @@ pub struct Stdin; pub struct Stdout {} pub struct Stderr; -use crate::os::xous::ffi::{lend, try_lend, try_scalar, Connection}; -use crate::os::xous::services::{log_server, try_connect, LogLend, LogScalar}; +use crate::os::xous::ffi::{Connection, lend, try_lend, try_scalar}; +use crate::os::xous::services::{LogLend, LogScalar, log_server, try_connect}; impl Stdin { pub const fn new() -> Stdin { diff --git a/library/std/src/sys/pal/xous/thread.rs b/library/std/src/sys/pal/xous/thread.rs index a95b0aa14d255..0ebb46dc19faa 100644 --- a/library/std/src/sys/pal/xous/thread.rs +++ b/library/std/src/sys/pal/xous/thread.rs @@ -4,10 +4,10 @@ use crate::ffi::CStr; use crate::io; use crate::num::NonZero; use crate::os::xous::ffi::{ - blocking_scalar, create_thread, do_yield, join_thread, map_memory, update_memory_flags, - MemoryFlags, Syscall, ThreadId, + MemoryFlags, Syscall, ThreadId, blocking_scalar, create_thread, do_yield, join_thread, + map_memory, update_memory_flags, }; -use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; +use crate::os::xous::services::{TicktimerScalar, ticktimer_server}; use crate::time::Duration; pub struct Thread { diff --git a/library/std/src/sys/pal/zkvm/args.rs b/library/std/src/sys/pal/zkvm/args.rs index 583c16e3a4721..47857f6c448bc 100644 --- a/library/std/src/sys/pal/zkvm/args.rs +++ b/library/std/src/sys/pal/zkvm/args.rs @@ -1,4 +1,4 @@ -use super::{abi, WORD_SIZE}; +use super::{WORD_SIZE, abi}; use crate::ffi::OsString; use crate::fmt; use crate::sys::os_str; diff --git a/library/std/src/sys/pal/zkvm/mod.rs b/library/std/src/sys/pal/zkvm/mod.rs index 20fdb7468a40d..6ea057720296d 100644 --- a/library/std/src/sys/pal/zkvm/mod.rs +++ b/library/std/src/sys/pal/zkvm/mod.rs @@ -60,11 +60,3 @@ pub fn decode_error_kind(_code: i32) -> crate::io::ErrorKind { pub fn abort_internal() -> ! { core::intrinsics::abort(); } - -pub fn hashmap_random_keys() -> (u64, u64) { - let mut buf = [0u32; 4]; - unsafe { - abi::sys_rand(buf.as_mut_ptr(), 4); - }; - ((buf[0] as u64) << 32 + buf[1] as u64, (buf[2] as u64) << 32 + buf[3] as u64) -} diff --git a/library/std/src/sys/pal/zkvm/os.rs b/library/std/src/sys/pal/zkvm/os.rs index 68d91a123acd4..5d224ffd1ba5a 100644 --- a/library/std/src/sys/pal/zkvm/os.rs +++ b/library/std/src/sys/pal/zkvm/os.rs @@ -1,4 +1,4 @@ -use super::{abi, unsupported, WORD_SIZE}; +use super::{WORD_SIZE, abi, unsupported}; use crate::error::Error as StdError; use crate::ffi::{OsStr, OsString}; use crate::marker::PhantomData; diff --git a/library/std/src/sys/path/windows.rs b/library/std/src/sys/path/windows.rs index 2ae9a0a91996f..9267602cb9715 100644 --- a/library/std/src/sys/path/windows.rs +++ b/library/std/src/sys/path/windows.rs @@ -99,7 +99,7 @@ impl<'a> PrefixParserSlice<'a, '_> { } pub fn parse_prefix(path: &OsStr) -> Option> { - use Prefix::{DeviceNS, Disk, Verbatim, VerbatimDisk, VerbatimUNC, UNC}; + use Prefix::{DeviceNS, Disk, UNC, Verbatim, VerbatimDisk, VerbatimUNC}; let parser = PrefixParser::<8>::new(path); let parser = parser.as_slice(); diff --git a/library/std/src/sys/random/apple.rs b/library/std/src/sys/random/apple.rs new file mode 100644 index 0000000000000..417198c9d850a --- /dev/null +++ b/library/std/src/sys/random/apple.rs @@ -0,0 +1,15 @@ +//! Random data on Apple platforms. +//! +//! `CCRandomGenerateBytes` calls into `CCRandomCopyBytes` with `kCCRandomDefault`. +//! `CCRandomCopyBytes` manages a CSPRNG which is seeded from the kernel's CSPRNG. +//! We use `CCRandomGenerateBytes` instead of `SecCopyBytes` because it is accessible via +//! `libSystem` (libc) while the other needs to link to `Security.framework`. +//! +//! Note that technically, `arc4random_buf` is available as well, but that calls +//! into the same system service anyway, and `CCRandomGenerateBytes` has been +//! proven to be App Store-compatible. + +pub fn fill_bytes(bytes: &mut [u8]) { + let ret = unsafe { libc::CCRandomGenerateBytes(bytes.as_mut_ptr().cast(), bytes.len()) }; + assert_eq!(ret, libc::kCCSuccess, "failed to generate random data"); +} diff --git a/library/std/src/sys/random/arc4random.rs b/library/std/src/sys/random/arc4random.rs new file mode 100644 index 0000000000000..32467e9ebaa64 --- /dev/null +++ b/library/std/src/sys/random/arc4random.rs @@ -0,0 +1,34 @@ +//! Random data generation with `arc4random_buf`. +//! +//! Contrary to its name, `arc4random` doesn't actually use the horribly-broken +//! RC4 cypher anymore, at least not on modern systems, but rather something +//! like ChaCha20 with continual reseeding from the OS. That makes it an ideal +//! source of large quantities of cryptographically secure data, which is exactly +//! what we need for `DefaultRandomSource`. Unfortunately, it's not available +//! on all UNIX systems, most notably Linux (until recently, but it's just a +//! wrapper for `getrandom`. Since we need to hook into `getrandom` directly +//! for `HashMap` keys anyway, we just keep our version). + +#[cfg(not(any( + target_os = "haiku", + target_os = "illumos", + target_os = "solaris", + target_os = "vita", +)))] +use libc::arc4random_buf; + +// FIXME: move these to libc (except Haiku, that one needs to link to libbsd.so). +#[cfg(any( + target_os = "haiku", // See https://git.haiku-os.org/haiku/tree/headers/compatibility/bsd/stdlib.h + target_os = "illumos", // See https://www.illumos.org/man/3C/arc4random + target_os = "solaris", // See https://docs.oracle.com/cd/E88353_01/html/E37843/arc4random-3c.html + target_os = "vita", // See https://github.com/vitasdk/newlib/blob/b89e5bc183b516945f9ee07eef483ecb916e45ff/newlib/libc/include/stdlib.h#L74 +))] +#[cfg_attr(target_os = "haiku", link(name = "bsd"))] +extern "C" { + fn arc4random_buf(buf: *mut core::ffi::c_void, nbytes: libc::size_t); +} + +pub fn fill_bytes(bytes: &mut [u8]) { + unsafe { arc4random_buf(bytes.as_mut_ptr().cast(), bytes.len()) } +} diff --git a/library/std/src/sys/random/espidf.rs b/library/std/src/sys/random/espidf.rs new file mode 100644 index 0000000000000..fd52cb5559ce5 --- /dev/null +++ b/library/std/src/sys/random/espidf.rs @@ -0,0 +1,9 @@ +use crate::ffi::c_void; + +extern "C" { + fn esp_fill_random(buf: *mut c_void, len: usize); +} + +pub fn fill_bytes(bytes: &mut [u8]) { + unsafe { esp_fill_random(bytes.as_mut_ptr().cast(), bytes.len()) } +} diff --git a/library/std/src/sys/random/fuchsia.rs b/library/std/src/sys/random/fuchsia.rs new file mode 100644 index 0000000000000..77d72b3c5b784 --- /dev/null +++ b/library/std/src/sys/random/fuchsia.rs @@ -0,0 +1,13 @@ +//! Random data generation using the Zircon kernel. +//! +//! Fuchsia, as always, is quite nice and provides exactly the API we need: +//! . + +#[link(name = "zircon")] +extern "C" { + fn zx_cprng_draw(buffer: *mut u8, len: usize); +} + +pub fn fill_bytes(bytes: &mut [u8]) { + unsafe { zx_cprng_draw(bytes.as_mut_ptr(), bytes.len()) } +} diff --git a/library/std/src/sys/random/getentropy.rs b/library/std/src/sys/random/getentropy.rs new file mode 100644 index 0000000000000..110ac134c1f47 --- /dev/null +++ b/library/std/src/sys/random/getentropy.rs @@ -0,0 +1,17 @@ +//! Random data generation through `getentropy`. +//! +//! Since issue 8 (2024), the POSIX specification mandates the existence of the +//! `getentropy` function, which fills a slice of up to `GETENTROPY_MAX` bytes +//! (256 on all known platforms) with random data. Unfortunately, it's only +//! meant to be used to seed other CPRNGs, which we don't have, so we only use +//! it where `arc4random_buf` and friends aren't available or secure (currently +//! that's only the case on Emscripten). + +pub fn fill_bytes(bytes: &mut [u8]) { + // GETENTROPY_MAX isn't defined yet on most platforms, but it's mandated + // to be at least 256, so just use that as limit. + for chunk in bytes.chunks_mut(256) { + let r = unsafe { libc::getentropy(chunk.as_mut_ptr().cast(), chunk.len()) }; + assert_ne!(r, -1, "failed to generate random data"); + } +} diff --git a/library/std/src/sys/random/hermit.rs b/library/std/src/sys/random/hermit.rs new file mode 100644 index 0000000000000..92c0550d2d584 --- /dev/null +++ b/library/std/src/sys/random/hermit.rs @@ -0,0 +1,7 @@ +pub fn fill_bytes(mut bytes: &mut [u8]) { + while !bytes.is_empty() { + let res = unsafe { hermit_abi::read_entropy(bytes.as_mut_ptr(), bytes.len(), 0) }; + assert_ne!(res, -1, "failed to generate random data"); + bytes = &mut bytes[res as usize..]; + } +} diff --git a/library/std/src/sys/random/horizon.rs b/library/std/src/sys/random/horizon.rs new file mode 100644 index 0000000000000..0be2eae20a727 --- /dev/null +++ b/library/std/src/sys/random/horizon.rs @@ -0,0 +1,7 @@ +pub fn fill_bytes(mut bytes: &mut [u8]) { + while !bytes.is_empty() { + let r = unsafe { libc::getrandom(bytes.as_mut_ptr().cast(), bytes.len(), 0) }; + assert_ne!(r, -1, "failed to generate random data"); + bytes = &mut bytes[r as usize..]; + } +} diff --git a/library/std/src/sys/random/linux.rs b/library/std/src/sys/random/linux.rs new file mode 100644 index 0000000000000..073fdc45e611e --- /dev/null +++ b/library/std/src/sys/random/linux.rs @@ -0,0 +1,170 @@ +//! Random data generation with the Linux kernel. +//! +//! The first interface random data interface to be introduced on Linux were +//! the `/dev/random` and `/dev/urandom` special files. As paths can become +//! unreachable when inside a chroot and when the file descriptors are exhausted, +//! this was not enough to provide userspace with a reliable source of randomness, +//! so when the OpenBSD 5.6 introduced the `getentropy` syscall, Linux 3.17 got +//! its very own `getrandom` syscall to match.[^1] Unfortunately, even if our +//! minimum supported version were high enough, we still couldn't rely on the +//! syscall being available, as it is blocked in `seccomp` by default. +//! +//! The question is therefore which of the random sources to use. Historically, +//! the kernel contained two pools: the blocking and non-blocking pool. The +//! blocking pool used entropy estimation to limit the amount of available +//! bytes, while the non-blocking pool, once initialized using the blocking +//! pool, uses a CPRNG to return an unlimited number of random bytes. With a +//! strong enough CPRNG however, the entropy estimation didn't contribute that +//! much towards security while being an excellent vector for DoS attacs. Thus, +//! the blocking pool was removed in kernel version 5.6.[^2] That patch did not +//! magically increase the quality of the non-blocking pool, however, so we can +//! safely consider it strong enough even in older kernel versions and use it +//! unconditionally. +//! +//! One additional consideration to make is that the non-blocking pool is not +//! always initialized during early boot. We want the best quality of randomness +//! for the output of `DefaultRandomSource` so we simply wait until it is +//! initialized. When `HashMap` keys however, this represents a potential source +//! of deadlocks, as the additional entropy may only be generated once the +//! program makes forward progress. In that case, we just use the best random +//! data the system has available at the time. +//! +//! So in conclusion, we always want the output of the non-blocking pool, but +//! may need to wait until it is initalized. The default behaviour of `getrandom` +//! is to wait until the non-blocking pool is initialized and then draw from there, +//! so if `getrandom` is available, we use its default to generate the bytes. For +//! `HashMap`, however, we need to specify the `GRND_INSECURE` flags, but that +//! is only available starting with kernel version 5.6. Thus, if we detect that +//! the flag is unsupported, we try `GRND_NONBLOCK` instead, which will only +//! succeed if the pool is initialized. If it isn't, we fall back to the file +//! access method. +//! +//! The behaviour of `/dev/urandom` is inverse to that of `getrandom`: it always +//! yields data, even when the pool is not initialized. For generating `HashMap` +//! keys, this is not important, so we can use it directly. For secure data +//! however, we need to wait until initialization, which we can do by `poll`ing +//! `/dev/random`. +//! +//! TLDR: our fallback strategies are: +//! +//! Secure data | `HashMap` keys +//! --------------------------------------------|------------------ +//! getrandom(0) | getrandom(GRND_INSECURE) +//! poll("/dev/random") && read("/dev/urandom") | getrandom(GRND_NONBLOCK) +//! | read("/dev/urandom") +//! +//! [^1]: +//! [^2]: +//! +// FIXME(in 2040 or so): once the minimum kernel version is 5.6, remove the +// `GRND_NONBLOCK` fallback and use `/dev/random` instead of `/dev/urandom` +// when secure data is required. + +use crate::fs::File; +use crate::io::Read; +use crate::os::fd::AsRawFd; +use crate::sync::OnceLock; +use crate::sync::atomic::AtomicBool; +use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use crate::sys::pal::os::errno; +use crate::sys::pal::weak::syscall; + +fn getrandom(mut bytes: &mut [u8], insecure: bool) { + // A weak symbol allows interposition, e.g. for perf measurements that want to + // disable randomness for consistency. Otherwise, we'll try a raw syscall. + // (`getrandom` was added in glibc 2.25, musl 1.1.20, android API level 28) + syscall! { + fn getrandom( + buffer: *mut libc::c_void, + length: libc::size_t, + flags: libc::c_uint + ) -> libc::ssize_t + } + + static GETRANDOM_AVAILABLE: AtomicBool = AtomicBool::new(true); + static GRND_INSECURE_AVAILABLE: AtomicBool = AtomicBool::new(true); + static URANDOM_READY: AtomicBool = AtomicBool::new(false); + static DEVICE: OnceLock = OnceLock::new(); + + if GETRANDOM_AVAILABLE.load(Relaxed) { + loop { + if bytes.is_empty() { + return; + } + + let flags = if insecure { + if GRND_INSECURE_AVAILABLE.load(Relaxed) { + libc::GRND_INSECURE + } else { + libc::GRND_NONBLOCK + } + } else { + 0 + }; + + let ret = unsafe { getrandom(bytes.as_mut_ptr().cast(), bytes.len(), flags) }; + if ret != -1 { + bytes = &mut bytes[ret as usize..]; + } else { + match errno() { + libc::EINTR => continue, + // `GRND_INSECURE` is not available, try + // `GRND_NONBLOCK`. + libc::EINVAL if flags == libc::GRND_INSECURE => { + GRND_INSECURE_AVAILABLE.store(false, Relaxed); + continue; + } + // The pool is not initialized yet, fall back to + // /dev/urandom for now. + libc::EAGAIN if flags == libc::GRND_NONBLOCK => break, + // `getrandom` is unavailable or blocked by seccomp. + // Don't try it again and fall back to /dev/urandom. + libc::ENOSYS | libc::EPERM => { + GETRANDOM_AVAILABLE.store(false, Relaxed); + break; + } + _ => panic!("failed to generate random data"), + } + } + } + } + + // When we want cryptographic strength, we need to wait for the CPRNG-pool + // to become initialized. Do this by polling `/dev/random` until it is ready. + if !insecure { + if !URANDOM_READY.load(Acquire) { + let random = File::open("/dev/random").expect("failed to open /dev/random"); + let mut fd = libc::pollfd { fd: random.as_raw_fd(), events: libc::POLLIN, revents: 0 }; + + while !URANDOM_READY.load(Acquire) { + let ret = unsafe { libc::poll(&mut fd, 1, -1) }; + match ret { + 1 => { + assert_eq!(fd.revents, libc::POLLIN); + URANDOM_READY.store(true, Release); + break; + } + -1 if errno() == libc::EINTR => continue, + _ => panic!("poll(\"/dev/random\") failed"), + } + } + } + } + + DEVICE + .get_or_try_init(|| File::open("/dev/urandom")) + .and_then(|mut dev| dev.read_exact(bytes)) + .expect("failed to generate random data"); +} + +pub fn fill_bytes(bytes: &mut [u8]) { + getrandom(bytes, false); +} + +pub fn hashmap_random_keys() -> (u64, u64) { + let mut bytes = [0; 16]; + getrandom(&mut bytes, true); + let k1 = u64::from_ne_bytes(bytes[..8].try_into().unwrap()); + let k2 = u64::from_ne_bytes(bytes[8..].try_into().unwrap()); + (k1, k2) +} diff --git a/library/std/src/sys/random/mod.rs b/library/std/src/sys/random/mod.rs new file mode 100644 index 0000000000000..16fb8c64c9b8f --- /dev/null +++ b/library/std/src/sys/random/mod.rs @@ -0,0 +1,95 @@ +cfg_if::cfg_if! { + // Tier 1 + if #[cfg(any(target_os = "linux", target_os = "android"))] { + mod linux; + pub use linux::{fill_bytes, hashmap_random_keys}; + } else if #[cfg(target_os = "windows")] { + mod windows; + pub use windows::fill_bytes; + } else if #[cfg(target_vendor = "apple")] { + mod apple; + pub use apple::fill_bytes; + // Others, in alphabetical ordering. + } else if #[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "haiku", + target_os = "illumos", + target_os = "netbsd", + target_os = "openbsd", + target_os = "solaris", + target_os = "vita", + ))] { + mod arc4random; + pub use arc4random::fill_bytes; + } else if #[cfg(target_os = "emscripten")] { + mod getentropy; + pub use getentropy::fill_bytes; + } else if #[cfg(target_os = "espidf")] { + mod espidf; + pub use espidf::fill_bytes; + } else if #[cfg(target_os = "fuchsia")] { + mod fuchsia; + pub use fuchsia::fill_bytes; + } else if #[cfg(target_os = "hermit")] { + mod hermit; + pub use hermit::fill_bytes; + } else if #[cfg(target_os = "horizon")] { + // FIXME: add arc4random_buf to shim-3ds + mod horizon; + pub use horizon::fill_bytes; + } else if #[cfg(any( + target_os = "hurd", + target_os = "l4re", + target_os = "nto", + ))] { + mod unix_legacy; + pub use unix_legacy::fill_bytes; + } else if #[cfg(target_os = "redox")] { + mod redox; + pub use redox::fill_bytes; + } else if #[cfg(all(target_vendor = "fortanix", target_env = "sgx"))] { + mod sgx; + pub use sgx::fill_bytes; + } else if #[cfg(target_os = "solid_asp3")] { + mod solid; + pub use solid::fill_bytes; + } else if #[cfg(target_os = "teeos")] { + mod teeos; + pub use teeos::fill_bytes; + } else if #[cfg(target_os = "uefi")] { + mod uefi; + pub use uefi::fill_bytes; + } else if #[cfg(target_os = "vxworks")] { + mod vxworks; + pub use vxworks::fill_bytes; + } else if #[cfg(target_os = "wasi")] { + mod wasi; + pub use wasi::fill_bytes; + } else if #[cfg(target_os = "zkvm")] { + mod zkvm; + pub use zkvm::fill_bytes; + } else if #[cfg(any( + all(target_family = "wasm", target_os = "unknown"), + target_os = "xous", + ))] { + // FIXME: finally remove std support for wasm32-unknown-unknown + // FIXME: add random data generation to xous + mod unsupported; + pub use unsupported::{fill_bytes, hashmap_random_keys}; + } +} + +#[cfg(not(any( + target_os = "linux", + target_os = "android", + all(target_family = "wasm", target_os = "unknown"), + target_os = "xous", +)))] +pub fn hashmap_random_keys() -> (u64, u64) { + let mut buf = [0; 16]; + fill_bytes(&mut buf); + let k1 = u64::from_ne_bytes(buf[..8].try_into().unwrap()); + let k2 = u64::from_ne_bytes(buf[8..].try_into().unwrap()); + (k1, k2) +} diff --git a/library/std/src/sys/random/redox.rs b/library/std/src/sys/random/redox.rs new file mode 100644 index 0000000000000..b004335a35176 --- /dev/null +++ b/library/std/src/sys/random/redox.rs @@ -0,0 +1,12 @@ +use crate::fs::File; +use crate::io::Read; +use crate::sync::OnceLock; + +static SCHEME: OnceLock = OnceLock::new(); + +pub fn fill_bytes(bytes: &mut [u8]) { + SCHEME + .get_or_try_init(|| File::open("/scheme/rand")) + .and_then(|mut scheme| scheme.read_exact(bytes)) + .expect("failed to generate random data"); +} diff --git a/library/std/src/sys/random/sgx.rs b/library/std/src/sys/random/sgx.rs new file mode 100644 index 0000000000000..c3647a8df220e --- /dev/null +++ b/library/std/src/sys/random/sgx.rs @@ -0,0 +1,67 @@ +use crate::arch::x86_64::{_rdrand16_step, _rdrand32_step, _rdrand64_step}; + +const RETRIES: u32 = 10; + +fn fail() -> ! { + panic!("failed to generate random data"); +} + +fn rdrand64() -> u64 { + unsafe { + let mut ret: u64 = 0; + for _ in 0..RETRIES { + if _rdrand64_step(&mut ret) == 1 { + return ret; + } + } + + fail(); + } +} + +fn rdrand32() -> u32 { + unsafe { + let mut ret: u32 = 0; + for _ in 0..RETRIES { + if _rdrand32_step(&mut ret) == 1 { + return ret; + } + } + + fail(); + } +} + +fn rdrand16() -> u16 { + unsafe { + let mut ret: u16 = 0; + for _ in 0..RETRIES { + if _rdrand16_step(&mut ret) == 1 { + return ret; + } + } + + fail(); + } +} + +pub fn fill_bytes(bytes: &mut [u8]) { + let mut chunks = bytes.array_chunks_mut(); + for chunk in &mut chunks { + *chunk = rdrand64().to_ne_bytes(); + } + + let mut chunks = chunks.into_remainder().array_chunks_mut(); + for chunk in &mut chunks { + *chunk = rdrand32().to_ne_bytes(); + } + + let mut chunks = chunks.into_remainder().array_chunks_mut(); + for chunk in &mut chunks { + *chunk = rdrand16().to_ne_bytes(); + } + + if let [byte] = chunks.into_remainder() { + *byte = rdrand16() as u8; + } +} diff --git a/library/std/src/sys/random/solid.rs b/library/std/src/sys/random/solid.rs new file mode 100644 index 0000000000000..545771150e284 --- /dev/null +++ b/library/std/src/sys/random/solid.rs @@ -0,0 +1,8 @@ +use crate::sys::pal::abi; + +pub fn fill_bytes(bytes: &mut [u8]) { + unsafe { + let result = abi::SOLID_RNG_SampleRandomBytes(bytes.as_mut_ptr(), bytes.len()); + assert_eq!(result, 0, "failed to generate random data"); + } +} diff --git a/library/std/src/sys/random/teeos.rs b/library/std/src/sys/random/teeos.rs new file mode 100644 index 0000000000000..fd6b24e19e982 --- /dev/null +++ b/library/std/src/sys/random/teeos.rs @@ -0,0 +1,7 @@ +extern "C" { + fn TEE_GenerateRandom(randomBuffer: *mut core::ffi::c_void, randomBufferLen: libc::size_t); +} + +pub fn fill_bytes(bytes: &mut [u8]) { + unsafe { TEE_GenerateRandom(bytes.as_mut_ptr().cast(), bytes.len()) } +} diff --git a/library/std/src/sys/random/uefi.rs b/library/std/src/sys/random/uefi.rs new file mode 100644 index 0000000000000..a4d29e66f3875 --- /dev/null +++ b/library/std/src/sys/random/uefi.rs @@ -0,0 +1,27 @@ +use r_efi::protocols::rng; + +use crate::sys::pal::helpers; + +pub fn fill_bytes(bytes: &mut [u8]) { + let handles = + helpers::locate_handles(rng::PROTOCOL_GUID).expect("failed to generate random data"); + for handle in handles { + if let Ok(protocol) = helpers::open_protocol::(handle, rng::PROTOCOL_GUID) { + let r = unsafe { + ((*protocol.as_ptr()).get_rng)( + protocol.as_ptr(), + crate::ptr::null_mut(), + bytes.len(), + bytes.as_mut_ptr(), + ) + }; + if r.is_error() { + continue; + } else { + return; + } + } + } + + panic!("failed to generate random data"); +} diff --git a/library/std/src/sys/random/unix_legacy.rs b/library/std/src/sys/random/unix_legacy.rs new file mode 100644 index 0000000000000..587068b0d6641 --- /dev/null +++ b/library/std/src/sys/random/unix_legacy.rs @@ -0,0 +1,20 @@ +//! Random data from `/dev/urandom` +//! +//! Before `getentropy` was standardized in 2024, UNIX didn't have a standardized +//! way of getting random data, so systems just followed the precedent set by +//! Linux and exposed random devices at `/dev/random` and `/dev/urandom`. Thus, +//! for the few systems that support neither `arc4random_buf` nor `getentropy` +//! yet, we just read from the file. + +use crate::fs::File; +use crate::io::Read; +use crate::sync::OnceLock; + +static DEVICE: OnceLock = OnceLock::new(); + +pub fn fill_bytes(bytes: &mut [u8]) { + DEVICE + .get_or_try_init(|| File::open("/dev/urandom")) + .and_then(|mut dev| dev.read_exact(bytes)) + .expect("failed to generate random data"); +} diff --git a/library/std/src/sys/random/unsupported.rs b/library/std/src/sys/random/unsupported.rs new file mode 100644 index 0000000000000..d68ce4a9e8703 --- /dev/null +++ b/library/std/src/sys/random/unsupported.rs @@ -0,0 +1,15 @@ +use crate::ptr; + +pub fn fill_bytes(_: &mut [u8]) { + panic!("this target does not support random data generation"); +} + +pub fn hashmap_random_keys() -> (u64, u64) { + // Use allocation addresses for a bit of randomness. This isn't + // particularily secure, but there isn't really an alternative. + let stack = 0u8; + let heap = Box::new(0u8); + let k1 = ptr::from_ref(&stack).addr() as u64; + let k2 = ptr::from_ref(&*heap).addr() as u64; + (k1, k2) +} diff --git a/library/std/src/sys/random/vxworks.rs b/library/std/src/sys/random/vxworks.rs new file mode 100644 index 0000000000000..d549ccebdb2cd --- /dev/null +++ b/library/std/src/sys/random/vxworks.rs @@ -0,0 +1,25 @@ +use crate::sync::atomic::AtomicBool; +use crate::sync::atomic::Ordering::Relaxed; + +static RNG_INIT: AtomicBool = AtomicBool::new(false); + +pub fn fill_bytes(mut bytes: &mut [u8]) { + while !RNG_INIT.load(Relaxed) { + let ret = unsafe { libc::randSecure() }; + if ret < 0 { + panic!("failed to generate random data"); + } else if ret > 0 { + RNG_INIT.store(true, Relaxed); + break; + } + + unsafe { libc::usleep(10) }; + } + + while !bytes.is_empty() { + let len = bytes.len().try_into().unwrap_or(libc::c_int::MAX); + let ret = unsafe { libc::randABytes(bytes.as_mut_ptr(), len) }; + assert!(ret >= 0, "failed to generate random data"); + bytes = &mut bytes[len as usize..]; + } +} diff --git a/library/std/src/sys/random/wasi.rs b/library/std/src/sys/random/wasi.rs new file mode 100644 index 0000000000000..d41da3751fc04 --- /dev/null +++ b/library/std/src/sys/random/wasi.rs @@ -0,0 +1,5 @@ +pub fn fill_bytes(bytes: &mut [u8]) { + unsafe { + wasi::random_get(bytes.as_mut_ptr(), bytes.len()).expect("failed to generate random data") + } +} diff --git a/library/std/src/sys/random/windows.rs b/library/std/src/sys/random/windows.rs new file mode 100644 index 0000000000000..7566000f9e6ff --- /dev/null +++ b/library/std/src/sys/random/windows.rs @@ -0,0 +1,20 @@ +use crate::sys::c; + +#[cfg(not(target_vendor = "win7"))] +#[inline] +pub fn fill_bytes(bytes: &mut [u8]) { + let ret = unsafe { c::ProcessPrng(bytes.as_mut_ptr(), bytes.len()) }; + // ProcessPrng is documented as always returning `TRUE`. + // https://learn.microsoft.com/en-us/windows/win32/seccng/processprng#return-value + debug_assert_eq!(ret, c::TRUE); +} + +#[cfg(target_vendor = "win7")] +pub fn fill_bytes(mut bytes: &mut [u8]) { + while !bytes.is_empty() { + let len = bytes.len().try_into().unwrap_or(u32::MAX); + let ret = unsafe { c::RtlGenRandom(bytes.as_mut_ptr().cast(), len) }; + assert_ne!(ret, 0, "failed to generate random data"); + bytes = &mut bytes[len as usize..]; + } +} diff --git a/library/std/src/sys/random/zkvm.rs b/library/std/src/sys/random/zkvm.rs new file mode 100644 index 0000000000000..3011942f6b26b --- /dev/null +++ b/library/std/src/sys/random/zkvm.rs @@ -0,0 +1,21 @@ +use crate::sys::pal::abi; + +pub fn fill_bytes(bytes: &mut [u8]) { + let (pre, words, post) = unsafe { bytes.align_to_mut::() }; + if !words.is_empty() { + unsafe { + abi::sys_rand(words.as_mut_ptr(), words.len()); + } + } + + let mut buf = [0u32; 2]; + let len = (pre.len() + post.len() + size_of::() - 1) / size_of::(); + if len != 0 { + unsafe { abi::sys_rand(buf.as_mut_ptr(), len) }; + } + + let buf = buf.map(u32::to_ne_bytes); + let buf = buf.as_flattened(); + pre.copy_from_slice(&buf[..pre.len()]); + post.copy_from_slice(&buf[pre.len()..pre.len() + post.len()]); +} diff --git a/library/std/src/sys/sync/condvar/pthread.rs b/library/std/src/sys/sync/condvar/pthread.rs index 2b4bdfe415c80..5b5e7770b0627 100644 --- a/library/std/src/sys/sync/condvar/pthread.rs +++ b/library/std/src/sys/sync/condvar/pthread.rs @@ -2,7 +2,7 @@ use crate::cell::UnsafeCell; use crate::ptr; use crate::sync::atomic::AtomicPtr; use crate::sync::atomic::Ordering::Relaxed; -use crate::sys::sync::{mutex, Mutex}; +use crate::sys::sync::{Mutex, mutex}; #[cfg(not(target_os = "nto"))] use crate::sys::time::TIMESPEC_MAX; #[cfg(target_os = "nto")] diff --git a/library/std/src/sys/sync/condvar/windows7.rs b/library/std/src/sys/sync/condvar/windows7.rs index 56eeeda551ebb..f03feef222124 100644 --- a/library/std/src/sys/sync/condvar/windows7.rs +++ b/library/std/src/sys/sync/condvar/windows7.rs @@ -1,5 +1,5 @@ use crate::cell::UnsafeCell; -use crate::sys::sync::{mutex, Mutex}; +use crate::sys::sync::{Mutex, mutex}; use crate::sys::{c, os}; use crate::time::Duration; diff --git a/library/std/src/sys/sync/condvar/xous.rs b/library/std/src/sys/sync/condvar/xous.rs index 007383479a100..cb55a3e3369bd 100644 --- a/library/std/src/sys/sync/condvar/xous.rs +++ b/library/std/src/sys/sync/condvar/xous.rs @@ -1,7 +1,7 @@ use core::sync::atomic::{AtomicUsize, Ordering}; use crate::os::xous::ffi::{blocking_scalar, scalar}; -use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; +use crate::os::xous::services::{TicktimerScalar, ticktimer_server}; use crate::sys::sync::Mutex; use crate::time::Duration; diff --git a/library/std/src/sys/sync/mutex/fuchsia.rs b/library/std/src/sys/sync/mutex/fuchsia.rs index 81a6361a83a49..3e871285bea01 100644 --- a/library/std/src/sys/sync/mutex/fuchsia.rs +++ b/library/std/src/sys/sync/mutex/fuchsia.rs @@ -40,9 +40,9 @@ use crate::sync::atomic::AtomicU32; use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sys::futex::zircon::{ - zx_futex_wait, zx_futex_wake_single_owner, zx_handle_t, zx_thread_self, ZX_ERR_BAD_HANDLE, - ZX_ERR_BAD_STATE, ZX_ERR_INVALID_ARGS, ZX_ERR_TIMED_OUT, ZX_ERR_WRONG_TYPE, ZX_OK, - ZX_TIME_INFINITE, + ZX_ERR_BAD_HANDLE, ZX_ERR_BAD_STATE, ZX_ERR_INVALID_ARGS, ZX_ERR_TIMED_OUT, ZX_ERR_WRONG_TYPE, + ZX_OK, ZX_TIME_INFINITE, zx_futex_wait, zx_futex_wake_single_owner, zx_handle_t, + zx_thread_self, }; // The lowest two bits of a `zx_handle_t` are always set, so the lowest bit is used to mark the diff --git a/library/std/src/sys/sync/mutex/itron.rs b/library/std/src/sys/sync/mutex/itron.rs index 8440ffdd33772..dcdfff0c81cd7 100644 --- a/library/std/src/sys/sync/mutex/itron.rs +++ b/library/std/src/sys/sync/mutex/itron.rs @@ -3,7 +3,7 @@ #![forbid(unsafe_op_in_unsafe_fn)] use crate::sys::pal::itron::abi; -use crate::sys::pal::itron::error::{expect_success, expect_success_aborting, fail, ItronError}; +use crate::sys::pal::itron::error::{ItronError, expect_success, expect_success_aborting, fail}; use crate::sys::pal::itron::spin::SpinIdOnceCell; pub struct Mutex { diff --git a/library/std/src/sys/sync/mutex/pthread.rs b/library/std/src/sys/sync/mutex/pthread.rs index ee0794334fbe3..1c407bc253776 100644 --- a/library/std/src/sys/sync/mutex/pthread.rs +++ b/library/std/src/sys/sync/mutex/pthread.rs @@ -1,6 +1,6 @@ use crate::cell::UnsafeCell; use crate::io::Error; -use crate::mem::{forget, MaybeUninit}; +use crate::mem::{MaybeUninit, forget}; use crate::sys::cvt_nz; use crate::sys_common::lazy_box::{LazyBox, LazyInit}; diff --git a/library/std/src/sys/sync/mutex/sgx.rs b/library/std/src/sys/sync/mutex/sgx.rs index d37bd02adf8dd..65d1e880f7baf 100644 --- a/library/std/src/sys/sync/mutex/sgx.rs +++ b/library/std/src/sys/sync/mutex/sgx.rs @@ -1,4 +1,4 @@ -use crate::sys::pal::waitqueue::{try_lock_or_false, SpinMutex, WaitQueue, WaitVariable}; +use crate::sys::pal::waitqueue::{SpinMutex, WaitQueue, WaitVariable, try_lock_or_false}; use crate::sys_common::lazy_box::{LazyBox, LazyInit}; /// FIXME: `UnsafeList` is not movable. diff --git a/library/std/src/sys/sync/mutex/xous.rs b/library/std/src/sys/sync/mutex/xous.rs index 63efa5a0210ab..233e638f9130b 100644 --- a/library/std/src/sys/sync/mutex/xous.rs +++ b/library/std/src/sys/sync/mutex/xous.rs @@ -1,5 +1,5 @@ use crate::os::xous::ffi::{blocking_scalar, do_yield}; -use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; +use crate::os::xous::services::{TicktimerScalar, ticktimer_server}; use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sync::atomic::{AtomicBool, AtomicUsize}; diff --git a/library/std/src/sys/sync/rwlock/queue.rs b/library/std/src/sys/sync/rwlock/queue.rs index 458c16516bbe1..0e658328c2e2d 100644 --- a/library/std/src/sys/sync/rwlock/queue.rs +++ b/library/std/src/sys/sync/rwlock/queue.rs @@ -110,7 +110,7 @@ use crate::cell::OnceCell; use crate::hint::spin_loop; use crate::mem; -use crate::ptr::{self, null_mut, without_provenance_mut, NonNull}; +use crate::ptr::{self, NonNull, null_mut, without_provenance_mut}; use crate::sync::atomic::Ordering::{AcqRel, Acquire, Relaxed, Release}; use crate::sync::atomic::{AtomicBool, AtomicPtr}; use crate::thread::{self, Thread}; diff --git a/library/std/src/sys/sync/rwlock/solid.rs b/library/std/src/sys/sync/rwlock/solid.rs index 0537140202091..7703082f95116 100644 --- a/library/std/src/sys/sync/rwlock/solid.rs +++ b/library/std/src/sys/sync/rwlock/solid.rs @@ -2,7 +2,7 @@ #![forbid(unsafe_op_in_unsafe_fn)] use crate::sys::pal::abi; -use crate::sys::pal::itron::error::{expect_success, expect_success_aborting, fail, ItronError}; +use crate::sys::pal::itron::error::{ItronError, expect_success, expect_success_aborting, fail}; use crate::sys::pal::itron::spin::SpinIdOnceCell; pub struct RwLock { diff --git a/library/std/src/sys/sync/thread_parking/id.rs b/library/std/src/sys/sync/thread_parking/id.rs index a7b07b509dfd8..6496435183770 100644 --- a/library/std/src/sys/sync/thread_parking/id.rs +++ b/library/std/src/sys/sync/thread_parking/id.rs @@ -10,8 +10,8 @@ use crate::cell::UnsafeCell; use crate::pin::Pin; use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; -use crate::sync::atomic::{fence, AtomicI8}; -use crate::sys::thread_parking::{current, park, park_timeout, unpark, ThreadId}; +use crate::sync::atomic::{AtomicI8, fence}; +use crate::sys::thread_parking::{ThreadId, current, park, park_timeout, unpark}; use crate::time::Duration; pub struct Parker { diff --git a/library/std/src/sys/sync/thread_parking/windows7.rs b/library/std/src/sys/sync/thread_parking/windows7.rs index 1000b63b6d01a..cdd59757fe2c0 100644 --- a/library/std/src/sys/sync/thread_parking/windows7.rs +++ b/library/std/src/sys/sync/thread_parking/windows7.rs @@ -190,7 +190,7 @@ mod keyed_events { use core::sync::atomic::Ordering::{Acquire, Relaxed}; use core::time::Duration; - use super::{Parker, EMPTY, NOTIFIED}; + use super::{EMPTY, NOTIFIED, Parker}; use crate::sys::c; pub unsafe fn park(parker: Pin<&Parker>) { diff --git a/library/std/src/sys/sync/thread_parking/xous.rs b/library/std/src/sys/sync/thread_parking/xous.rs index 64b6f731f2377..28c90249dc2c2 100644 --- a/library/std/src/sys/sync/thread_parking/xous.rs +++ b/library/std/src/sys/sync/thread_parking/xous.rs @@ -1,5 +1,5 @@ use crate::os::xous::ffi::{blocking_scalar, scalar}; -use crate::os::xous::services::{ticktimer_server, TicktimerScalar}; +use crate::os::xous::services::{TicktimerScalar, ticktimer_server}; use crate::pin::Pin; use crate::ptr; use crate::sync::atomic::AtomicI8; diff --git a/library/std/src/sys/thread_local/guard/key.rs b/library/std/src/sys/thread_local/guard/key.rs index 67c3ca8862767..77575547c1498 100644 --- a/library/std/src/sys/thread_local/guard/key.rs +++ b/library/std/src/sys/thread_local/guard/key.rs @@ -4,7 +4,7 @@ use crate::ptr; use crate::sys::thread_local::destructors; -use crate::sys::thread_local::key::{set, LazyKey}; +use crate::sys::thread_local::key::{LazyKey, set}; pub fn enable() { static DTORS: LazyKey = LazyKey::new(Some(run)); diff --git a/library/std/src/sys/thread_local/key/tests.rs b/library/std/src/sys/thread_local/key/tests.rs index d82b34e71f0e4..c7d2c8e6301ef 100644 --- a/library/std/src/sys/thread_local/key/tests.rs +++ b/library/std/src/sys/thread_local/key/tests.rs @@ -1,4 +1,4 @@ -use super::{get, set, LazyKey}; +use super::{LazyKey, get, set}; use crate::ptr; #[test] diff --git a/library/std/src/sys/thread_local/key/xous.rs b/library/std/src/sys/thread_local/key/xous.rs index 4fb2fdcc61925..295fb848b304d 100644 --- a/library/std/src/sys/thread_local/key/xous.rs +++ b/library/std/src/sys/thread_local/key/xous.rs @@ -39,7 +39,7 @@ use core::arch::asm; use crate::mem::ManuallyDrop; -use crate::os::xous::ffi::{map_memory, unmap_memory, MemoryFlags}; +use crate::os::xous::ffi::{MemoryFlags, map_memory, unmap_memory}; use crate::ptr; use crate::sync::atomic::Ordering::{Acquire, Relaxed, Release}; use crate::sync::atomic::{AtomicPtr, AtomicUsize}; diff --git a/library/std/src/sys/thread_local/os.rs b/library/std/src/sys/thread_local/os.rs index e27b47c3f4536..f09c396ef0f1e 100644 --- a/library/std/src/sys/thread_local/os.rs +++ b/library/std/src/sys/thread_local/os.rs @@ -2,7 +2,7 @@ use super::abort_on_dtor_unwind; use crate::cell::Cell; use crate::marker::PhantomData; use crate::ptr; -use crate::sys::thread_local::key::{get, set, Key, LazyKey}; +use crate::sys::thread_local::key::{Key, LazyKey, get, set}; #[doc(hidden)] #[allow_internal_unstable(thread_local_internals)] diff --git a/library/std/src/sys_common/net.rs b/library/std/src/sys_common/net.rs index 25ebeb3502d20..85a82b088cd4f 100644 --- a/library/std/src/sys_common/net.rs +++ b/library/std/src/sys_common/net.rs @@ -5,7 +5,7 @@ use crate::ffi::{c_int, c_void}; use crate::io::{self, BorrowedCursor, ErrorKind, IoSlice, IoSliceMut}; use crate::net::{Ipv4Addr, Ipv6Addr, Shutdown, SocketAddr}; use crate::sys::common::small_c_string::run_with_cstr; -use crate::sys::net::{cvt, cvt_gai, cvt_r, init, netc as c, wrlen_t, Socket}; +use crate::sys::net::{Socket, cvt, cvt_gai, cvt_r, init, netc as c, wrlen_t}; use crate::sys_common::{AsInner, FromInner, IntoInner}; use crate::time::Duration; use crate::{cmp, fmt, mem, ptr}; diff --git a/library/std/src/sys_common/wtf8.rs b/library/std/src/sys_common/wtf8.rs index 063451ad54e1c..554e07c1e59b9 100644 --- a/library/std/src/sys_common/wtf8.rs +++ b/library/std/src/sys_common/wtf8.rs @@ -18,7 +18,7 @@ #[cfg(test)] mod tests; -use core::char::{encode_utf16_raw, encode_utf8_raw}; +use core::char::{encode_utf8_raw, encode_utf16_raw}; use core::clone::CloneToUninit; use core::str::next_code_point; diff --git a/library/std/src/sys_common/wtf8/tests.rs b/library/std/src/sys_common/wtf8/tests.rs index b57c99a8452a1..bc06eaa2b8fa1 100644 --- a/library/std/src/sys_common/wtf8/tests.rs +++ b/library/std/src/sys_common/wtf8/tests.rs @@ -356,32 +356,32 @@ fn wtf8buf_from_iterator() { fn f(values: &[u32]) -> Wtf8Buf { values.iter().map(|&c| CodePoint::from_u32(c).unwrap()).collect::() } - assert_eq!( - f(&[0x61, 0xE9, 0x20, 0x1F4A9]), - Wtf8Buf { bytes: b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec(), is_known_utf8: true } - ); + assert_eq!(f(&[0x61, 0xE9, 0x20, 0x1F4A9]), Wtf8Buf { + bytes: b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec(), + is_known_utf8: true + }); assert_eq!(f(&[0xD83D, 0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! - assert_eq!( - f(&[0xD83D, 0x20, 0xDCA9]), - Wtf8Buf { bytes: b"\xED\xA0\xBD \xED\xB2\xA9".to_vec(), is_known_utf8: false } - ); - assert_eq!( - f(&[0xD800, 0xDBFF]), - Wtf8Buf { bytes: b"\xED\xA0\x80\xED\xAF\xBF".to_vec(), is_known_utf8: false } - ); - assert_eq!( - f(&[0xD800, 0xE000]), - Wtf8Buf { bytes: b"\xED\xA0\x80\xEE\x80\x80".to_vec(), is_known_utf8: false } - ); - assert_eq!( - f(&[0xD7FF, 0xDC00]), - Wtf8Buf { bytes: b"\xED\x9F\xBF\xED\xB0\x80".to_vec(), is_known_utf8: false } - ); - assert_eq!( - f(&[0x61, 0xDC00]), - Wtf8Buf { bytes: b"\x61\xED\xB0\x80".to_vec(), is_known_utf8: false } - ); + assert_eq!(f(&[0xD83D, 0x20, 0xDCA9]), Wtf8Buf { + bytes: b"\xED\xA0\xBD \xED\xB2\xA9".to_vec(), + is_known_utf8: false + }); + assert_eq!(f(&[0xD800, 0xDBFF]), Wtf8Buf { + bytes: b"\xED\xA0\x80\xED\xAF\xBF".to_vec(), + is_known_utf8: false + }); + assert_eq!(f(&[0xD800, 0xE000]), Wtf8Buf { + bytes: b"\xED\xA0\x80\xEE\x80\x80".to_vec(), + is_known_utf8: false + }); + assert_eq!(f(&[0xD7FF, 0xDC00]), Wtf8Buf { + bytes: b"\xED\x9F\xBF\xED\xB0\x80".to_vec(), + is_known_utf8: false + }); + assert_eq!(f(&[0x61, 0xDC00]), Wtf8Buf { + bytes: b"\x61\xED\xB0\x80".to_vec(), + is_known_utf8: false + }); assert_eq!(f(&[0xDC00]), Wtf8Buf { bytes: b"\xED\xB0\x80".to_vec(), is_known_utf8: false }); } @@ -396,36 +396,36 @@ fn wtf8buf_extend() { string } - assert_eq!( - e(&[0x61, 0xE9], &[0x20, 0x1F4A9]), - Wtf8Buf { bytes: b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec(), is_known_utf8: true } - ); + assert_eq!(e(&[0x61, 0xE9], &[0x20, 0x1F4A9]), Wtf8Buf { + bytes: b"a\xC3\xA9 \xF0\x9F\x92\xA9".to_vec(), + is_known_utf8: true + }); assert_eq!(e(&[0xD83D], &[0xDCA9]).bytes, b"\xF0\x9F\x92\xA9"); // Magic! - assert_eq!( - e(&[0xD83D, 0x20], &[0xDCA9]), - Wtf8Buf { bytes: b"\xED\xA0\xBD \xED\xB2\xA9".to_vec(), is_known_utf8: false } - ); - assert_eq!( - e(&[0xD800], &[0xDBFF]), - Wtf8Buf { bytes: b"\xED\xA0\x80\xED\xAF\xBF".to_vec(), is_known_utf8: false } - ); - assert_eq!( - e(&[0xD800], &[0xE000]), - Wtf8Buf { bytes: b"\xED\xA0\x80\xEE\x80\x80".to_vec(), is_known_utf8: false } - ); - assert_eq!( - e(&[0xD7FF], &[0xDC00]), - Wtf8Buf { bytes: b"\xED\x9F\xBF\xED\xB0\x80".to_vec(), is_known_utf8: false } - ); - assert_eq!( - e(&[0x61], &[0xDC00]), - Wtf8Buf { bytes: b"\x61\xED\xB0\x80".to_vec(), is_known_utf8: false } - ); - assert_eq!( - e(&[], &[0xDC00]), - Wtf8Buf { bytes: b"\xED\xB0\x80".to_vec(), is_known_utf8: false } - ); + assert_eq!(e(&[0xD83D, 0x20], &[0xDCA9]), Wtf8Buf { + bytes: b"\xED\xA0\xBD \xED\xB2\xA9".to_vec(), + is_known_utf8: false + }); + assert_eq!(e(&[0xD800], &[0xDBFF]), Wtf8Buf { + bytes: b"\xED\xA0\x80\xED\xAF\xBF".to_vec(), + is_known_utf8: false + }); + assert_eq!(e(&[0xD800], &[0xE000]), Wtf8Buf { + bytes: b"\xED\xA0\x80\xEE\x80\x80".to_vec(), + is_known_utf8: false + }); + assert_eq!(e(&[0xD7FF], &[0xDC00]), Wtf8Buf { + bytes: b"\xED\x9F\xBF\xED\xB0\x80".to_vec(), + is_known_utf8: false + }); + assert_eq!(e(&[0x61], &[0xDC00]), Wtf8Buf { + bytes: b"\x61\xED\xB0\x80".to_vec(), + is_known_utf8: false + }); + assert_eq!(e(&[], &[0xDC00]), Wtf8Buf { + bytes: b"\xED\xB0\x80".to_vec(), + is_known_utf8: false + }); } #[test] @@ -556,10 +556,9 @@ fn wtf8_encode_wide() { let mut string = Wtf8Buf::from_str("aé "); string.push(CodePoint::from_u32(0xD83D).unwrap()); string.push_char('💩'); - assert_eq!( - string.encode_wide().collect::>(), - vec![0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9] - ); + assert_eq!(string.encode_wide().collect::>(), vec![ + 0x61, 0xE9, 0x20, 0xD83D, 0xD83D, 0xDCA9 + ]); } #[test] diff --git a/library/std/src/thread/mod.rs b/library/std/src/thread/mod.rs index 33cb7e0bcca82..a53e3565dfe35 100644 --- a/library/std/src/thread/mod.rs +++ b/library/std/src/thread/mod.rs @@ -162,12 +162,12 @@ use crate::any::Any; use crate::cell::{Cell, OnceCell, UnsafeCell}; use crate::ffi::CStr; use crate::marker::PhantomData; -use crate::mem::{self, forget, ManuallyDrop}; +use crate::mem::{self, ManuallyDrop, forget}; use crate::num::NonZero; use crate::pin::Pin; use crate::ptr::addr_of_mut; -use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sync::Arc; +use crate::sync::atomic::{AtomicUsize, Ordering}; use crate::sys::sync::Parker; use crate::sys::thread as imp; use crate::sys_common::{AsInner, IntoInner}; @@ -178,7 +178,7 @@ use crate::{env, fmt, io, panic, panicking, str}; mod scoped; #[stable(feature = "scoped_threads", since = "1.63.0")] -pub use scoped::{scope, Scope, ScopedJoinHandle}; +pub use scoped::{Scope, ScopedJoinHandle, scope}; //////////////////////////////////////////////////////////////////////////////// // Thread-local storage diff --git a/library/std/src/thread/scoped.rs b/library/std/src/thread/scoped.rs index ba27c9220aea5..b2305b1eda7e1 100644 --- a/library/std/src/thread/scoped.rs +++ b/library/std/src/thread/scoped.rs @@ -1,8 +1,8 @@ -use super::{current, park, Builder, JoinInner, Result, Thread}; +use super::{Builder, JoinInner, Result, Thread, current, park}; use crate::marker::PhantomData; -use crate::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; -use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use crate::panic::{AssertUnwindSafe, catch_unwind, resume_unwind}; use crate::sync::Arc; +use crate::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use crate::{fmt, io}; /// A scope to spawn scoped threads in. diff --git a/library/std/src/thread/tests.rs b/library/std/src/thread/tests.rs index aa464d56f95b2..ff45e82bd9c71 100644 --- a/library/std/src/thread/tests.rs +++ b/library/std/src/thread/tests.rs @@ -2,7 +2,7 @@ use super::Builder; use crate::any::Any; use crate::panic::panic_any; use crate::sync::atomic::{AtomicBool, Ordering}; -use crate::sync::mpsc::{channel, Sender}; +use crate::sync::mpsc::{Sender, channel}; use crate::sync::{Arc, Barrier}; use crate::thread::{self, Scope, ThreadId}; use crate::time::{Duration, Instant}; diff --git a/library/std/src/time/tests.rs b/library/std/src/time/tests.rs index de36dc4c9fd16..e88f2d5e80676 100644 --- a/library/std/src/time/tests.rs +++ b/library/std/src/time/tests.rs @@ -1,7 +1,7 @@ use core::fmt::Debug; #[cfg(not(target_arch = "wasm32"))] -use test::{black_box, Bencher}; +use test::{Bencher, black_box}; use super::{Duration, Instant, SystemTime, UNIX_EPOCH}; @@ -235,8 +235,8 @@ macro_rules! bench_instant_threaded { #[bench] #[cfg(not(target_arch = "wasm32"))] fn $bench_name(b: &mut Bencher) -> crate::thread::Result<()> { - use crate::sync::atomic::{AtomicBool, Ordering}; use crate::sync::Arc; + use crate::sync::atomic::{AtomicBool, Ordering}; let running = Arc::new(AtomicBool::new(true)); diff --git a/library/std/tests/thread.rs b/library/std/tests/thread.rs index 79a981d0b0d18..fc9917178b244 100644 --- a/library/std/tests/thread.rs +++ b/library/std/tests/thread.rs @@ -37,3 +37,21 @@ fn thread_local_containing_const_statements() { assert_eq!(CELL.get(), 1); assert_eq!(REFCELL.take(), 1); } + +#[test] +// Include an ignore list on purpose, so that new platforms don't miss it +#[cfg_attr( + any( + target_os = "redox", + target_os = "l4re", + target_env = "sgx", + target_os = "solid_asp3", + target_os = "teeos", + target_os = "wasi" + ), + should_panic +)] +fn available_parallelism() { + // check that std::thread::available_parallelism() returns a valid value + assert!(thread::available_parallelism().is_ok()); +} diff --git a/library/test/src/bench.rs b/library/test/src/bench.rs index b71def3b03223..62e51026b818c 100644 --- a/library/test/src/bench.rs +++ b/library/test/src/bench.rs @@ -1,15 +1,15 @@ //! Benchmarking module. -use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use std::{cmp, io}; +use super::Sender; use super::event::CompletedTest; use super::options::BenchMode; use super::test_result::TestResult; use super::types::{TestDesc, TestId}; -use super::Sender; use crate::stats; /// An identity function that *__hints__* to the compiler to be maximally pessimistic about what diff --git a/library/test/src/lib.rs b/library/test/src/lib.rs index 632f8d161affa..ebbe50cc65154 100644 --- a/library/test/src/lib.rs +++ b/library/test/src/lib.rs @@ -28,17 +28,17 @@ pub use cli::TestOpts; -pub use self::bench::{black_box, Bencher}; +pub use self::ColorConfig::*; +pub use self::bench::{Bencher, black_box}; pub use self::console::run_tests_console; pub use self::options::{ColorConfig, Options, OutputFormat, RunIgnored, ShouldPanic}; pub use self::types::TestName::*; pub use self::types::*; -pub use self::ColorConfig::*; // Module to be used by rustc to compile tests in libtest pub mod test { pub use crate::bench::Bencher; - pub use crate::cli::{parse_opts, TestOpts}; + pub use crate::cli::{TestOpts, parse_opts}; pub use crate::helpers::metrics::{Metric, MetricMap}; pub use crate::options::{Options, RunIgnored, RunStrategy, ShouldPanic}; pub use crate::test_result::{TestResult, TrFailed, TrFailedMsg, TrIgnored, TrOk}; @@ -53,9 +53,9 @@ pub mod test { use std::collections::VecDeque; use std::io::prelude::Write; use std::mem::ManuallyDrop; -use std::panic::{self, catch_unwind, AssertUnwindSafe, PanicHookInfo}; +use std::panic::{self, AssertUnwindSafe, PanicHookInfo, catch_unwind}; use std::process::{self, Command, Termination}; -use std::sync::mpsc::{channel, Sender}; +use std::sync::mpsc::{Sender, channel}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use std::{env, io, thread}; diff --git a/library/test/src/term/terminfo/mod.rs b/library/test/src/term/terminfo/mod.rs index 67eec3ca50f48..ac10ec2b850ec 100644 --- a/library/test/src/term/terminfo/mod.rs +++ b/library/test/src/term/terminfo/mod.rs @@ -7,11 +7,11 @@ use std::io::{self, BufReader}; use std::path::Path; use std::{env, error, fmt}; -use parm::{expand, Param, Variables}; +use parm::{Param, Variables, expand}; use parser::compiled::{msys_terminfo, parse}; use searcher::get_dbpath_for_term; -use super::{color, Terminal}; +use super::{Terminal, color}; /// A parsed terminfo database entry. #[allow(unused)] diff --git a/library/test/src/term/win.rs b/library/test/src/term/win.rs index ce9cad37f306b..c77e6aac478bc 100644 --- a/library/test/src/term/win.rs +++ b/library/test/src/term/win.rs @@ -5,7 +5,7 @@ use std::io; use std::io::prelude::*; -use super::{color, Terminal}; +use super::{Terminal, color}; /// A Terminal implementation that uses the Win32 Console API. pub(crate) struct WinConsole { diff --git a/library/test/src/tests.rs b/library/test/src/tests.rs index ba2f35362c54f..e85e61090a91b 100644 --- a/library/test/src/tests.rs +++ b/library/test/src/tests.rs @@ -3,11 +3,11 @@ use crate::{ console::OutputLocation, formatters::PrettyFormatter, test::{ - parse_opts, MetricMap, // FIXME (introduced by #65251) // ShouldPanic, StaticTestName, TestDesc, TestDescAndFn, TestOpts, TestTimeOptions, // TestType, TrFailedMsg, TrIgnored, TrOk, + parse_opts, }, time::{TestTimeOptions, TimeThreshold}, }; diff --git a/library/unwind/src/unwinding.rs b/library/unwind/src/unwinding.rs index b3460791ce5ca..1b94005ab6cd0 100644 --- a/library/unwind/src/unwinding.rs +++ b/library/unwind/src/unwinding.rs @@ -32,7 +32,7 @@ pub use unwinding::abi::{UnwindContext, UnwindException}; pub enum _Unwind_Context {} pub use unwinding::custom_eh_frame_finder::{ - set_custom_eh_frame_finder, EhFrameFinder, FrameInfo, FrameInfoKind, + EhFrameFinder, FrameInfo, FrameInfoKind, set_custom_eh_frame_finder, }; pub type _Unwind_Exception_Class = u64; diff --git a/rustfmt.toml b/rustfmt.toml index e62ab86d04e53..4d48236a393c4 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,5 +1,5 @@ # Run rustfmt with this config (it should be picked up automatically). -version = "Two" +style_edition = "2024" use_small_heuristics = "Max" merge_derives = false group_imports = "StdExternalCrate" diff --git a/src/bootstrap/mk/Makefile.in b/src/bootstrap/mk/Makefile.in index 3fa2b3c22921e..92c8f5dc452fc 100644 --- a/src/bootstrap/mk/Makefile.in +++ b/src/bootstrap/mk/Makefile.in @@ -95,7 +95,7 @@ install: tidy: $(Q)$(BOOTSTRAP) test --stage 2 src/tools/tidy $(BOOTSTRAP_ARGS) prepare: - $(Q)$(BOOTSTRAP) build --stage 2 nonexistent/path/to/trigger/cargo/metadata + $(Q)$(BOOTSTRAP) build --stage 2 --dry-run ## MSVC native builders diff --git a/src/bootstrap/src/bin/main.rs b/src/bootstrap/src/bin/main.rs index f03f03e2d9398..b9df7336cca0b 100644 --- a/src/bootstrap/src/bin/main.rs +++ b/src/bootstrap/src/bin/main.rs @@ -11,8 +11,8 @@ use std::str::FromStr; use std::{env, process}; use bootstrap::{ - find_recent_config_change_ids, human_readable_changes, t, Build, Config, Flags, Subcommand, - CONFIG_CHANGE_HISTORY, + Build, CONFIG_CHANGE_HISTORY, Config, Flags, Subcommand, find_recent_config_change_ids, + human_readable_changes, t, }; fn main() { diff --git a/src/bootstrap/src/core/build_steps/check.rs b/src/bootstrap/src/core/build_steps/check.rs index ba12e64c4a26f..7671fc7e013b7 100644 --- a/src/bootstrap/src/core/build_steps/check.rs +++ b/src/bootstrap/src/core/build_steps/check.rs @@ -5,9 +5,9 @@ use std::path::PathBuf; use crate::core::build_steps::compile::{ add_to_sysroot, run_cargo, rustc_cargo, rustc_cargo_env, std_cargo, std_crates_for_run_make, }; -use crate::core::build_steps::tool::{prepare_tool_cargo, SourceType}; +use crate::core::build_steps::tool::{SourceType, prepare_tool_cargo}; use crate::core::builder::{ - self, crate_description, Alias, Builder, Kind, RunConfig, ShouldRun, Step, + self, Alias, Builder, Kind, RunConfig, ShouldRun, Step, crate_description, }; use crate::core::config::TargetSelection; use crate::{Compiler, Mode, Subcommand}; diff --git a/src/bootstrap/src/core/build_steps/clean.rs b/src/bootstrap/src/core/build_steps/clean.rs index f608e5d715e49..040690623a108 100644 --- a/src/bootstrap/src/core/build_steps/clean.rs +++ b/src/bootstrap/src/core/build_steps/clean.rs @@ -9,7 +9,7 @@ use std::fs; use std::io::{self, ErrorKind}; use std::path::Path; -use crate::core::builder::{crate_description, Builder, RunConfig, ShouldRun, Step}; +use crate::core::builder::{Builder, RunConfig, ShouldRun, Step, crate_description}; use crate::utils::helpers::t; use crate::{Build, Compiler, Kind, Mode, Subcommand}; diff --git a/src/bootstrap/src/core/build_steps/clippy.rs b/src/bootstrap/src/core/build_steps/clippy.rs index a0992350722fe..cd198c425c008 100644 --- a/src/bootstrap/src/core/build_steps/clippy.rs +++ b/src/bootstrap/src/core/build_steps/clippy.rs @@ -1,12 +1,12 @@ //! Implementation of running clippy on the compiler, standard library and various tools. use super::compile::{librustc_stamp, libstd_stamp, run_cargo, rustc_cargo, std_cargo}; -use super::tool::{prepare_tool_cargo, SourceType}; +use super::tool::{SourceType, prepare_tool_cargo}; use super::{check, compile}; use crate::builder::{Builder, ShouldRun}; use crate::core::build_steps::compile::std_crates_for_run_make; use crate::core::builder; -use crate::core::builder::{crate_description, Alias, Kind, RunConfig, Step}; +use crate::core::builder::{Alias, Kind, RunConfig, Step, crate_description}; use crate::{Mode, Subcommand, TargetSelection}; /// Disable the most spammy clippy lints diff --git a/src/bootstrap/src/core/build_steps/compile.rs b/src/bootstrap/src/core/build_steps/compile.rs index e1ab1e7599e84..0e596f0da0ec7 100644 --- a/src/bootstrap/src/core/build_steps/compile.rs +++ b/src/bootstrap/src/core/build_steps/compile.rs @@ -9,8 +9,8 @@ use std::borrow::Cow; use std::collections::HashSet; use std::ffi::OsStr; -use std::io::prelude::*; use std::io::BufReader; +use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::{env, fs, str}; @@ -22,14 +22,14 @@ use crate::core::build_steps::tool::SourceType; use crate::core::build_steps::{dist, llvm}; use crate::core::builder; use crate::core::builder::{ - crate_description, Builder, Cargo, Kind, PathSet, RunConfig, ShouldRun, Step, TaskPath, + Builder, Cargo, Kind, PathSet, RunConfig, ShouldRun, Step, TaskPath, crate_description, }; use crate::core::config::{DebuginfoLevel, LlvmLibunwind, RustcLto, TargetSelection}; use crate::utils::exec::command; use crate::utils::helpers::{ self, exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date, }; -use crate::{CLang, Compiler, DependencyType, GitRepo, Mode, LLVM_TOOLS}; +use crate::{CLang, Compiler, DependencyType, GitRepo, LLVM_TOOLS, Mode}; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Std { @@ -1057,6 +1057,10 @@ pub fn rustc_cargo( // killed, rather than having an error bubble up and cause a panic. cargo.rustflag("-Zon-broken-pipe=kill"); + if builder.config.llvm_enzyme { + cargo.rustflag("-l").rustflag("Enzyme-19"); + } + // We currently don't support cross-crate LTO in stage0. This also isn't hugely necessary // and may just be a time sink. if compiler.stage != 0 { diff --git a/src/bootstrap/src/core/build_steps/dist.rs b/src/bootstrap/src/core/build_steps/dist.rs index 294a56b3e976a..4c557366297ed 100644 --- a/src/bootstrap/src/core/build_steps/dist.rs +++ b/src/bootstrap/src/core/build_steps/dist.rs @@ -14,8 +14,8 @@ use std::io::Write; use std::path::{Path, PathBuf}; use std::{env, fs}; -use object::read::archive::ArchiveFile; use object::BinaryFormat; +use object::read::archive::ArchiveFile; use crate::core::build_steps::doc::DocumentationFormat; use crate::core::build_steps::tool::{self, Tool}; @@ -24,12 +24,12 @@ use crate::core::build_steps::{compile, llvm}; use crate::core::builder::{Builder, Kind, RunConfig, ShouldRun, Step}; use crate::core::config::TargetSelection; use crate::utils::channel::{self, Info}; -use crate::utils::exec::{command, BootstrapCommand}; +use crate::utils::exec::{BootstrapCommand, command}; use crate::utils::helpers::{ exe, is_dylib, move_file, t, target_supports_cranelift_backend, timeit, }; use crate::utils::tarball::{GeneratedTarball, OverlayKind, Tarball}; -use crate::{Compiler, DependencyType, Mode, LLVM_TOOLS}; +use crate::{Compiler, DependencyType, LLVM_TOOLS, Mode}; pub fn pkgname(builder: &Builder<'_>, component: &str) -> String { format!("{}-{}", component, builder.rust_package_vers()) diff --git a/src/bootstrap/src/core/build_steps/doc.rs b/src/bootstrap/src/core/build_steps/doc.rs index 979671cfa9d31..3d504c3771fb2 100644 --- a/src/bootstrap/src/core/build_steps/doc.rs +++ b/src/bootstrap/src/core/build_steps/doc.rs @@ -11,14 +11,14 @@ use std::io::{self, Write}; use std::path::{Path, PathBuf}; use std::{env, fs, mem}; +use crate::Mode; use crate::core::build_steps::compile; -use crate::core::build_steps::tool::{self, prepare_tool_cargo, SourceType, Tool}; +use crate::core::build_steps::tool::{self, SourceType, Tool, prepare_tool_cargo}; use crate::core::builder::{ - self, crate_description, Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step, + self, Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step, crate_description, }; use crate::core::config::{Config, TargetSelection}; use crate::utils::helpers::{symlink_dir, t, up_to_date}; -use crate::Mode; macro_rules! submodule_helper { ($path:expr, submodule) => { @@ -63,7 +63,7 @@ macro_rules! book { src: builder.src.join($path), parent: Some(self), languages: $lang.into(), - rustdoc: None, + rustdoc_compiler: None, }) } } @@ -113,7 +113,7 @@ impl Step for UnstableBook { src: builder.md_doc_out(self.target).join("unstable-book"), parent: Some(self), languages: vec![], - rustdoc: None, + rustdoc_compiler: None, }) } } @@ -125,7 +125,7 @@ struct RustbookSrc { src: PathBuf, parent: Option

, languages: Vec<&'static str>, - rustdoc: Option, + rustdoc_compiler: Option, } impl Step for RustbookSrc

{ @@ -157,7 +157,9 @@ impl Step for RustbookSrc

{ let _ = fs::remove_dir_all(&out); let mut rustbook_cmd = builder.tool_cmd(Tool::Rustbook); - if let Some(mut rustdoc) = self.rustdoc { + + if let Some(compiler) = self.rustdoc_compiler { + let mut rustdoc = builder.rustdoc(compiler); rustdoc.pop(); let old_path = env::var_os("PATH").unwrap_or_default(); let new_path = @@ -165,6 +167,7 @@ impl Step for RustbookSrc

{ .expect("could not add rustdoc to PATH"); rustbook_cmd.env("PATH", new_path); + builder.add_rustc_lib_path(compiler, &mut rustbook_cmd); } rustbook_cmd.arg("build").arg(&src).arg("-d").arg(&out).run(builder); @@ -240,7 +243,7 @@ impl Step for TheBook { src: absolute_path.clone(), parent: Some(self), languages: vec![], - rustdoc: None, + rustdoc_compiler: None, }); // building older edition redirects @@ -253,7 +256,7 @@ impl Step for TheBook { // treat the other editions as not having a parent. parent: Option::::None, languages: vec![], - rustdoc: None, + rustdoc_compiler: None, }); } @@ -1236,7 +1239,7 @@ impl Step for RustcBook { src: out_base, parent: Some(self), languages: vec![], - rustdoc: None, + rustdoc_compiler: None, }); } } @@ -1270,16 +1273,15 @@ impl Step for Reference { // This is needed for generating links to the standard library using // the mdbook-spec plugin. builder.ensure(compile::Std::new(self.compiler, builder.config.build)); - let rustdoc = builder.rustdoc(self.compiler); // Run rustbook/mdbook to generate the HTML pages. builder.ensure(RustbookSrc { target: self.target, name: "reference".to_owned(), src: builder.src.join("src/doc/reference"), + rustdoc_compiler: Some(self.compiler), parent: Some(self), languages: vec![], - rustdoc: Some(rustdoc), }); } } diff --git a/src/bootstrap/src/core/build_steps/format.rs b/src/bootstrap/src/core/build_steps/format.rs index bbd81fb570bd5..952d8d73328fb 100644 --- a/src/bootstrap/src/core/build_steps/format.rs +++ b/src/bootstrap/src/core/build_steps/format.rs @@ -3,8 +3,8 @@ use std::collections::VecDeque; use std::path::{Path, PathBuf}; use std::process::Command; -use std::sync::mpsc::SyncSender; use std::sync::Mutex; +use std::sync::mpsc::SyncSender; use build_helper::ci::CiEnv; use build_helper::git::get_git_modified_files; diff --git a/src/bootstrap/src/core/build_steps/gcc.rs b/src/bootstrap/src/core/build_steps/gcc.rs index f7a88930b8d54..b950bec11fd01 100644 --- a/src/bootstrap/src/core/build_steps/gcc.rs +++ b/src/bootstrap/src/core/build_steps/gcc.rs @@ -15,8 +15,8 @@ use std::sync::OnceLock; use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::core::config::TargetSelection; use crate::utils::exec::command; -use crate::utils::helpers::{self, t, HashStamp}; -use crate::{generate_smart_stamp_hash, Kind}; +use crate::utils::helpers::{self, HashStamp, t}; +use crate::{Kind, generate_smart_stamp_hash}; pub struct Meta { stamp: HashStamp, diff --git a/src/bootstrap/src/core/build_steps/llvm.rs b/src/bootstrap/src/core/build_steps/llvm.rs index d8752d037618e..b3bc6df1f87f4 100644 --- a/src/bootstrap/src/core/build_steps/llvm.rs +++ b/src/bootstrap/src/core/build_steps/llvm.rs @@ -23,9 +23,9 @@ use crate::core::config::{Config, TargetSelection}; use crate::utils::channel; use crate::utils::exec::command; use crate::utils::helpers::{ - self, exe, get_clang_cl_resource_dir, output, t, unhashed_basename, up_to_date, HashStamp, + self, HashStamp, exe, get_clang_cl_resource_dir, output, t, unhashed_basename, up_to_date, }; -use crate::{generate_smart_stamp_hash, CLang, GitRepo, Kind}; +use crate::{CLang, GitRepo, Kind, generate_smart_stamp_hash}; #[derive(Clone)] pub struct LlvmResult { @@ -154,16 +154,12 @@ pub fn prebuilt_llvm_config(builder: &Builder<'_>, target: TargetSelection) -> L /// This retrieves the LLVM sha we *want* to use, according to git history. pub(crate) fn detect_llvm_sha(config: &Config, is_git: bool) -> String { let llvm_sha = if is_git { - get_closest_merge_commit( - Some(&config.src), - &config.git_config(), - &[ - config.src.join("src/llvm-project"), - config.src.join("src/bootstrap/download-ci-llvm-stamp"), - // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly` - config.src.join("src/version"), - ], - ) + get_closest_merge_commit(Some(&config.src), &config.git_config(), &[ + config.src.join("src/llvm-project"), + config.src.join("src/bootstrap/download-ci-llvm-stamp"), + // the LLVM shared object file is named `LLVM-12-rust-{version}-nightly` + config.src.join("src/version"), + ]) .unwrap() } else if let Some(info) = channel::read_commit_info_file(&config.src) { info.sha.trim().to_owned() diff --git a/src/bootstrap/src/core/build_steps/run.rs b/src/bootstrap/src/core/build_steps/run.rs index 65d635c0bd69f..c7bcd76caddb9 100644 --- a/src/bootstrap/src/core/build_steps/run.rs +++ b/src/bootstrap/src/core/build_steps/run.rs @@ -5,14 +5,14 @@ use std::path::PathBuf; +use crate::Mode; use crate::core::build_steps::dist::distdir; use crate::core::build_steps::test; use crate::core::build_steps::tool::{self, SourceType, Tool}; use crate::core::builder::{Builder, Kind, RunConfig, ShouldRun, Step}; -use crate::core::config::flags::get_completion; use crate::core::config::TargetSelection; +use crate::core::config::flags::get_completion; use crate::utils::exec::command; -use crate::Mode; #[derive(Debug, PartialOrd, Ord, Clone, Hash, PartialEq, Eq)] pub struct BuildManifest; diff --git a/src/bootstrap/src/core/build_steps/setup.rs b/src/bootstrap/src/core/build_steps/setup.rs index f7b26712cabd6..f4c5fe5ff941c 100644 --- a/src/bootstrap/src/core/build_steps/setup.rs +++ b/src/bootstrap/src/core/build_steps/setup.rs @@ -9,7 +9,7 @@ use std::env::consts::EXE_SUFFIX; use std::fmt::Write as _; use std::fs::File; use std::io::Write; -use std::path::{Path, PathBuf, MAIN_SEPARATOR_STR}; +use std::path::{MAIN_SEPARATOR_STR, Path, PathBuf}; use std::str::FromStr; use std::{fmt, fs, io}; @@ -19,7 +19,7 @@ use crate::core::builder::{Builder, RunConfig, ShouldRun, Step}; use crate::utils::change_tracker::CONFIG_CHANGE_HISTORY; use crate::utils::exec::command; use crate::utils::helpers::{self, hex_encode}; -use crate::{t, Config}; +use crate::{Config, t}; #[cfg(test)] mod tests; diff --git a/src/bootstrap/src/core/build_steps/synthetic_targets.rs b/src/bootstrap/src/core/build_steps/synthetic_targets.rs index 04297c01d10aa..477ff9553a480 100644 --- a/src/bootstrap/src/core/build_steps/synthetic_targets.rs +++ b/src/bootstrap/src/core/build_steps/synthetic_targets.rs @@ -7,10 +7,10 @@ //! one of the target specs already defined in this module, or create new ones by adding a new step //! that calls create_synthetic_target. +use crate::Compiler; use crate::core::builder::{Builder, ShouldRun, Step}; use crate::core::config::TargetSelection; use crate::utils::exec::command; -use crate::Compiler; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub(crate) struct MirOptPanicAbortSyntheticTarget { diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 2047345d78a74..870fe6a9f1658 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -15,17 +15,17 @@ use crate::core::build_steps::tool::{self, SourceType, Tool}; use crate::core::build_steps::toolstate::ToolState; use crate::core::build_steps::{compile, dist, llvm}; use crate::core::builder::{ - self, crate_description, Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step, + self, Alias, Builder, Compiler, Kind, RunConfig, ShouldRun, Step, crate_description, }; -use crate::core::config::flags::{get_completion, Subcommand}; use crate::core::config::TargetSelection; -use crate::utils::exec::{command, BootstrapCommand}; +use crate::core::config::flags::{Subcommand, get_completion}; +use crate::utils::exec::{BootstrapCommand, command}; use crate::utils::helpers::{ - self, add_link_lib_path, add_rustdoc_cargo_linker_args, dylib_path, dylib_path_var, - linker_args, linker_flags, t, target_supports_cranelift_backend, up_to_date, LldThreads, + self, LldThreads, add_link_lib_path, add_rustdoc_cargo_linker_args, dylib_path, dylib_path_var, + linker_args, linker_flags, t, target_supports_cranelift_backend, up_to_date, }; use crate::utils::render_tests::{add_flags_and_try_run_tests, try_run_tests}; -use crate::{envify, CLang, DocTests, GitRepo, Mode}; +use crate::{CLang, DocTests, GitRepo, Mode, envify}; const ADB_TEST_DIR: &str = "/data/local/tmp/work"; @@ -1075,12 +1075,8 @@ HELP: to skip test's attempt to check tidiness, pass `--skip src/tools/tidy` to crate::exit!(1); } let all = false; - crate::core::build_steps::format::format( - builder, - !builder.config.cmd.bless(), - all, - &[], - ); + crate::core::build_steps::format::format(builder, !builder.config.cmd.bless(), all, &[ + ]); } builder.info("tidy check"); @@ -1734,8 +1730,23 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the 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); + let cargo_path = if builder.top_stage == 0 { + // If we're using `--stage 0`, we should provide the bootstrap cargo. + builder.initial_cargo.clone() + } else { + // We need to properly build cargo using the suitable stage compiler. + + // HACK: currently tool stages are off-by-one compared to compiler stages, i.e. if + // you give `tool::Cargo` a stage 1 rustc, it will cause stage 2 rustc to be built + // and produce a cargo built with stage 2 rustc. To fix this, we need to chop off + // the compiler stage by 1 to align with expected `./x test run-make --stage N` + // behavior, i.e. we need to pass `N - 1` compiler stage to cargo. See also Miri + // which does a similar hack. + let compiler = builder.compiler(builder.top_stage - 1, compiler.host); + builder.ensure(tool::Cargo { compiler, target: compiler.host }) + }; + + cmd.arg("--cargo-path").arg(cargo_path); } // Avoid depending on rustdoc when we don't need it. @@ -2092,8 +2103,6 @@ NOTE: if you're sure you want to do this, please open an issue as to why. In the cmd.arg("--rustfix-coverage"); } - cmd.env("BOOTSTRAP_CARGO", &builder.initial_cargo); - cmd.arg("--channel").arg(&builder.config.channel); if !builder.config.omit_git_hash { @@ -3440,11 +3449,10 @@ impl Step for CodegenGCC { let compiler = self.compiler; let target = self.target; - builder.ensure(compile::Std::new_with_extra_rust_args( - compiler, - target, - &["-Csymbol-mangling-version=v0", "-Cpanic=abort"], - )); + builder.ensure(compile::Std::new_with_extra_rust_args(compiler, target, &[ + "-Csymbol-mangling-version=v0", + "-Cpanic=abort", + ])); // If we're not doing a full bootstrap but we're testing a stage2 // version of libstd, then what we're actually testing is the libstd diff --git a/src/bootstrap/src/core/build_steps/tool.rs b/src/bootstrap/src/core/build_steps/tool.rs index a437f829ba5a6..64dfe054d9c77 100644 --- a/src/bootstrap/src/core/build_steps/tool.rs +++ b/src/bootstrap/src/core/build_steps/tool.rs @@ -9,9 +9,9 @@ use crate::core::builder; use crate::core::builder::{Builder, Cargo as CargoCommand, RunConfig, ShouldRun, Step}; use crate::core::config::TargetSelection; use crate::utils::channel::GitInfo; -use crate::utils::exec::{command, BootstrapCommand}; +use crate::utils::exec::{BootstrapCommand, command}; use crate::utils::helpers::{add_dylib_path, exe, git, t}; -use crate::{gha, Compiler, Kind, Mode}; +use crate::{Compiler, Kind, Mode, gha}; #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub enum SourceType { diff --git a/src/bootstrap/src/core/build_steps/toolstate.rs b/src/bootstrap/src/core/build_steps/toolstate.rs index b73961062f684..8ac311b249318 100644 --- a/src/bootstrap/src/core/build_steps/toolstate.rs +++ b/src/bootstrap/src/core/build_steps/toolstate.rs @@ -42,15 +42,11 @@ pub enum ToolState { impl fmt::Display for ToolState { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{}", - match self { - ToolState::TestFail => "test-fail", - ToolState::TestPass => "test-pass", - ToolState::BuildFail => "build-fail", - } - ) + write!(f, "{}", match self { + ToolState::TestFail => "test-fail", + ToolState::TestPass => "test-pass", + ToolState::BuildFail => "build-fail", + }) } } diff --git a/src/bootstrap/src/core/builder.rs b/src/bootstrap/src/core/builder.rs index 2124890b94f67..47420f8fe72fb 100644 --- a/src/bootstrap/src/core/builder.rs +++ b/src/bootstrap/src/core/builder.rs @@ -1,4 +1,4 @@ -use std::any::{type_name, Any}; +use std::any::{Any, type_name}; use std::cell::{Cell, RefCell}; use std::collections::BTreeSet; use std::ffi::{OsStr, OsString}; @@ -12,6 +12,7 @@ use std::{env, fs}; use clap::ValueEnum; +pub use crate::Compiler; use crate::core::build_steps::tool::{self, SourceType}; use crate::core::build_steps::{ check, clean, clippy, compile, dist, doc, gcc, install, llvm, run, setup, test, vendor, @@ -19,14 +20,13 @@ use crate::core::build_steps::{ use crate::core::config::flags::{Color, Subcommand}; use crate::core::config::{DryRun, SplitDebuginfo, TargetSelection}; use crate::utils::cache::Cache; -use crate::utils::exec::{command, BootstrapCommand}; +use crate::utils::exec::{BootstrapCommand, command}; use crate::utils::helpers::{ - self, add_dylib_path, add_link_lib_path, check_cfg_arg, exe, libdir, linker_args, linker_flags, - t, LldThreads, + self, LldThreads, add_dylib_path, add_link_lib_path, check_cfg_arg, exe, libdir, linker_args, + linker_flags, t, }; -pub use crate::Compiler; use crate::{ - prepare_behaviour_dump_dir, Build, CLang, Crate, DocTests, GitRepo, Mode, EXTRA_CHECK_CFGS, + Build, CLang, Crate, DocTests, EXTRA_CHECK_CFGS, GitRepo, Mode, prepare_behaviour_dump_dir, }; #[cfg(test)] @@ -314,33 +314,30 @@ const PATH_REMAP: &[(&str, &[&str])] = &[ // actual path is `proc-macro-srv-cli` ("rust-analyzer-proc-macro-srv", &["src/tools/rust-analyzer/crates/proc-macro-srv-cli"]), // Make `x test tests` function the same as `x t tests/*` - ( - "tests", - &[ - // tidy-alphabetical-start - "tests/assembly", - "tests/codegen", - "tests/codegen-units", - "tests/coverage", - "tests/coverage-run-rustdoc", - "tests/crashes", - "tests/debuginfo", - "tests/incremental", - "tests/mir-opt", - "tests/pretty", - "tests/run-make", - "tests/run-pass-valgrind", - "tests/rustdoc", - "tests/rustdoc-gui", - "tests/rustdoc-js", - "tests/rustdoc-js-std", - "tests/rustdoc-json", - "tests/rustdoc-ui", - "tests/ui", - "tests/ui-fulldeps", - // tidy-alphabetical-end - ], - ), + ("tests", &[ + // tidy-alphabetical-start + "tests/assembly", + "tests/codegen", + "tests/codegen-units", + "tests/coverage", + "tests/coverage-run-rustdoc", + "tests/crashes", + "tests/debuginfo", + "tests/incremental", + "tests/mir-opt", + "tests/pretty", + "tests/run-make", + "tests/run-pass-valgrind", + "tests/rustdoc", + "tests/rustdoc-gui", + "tests/rustdoc-js", + "tests/rustdoc-js-std", + "tests/rustdoc-json", + "tests/rustdoc-ui", + "tests/ui", + "tests/ui-fulldeps", + // tidy-alphabetical-end + ]), ]; fn remap_paths(paths: &mut Vec) { @@ -1592,12 +1589,6 @@ impl<'a> Builder<'a> { rustflags.arg(sysroot_str); } - // https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/.E2.9C.94.20link.20new.20library.20into.20stage1.2Frustc - if self.config.llvm_enzyme { - rustflags.arg("-l"); - rustflags.arg("Enzyme-19"); - } - let use_new_symbol_mangling = match self.config.rust_new_symbol_mangling { Some(setting) => { // If an explicit setting is given, use that diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index c554684d5a75b..bd81dc930be05 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1,9 +1,9 @@ use std::thread; use super::*; +use crate::Flags; use crate::core::build_steps::doc::DocumentationFormat; use crate::core::config::Config; -use crate::Flags; fn configure(cmd: &str, host: &[&str], target: &[&str]) -> Config { configure_with_args(&[cmd.to_owned()], host, target) @@ -202,10 +202,10 @@ fn test_exclude_kind() { fn alias_and_path_for_library() { let mut cache = run_build(&["library".into(), "core".into()], configure("build", &["A-A"], &["A-A"])); - assert_eq!( - first(cache.all::()), - &[std!(A => A, stage = 0), std!(A => A, stage = 1)] - ); + assert_eq!(first(cache.all::()), &[ + std!(A => A, stage = 0), + std!(A => A, stage = 1) + ]); let mut cache = run_build(&["library".into(), "core".into()], configure("doc", &["A-A"], &["A-A"])); @@ -216,18 +216,18 @@ mod defaults { use pretty_assertions::assert_eq; use super::{configure, first, run_build}; - use crate::core::builder::*; use crate::Config; + use crate::core::builder::*; #[test] fn build_default() { let mut cache = run_build(&[], configure("build", &["A-A"], &["A-A"])); let a = TargetSelection::from_user("A-A"); - assert_eq!( - first(cache.all::()), - &[std!(A => A, stage = 0), std!(A => A, stage = 1),] - ); + assert_eq!(first(cache.all::()), &[ + std!(A => A, stage = 0), + std!(A => A, stage = 1), + ]); assert!(!cache.all::().is_empty()); // Make sure rustdoc is only built once. assert_eq!( @@ -269,34 +269,25 @@ mod defaults { // there's not really a need for us to build for target A in this case // (since we're producing stage 1 libraries/binaries). But currently // bootstrap is just a bit buggy here; this should be fixed though. - assert_eq!( - first(cache.all::()), - &[ - std!(A => A, stage = 0), - std!(A => A, stage = 1), - std!(A => B, stage = 0), - std!(A => B, stage = 1), - ] - ); - assert_eq!( - first(cache.all::()), - &[ - compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, - compile::Assemble { target_compiler: Compiler { host: b, stage: 1 } }, - ] - ); - assert_eq!( - first(cache.all::()), - &[ - tool::Rustdoc { compiler: Compiler { host: a, stage: 1 } }, - tool::Rustdoc { compiler: Compiler { host: b, stage: 1 } }, - ], - ); - assert_eq!( - first(cache.all::()), - &[rustc!(A => A, stage = 0), rustc!(A => B, stage = 0),] - ); + assert_eq!(first(cache.all::()), &[ + std!(A => A, stage = 0), + std!(A => A, stage = 1), + std!(A => B, stage = 0), + std!(A => B, stage = 1), + ]); + assert_eq!(first(cache.all::()), &[ + compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, + compile::Assemble { target_compiler: Compiler { host: b, stage: 1 } }, + ]); + assert_eq!(first(cache.all::()), &[ + tool::Rustdoc { compiler: Compiler { host: a, stage: 1 } }, + tool::Rustdoc { compiler: Compiler { host: b, stage: 1 } }, + ],); + assert_eq!(first(cache.all::()), &[ + rustc!(A => A, stage = 0), + rustc!(A => B, stage = 0), + ]); } #[test] @@ -310,24 +301,22 @@ mod defaults { // error_index_generator uses stage 0 to share rustdoc artifacts with the // rustdoc tool. assert_eq!(first(cache.all::()), &[doc::ErrorIndex { target: a },]); - assert_eq!( - first(cache.all::()), - &[tool::ErrorIndex { compiler: Compiler { host: a, stage: 0 } }] - ); + assert_eq!(first(cache.all::()), &[tool::ErrorIndex { + compiler: Compiler { host: a, stage: 0 } + }]); // docs should be built with the beta compiler, not with the stage0 artifacts. // recall that rustdoc is off-by-one: `stage` is the compiler rustdoc is _linked_ to, // not the one it was built by. - assert_eq!( - first(cache.all::()), - &[tool::Rustdoc { compiler: Compiler { host: a, stage: 0 } },] - ); + assert_eq!(first(cache.all::()), &[tool::Rustdoc { + compiler: Compiler { host: a, stage: 0 } + },]); } } mod dist { use pretty_assertions::assert_eq; - use super::{first, run_build, Config}; + use super::{Config, first, run_build}; use crate::core::builder::*; fn configure(host: &[&str], target: &[&str]) -> Config { @@ -342,20 +331,18 @@ mod dist { assert_eq!(first(cache.all::()), &[dist::Docs { host: a },]); assert_eq!(first(cache.all::()), &[dist::Mingw { host: a },]); - assert_eq!( - first(cache.all::()), - &[dist::Rustc { compiler: Compiler { host: a, stage: 2 } },] - ); - assert_eq!( - first(cache.all::()), - &[dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a },] - ); + assert_eq!(first(cache.all::()), &[dist::Rustc { + compiler: Compiler { host: a, stage: 2 } + },]); + assert_eq!(first(cache.all::()), &[dist::Std { + compiler: Compiler { host: a, stage: 1 }, + target: a + },]); assert_eq!(first(cache.all::()), &[dist::Src]); // Make sure rustdoc is only built once. - assert_eq!( - first(cache.all::()), - &[tool::Rustdoc { compiler: Compiler { host: a, stage: 2 } },] - ); + assert_eq!(first(cache.all::()), &[tool::Rustdoc { + compiler: Compiler { host: a, stage: 2 } + },]); } #[test] @@ -365,25 +352,19 @@ mod dist { let a = TargetSelection::from_user("A-A"); let b = TargetSelection::from_user("B-B"); - assert_eq!( - first(cache.all::()), - &[dist::Docs { host: a }, dist::Docs { host: b },] - ); - assert_eq!( - first(cache.all::()), - &[dist::Mingw { host: a }, dist::Mingw { host: b },] - ); - assert_eq!( - first(cache.all::()), - &[dist::Rustc { compiler: Compiler { host: a, stage: 2 } },] - ); - assert_eq!( - first(cache.all::()), - &[ - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, - dist::Std { compiler: Compiler { host: a, stage: 2 }, target: b }, - ] - ); + assert_eq!(first(cache.all::()), &[dist::Docs { host: a }, dist::Docs { + host: b + },]); + assert_eq!(first(cache.all::()), &[dist::Mingw { host: a }, dist::Mingw { + host: b + },]); + assert_eq!(first(cache.all::()), &[dist::Rustc { + compiler: Compiler { host: a, stage: 2 } + },]); + assert_eq!(first(cache.all::()), &[ + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, + dist::Std { compiler: Compiler { host: a, stage: 2 }, target: b }, + ]); assert_eq!(first(cache.all::()), &[dist::Src]); } @@ -394,38 +375,27 @@ mod dist { let a = TargetSelection::from_user("A-A"); let b = TargetSelection::from_user("B-B"); - assert_eq!( - first(cache.all::()), - &[dist::Docs { host: a }, dist::Docs { host: b },] - ); - assert_eq!( - first(cache.all::()), - &[dist::Mingw { host: a }, dist::Mingw { host: b },] - ); - assert_eq!( - first(cache.all::()), - &[ - dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, - dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, - ] - ); - assert_eq!( - first(cache.all::()), - &[ - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, - ] - ); - assert_eq!( - first(cache.all::()), - &[ - std!(A => A, stage = 0), - std!(A => A, stage = 1), - std!(A => A, stage = 2), - std!(A => B, stage = 1), - std!(A => B, stage = 2), - ], - ); + assert_eq!(first(cache.all::()), &[dist::Docs { host: a }, dist::Docs { + host: b + },]); + assert_eq!(first(cache.all::()), &[dist::Mingw { host: a }, dist::Mingw { + host: b + },]); + assert_eq!(first(cache.all::()), &[ + dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, + dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, + ]); + assert_eq!(first(cache.all::()), &[ + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, + ]); + assert_eq!(first(cache.all::()), &[ + std!(A => A, stage = 0), + std!(A => A, stage = 1), + std!(A => A, stage = 2), + std!(A => B, stage = 1), + std!(A => B, stage = 2), + ],); assert_eq!(first(cache.all::()), &[dist::Src]); } @@ -438,14 +408,13 @@ mod dist { config.hosts = vec![b]; let mut cache = run_build(&[], config); - assert_eq!( - first(cache.all::()), - &[dist::Rustc { compiler: Compiler { host: b, stage: 2 } },] - ); - assert_eq!( - first(cache.all::()), - &[rustc!(A => A, stage = 0), rustc!(A => B, stage = 1),] - ); + assert_eq!(first(cache.all::()), &[dist::Rustc { + compiler: Compiler { host: b, stage: 2 } + },]); + assert_eq!(first(cache.all::()), &[ + rustc!(A => A, stage = 0), + rustc!(A => B, stage = 1), + ]); } #[test] @@ -456,29 +425,25 @@ mod dist { let b = TargetSelection::from_user("B-B"); let c = TargetSelection::from_user("C-C"); - assert_eq!( - first(cache.all::()), - &[dist::Docs { host: a }, dist::Docs { host: b }, dist::Docs { host: c },] - ); - assert_eq!( - first(cache.all::()), - &[dist::Mingw { host: a }, dist::Mingw { host: b }, dist::Mingw { host: c },] - ); - assert_eq!( - first(cache.all::()), - &[ - dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, - dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, - ] - ); - assert_eq!( - first(cache.all::()), - &[ - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, - dist::Std { compiler: Compiler { host: a, stage: 2 }, target: c }, - ] - ); + assert_eq!(first(cache.all::()), &[ + dist::Docs { host: a }, + dist::Docs { host: b }, + dist::Docs { host: c }, + ]); + assert_eq!(first(cache.all::()), &[ + dist::Mingw { host: a }, + dist::Mingw { host: b }, + dist::Mingw { host: c }, + ]); + assert_eq!(first(cache.all::()), &[ + dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, + dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, + ]); + assert_eq!(first(cache.all::()), &[ + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, + dist::Std { compiler: Compiler { host: a, stage: 2 }, target: c }, + ]); assert_eq!(first(cache.all::()), &[dist::Src]); } @@ -492,10 +457,10 @@ mod dist { assert_eq!(first(cache.all::()), &[dist::Docs { host: c },]); assert_eq!(first(cache.all::()), &[dist::Mingw { host: c },]); - assert_eq!( - first(cache.all::()), - &[dist::Std { compiler: Compiler { host: a, stage: 2 }, target: c },] - ); + assert_eq!(first(cache.all::()), &[dist::Std { + compiler: Compiler { host: a, stage: 2 }, + target: c + },]); } #[test] @@ -505,81 +470,61 @@ mod dist { let a = TargetSelection::from_user("A-A"); let b = TargetSelection::from_user("B-B"); - assert_eq!( - first(cache.all::()), - &[dist::Docs { host: a }, dist::Docs { host: b },] - ); - assert_eq!( - first(cache.all::()), - &[dist::Mingw { host: a }, dist::Mingw { host: b },] - ); - assert_eq!( - first(cache.all::()), - &[ - dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, - dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, - ] - ); - assert_eq!( - first(cache.all::()), - &[ - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, - dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, - ] - ); + assert_eq!(first(cache.all::()), &[dist::Docs { host: a }, dist::Docs { + host: b + },]); + assert_eq!(first(cache.all::()), &[dist::Mingw { host: a }, dist::Mingw { + host: b + },]); + assert_eq!(first(cache.all::()), &[ + dist::Rustc { compiler: Compiler { host: a, stage: 2 } }, + dist::Rustc { compiler: Compiler { host: b, stage: 2 } }, + ]); + assert_eq!(first(cache.all::()), &[ + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: a }, + dist::Std { compiler: Compiler { host: a, stage: 1 }, target: b }, + ]); assert_eq!(first(cache.all::()), &[dist::Src]); - assert_eq!( - first(cache.all::()), - &[ - std!(A => A, stage = 0), - std!(A => A, stage = 1), - std!(A => A, stage = 2), - std!(A => B, stage = 1), - std!(A => B, stage = 2), - ] - ); - assert_eq!( - first(cache.all::()), - &[ - compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 2 } }, - compile::Assemble { target_compiler: Compiler { host: b, stage: 2 } }, - ] - ); + assert_eq!(first(cache.all::()), &[ + std!(A => A, stage = 0), + std!(A => A, stage = 1), + std!(A => A, stage = 2), + std!(A => B, stage = 1), + std!(A => B, stage = 2), + ]); + assert_eq!(first(cache.all::()), &[ + compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 2 } }, + compile::Assemble { target_compiler: Compiler { host: b, stage: 2 } }, + ]); } #[test] fn build_all() { let build = Build::new(configure(&["A-A", "B-B"], &["A-A", "B-B", "C-C"])); let mut builder = Builder::new(&build); - builder.run_step_descriptions( - &Builder::get_step_descriptions(Kind::Build), - &["compiler/rustc".into(), "library".into()], - ); - - assert_eq!( - first(builder.cache.all::()), - &[ - std!(A => A, stage = 0), - std!(A => A, stage = 1), - std!(A => A, stage = 2), - std!(A => B, stage = 1), - std!(A => B, stage = 2), - std!(A => C, stage = 2), - ] - ); + builder.run_step_descriptions(&Builder::get_step_descriptions(Kind::Build), &[ + "compiler/rustc".into(), + "library".into(), + ]); + + assert_eq!(first(builder.cache.all::()), &[ + std!(A => A, stage = 0), + std!(A => A, stage = 1), + std!(A => A, stage = 2), + std!(A => B, stage = 1), + std!(A => B, stage = 2), + std!(A => C, stage = 2), + ]); assert_eq!(builder.cache.all::().len(), 5); - assert_eq!( - first(builder.cache.all::()), - &[ - rustc!(A => A, stage = 0), - rustc!(A => A, stage = 1), - rustc!(A => A, stage = 2), - rustc!(A => B, stage = 1), - rustc!(A => B, stage = 2), - ] - ); + assert_eq!(first(builder.cache.all::()), &[ + rustc!(A => A, stage = 0), + rustc!(A => A, stage = 1), + rustc!(A => A, stage = 2), + rustc!(A => B, stage = 1), + rustc!(A => B, stage = 2), + ]); } #[test] @@ -608,22 +553,20 @@ mod dist { let a = TargetSelection::from_user("A-A"); - assert_eq!( - first(builder.cache.all::()), - &[std!(A => A, stage = 0), std!(A => A, stage = 1), std!(A => C, stage = 2),] - ); - assert_eq!( - first(builder.cache.all::()), - &[ - compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, - compile::Assemble { target_compiler: Compiler { host: a, stage: 2 } }, - ] - ); - assert_eq!( - first(builder.cache.all::()), - &[rustc!(A => A, stage = 0), rustc!(A => A, stage = 1),] - ); + assert_eq!(first(builder.cache.all::()), &[ + std!(A => A, stage = 0), + std!(A => A, stage = 1), + std!(A => C, stage = 2), + ]); + assert_eq!(first(builder.cache.all::()), &[ + compile::Assemble { target_compiler: Compiler { host: a, stage: 0 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 1 } }, + compile::Assemble { target_compiler: Compiler { host: a, stage: 2 } }, + ]); + assert_eq!(first(builder.cache.all::()), &[ + rustc!(A => A, stage = 0), + rustc!(A => A, stage = 1), + ]); } #[test] @@ -652,22 +595,18 @@ mod dist { let host = TargetSelection::from_user("A-A"); - builder.run_step_descriptions( - &[StepDescription::from::(Kind::Test)], - &["library/std".into()], - ); + builder.run_step_descriptions(&[StepDescription::from::(Kind::Test)], &[ + "library/std".into(), + ]); // Ensure we don't build any compiler artifacts. assert!(!builder.cache.contains::()); - assert_eq!( - first(builder.cache.all::()), - &[test::Crate { - compiler: Compiler { host, stage: 0 }, - target: host, - mode: Mode::Std, - crates: vec!["std".to_owned()], - },] - ); + assert_eq!(first(builder.cache.all::()), &[test::Crate { + compiler: Compiler { host, stage: 0 }, + target: host, + mode: Mode::Std, + crates: vec!["std".to_owned()], + },]); } #[test] @@ -686,16 +625,14 @@ mod dist { first(builder.cache.all::()), &[doc::ErrorIndex { target: a },] ); - assert_eq!( - first(builder.cache.all::()), - &[tool::ErrorIndex { compiler: Compiler { host: a, stage: 1 } }] - ); + assert_eq!(first(builder.cache.all::()), &[tool::ErrorIndex { + compiler: Compiler { host: a, stage: 1 } + }]); // This is actually stage 1, but Rustdoc::run swaps out the compiler with // stage minus 1 if --stage is not 0. Very confusing! - assert_eq!( - first(builder.cache.all::()), - &[tool::Rustdoc { compiler: Compiler { host: a, stage: 2 } },] - ); + assert_eq!(first(builder.cache.all::()), &[tool::Rustdoc { + compiler: Compiler { host: a, stage: 2 } + },]); } #[test] @@ -731,10 +668,9 @@ mod dist { first(builder.cache.all::()), &[doc::ErrorIndex { target: a },] ); - assert_eq!( - first(builder.cache.all::()), - &[tool::ErrorIndex { compiler: Compiler { host: a, stage: 1 } }] - ); + assert_eq!(first(builder.cache.all::()), &[tool::ErrorIndex { + compiler: Compiler { host: a, stage: 1 } + }]); // Unfortunately rustdoc is built twice. Once from stage1 for compiletest // (and other things), and once from stage0 for std crates. Ideally it // would only be built once. If someone wants to fix this, it might be @@ -746,13 +682,10 @@ mod dist { // The stage 0 copy is the one downloaded for bootstrapping. It is // (currently) needed to run "cargo test" on the linkchecker, and // should be relatively "free". - assert_eq!( - first(builder.cache.all::()), - &[ - tool::Rustdoc { compiler: Compiler { host: a, stage: 0 } }, - tool::Rustdoc { compiler: Compiler { host: a, stage: 1 } }, - tool::Rustdoc { compiler: Compiler { host: a, stage: 2 } }, - ] - ); + assert_eq!(first(builder.cache.all::()), &[ + tool::Rustdoc { compiler: Compiler { host: a, stage: 0 } }, + tool::Rustdoc { compiler: Compiler { host: a, stage: 1 } }, + tool::Rustdoc { compiler: Compiler { host: a, stage: 2 } }, + ]); } } diff --git a/src/bootstrap/src/core/config/config.rs b/src/bootstrap/src/core/config/config.rs index dcecd7f808445..77e0ece31047f 100644 --- a/src/bootstrap/src/core/config/config.rs +++ b/src/bootstrap/src/core/config/config.rs @@ -7,14 +7,14 @@ use std::cell::{Cell, RefCell}; use std::collections::{HashMap, HashSet}; use std::fmt::{self, Display}; use std::io::IsTerminal; -use std::path::{absolute, Path, PathBuf}; +use std::path::{Path, PathBuf, absolute}; use std::process::Command; use std::str::FromStr; use std::sync::OnceLock; use std::{cmp, env, fs}; use build_helper::exit; -use build_helper::git::{get_closest_merge_commit, output_result, GitConfig}; +use build_helper::git::{GitConfig, get_closest_merge_commit, output_result}; use serde::{Deserialize, Deserializer}; use serde_derive::Deserialize; @@ -22,7 +22,7 @@ use crate::core::build_steps::compile::CODEGEN_BACKEND_PREFIX; use crate::core::build_steps::llvm; pub use crate::core::config::flags::Subcommand; use crate::core::config::flags::{Color, Flags, Warnings}; -use crate::utils::cache::{Interned, INTERNER}; +use crate::utils::cache::{INTERNER, Interned}; use crate::utils::channel::{self, GitInfo}; use crate::utils::helpers::{self, exe, output, t}; @@ -1745,14 +1745,11 @@ impl Config { config.rustc_default_linker = default_linker; config.musl_root = musl_root.map(PathBuf::from); config.save_toolstates = save_toolstates.map(PathBuf::from); - set( - &mut config.deny_warnings, - match flags.warnings { - Warnings::Deny => Some(true), - Warnings::Warn => Some(false), - Warnings::Default => deny_warnings, - }, - ); + set(&mut config.deny_warnings, match flags.warnings { + Warnings::Deny => Some(true), + Warnings::Warn => Some(false), + Warnings::Default => deny_warnings, + }); set(&mut config.backtrace_on_ice, backtrace_on_ice); set(&mut config.rust_verify_llvm_ir, verify_llvm_ir); config.rust_thin_lto_import_instr_limit = thin_lto_import_instr_limit; diff --git a/src/bootstrap/src/core/config/flags.rs b/src/bootstrap/src/core/config/flags.rs index effc5f5091110..87db5f93fb03c 100644 --- a/src/bootstrap/src/core/config/flags.rs +++ b/src/bootstrap/src/core/config/flags.rs @@ -9,7 +9,7 @@ use clap::{CommandFactory, Parser, ValueEnum}; use crate::core::build_steps::setup::Profile; use crate::core::builder::{Builder, Kind}; -use crate::core::config::{target_selection_list, Config, TargetSelectionList}; +use crate::core::config::{Config, TargetSelectionList, target_selection_list}; use crate::{Build, DocTests}; #[derive(Copy, Clone, Default, Debug, ValueEnum)] diff --git a/src/bootstrap/src/core/config/tests.rs b/src/bootstrap/src/core/config/tests.rs index a45e73b5d95ec..e38d4eac051d8 100644 --- a/src/bootstrap/src/core/config/tests.rs +++ b/src/bootstrap/src/core/config/tests.rs @@ -1,5 +1,5 @@ use std::env; -use std::fs::{remove_file, File}; +use std::fs::{File, remove_file}; use std::io::Write; use std::path::Path; diff --git a/src/bootstrap/src/core/download.rs b/src/bootstrap/src/core/download.rs index d8b39ac0b6dac..444b75876f248 100644 --- a/src/bootstrap/src/core/download.rs +++ b/src/bootstrap/src/core/download.rs @@ -10,9 +10,9 @@ use build_helper::ci::CiEnv; use xz2::bufread::XzDecoder; use crate::core::config::BUILDER_CONFIG_FILENAME; -use crate::utils::exec::{command, BootstrapCommand}; +use crate::utils::exec::{BootstrapCommand, command}; use crate::utils::helpers::{check_run, exe, hex_encode, move_file, program_out_of_date}; -use crate::{t, Config}; +use crate::{Config, t}; static SHOULD_FIX_BINS_AND_DYLIBS: OnceLock = OnceLock::new(); diff --git a/src/bootstrap/src/core/metadata.rs b/src/bootstrap/src/core/metadata.rs index d665544f59339..983674d2c6835 100644 --- a/src/bootstrap/src/core/metadata.rs +++ b/src/bootstrap/src/core/metadata.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; use serde_derive::Deserialize; use crate::utils::exec::command; -use crate::{t, Build, Crate}; +use crate::{Build, Crate, t}; /// For more information, see the output of /// diff --git a/src/bootstrap/src/core/sanity.rs b/src/bootstrap/src/core/sanity.rs index e0790c5bf7091..888ba8e2a3f75 100644 --- a/src/bootstrap/src/core/sanity.rs +++ b/src/bootstrap/src/core/sanity.rs @@ -15,6 +15,7 @@ use std::{env, fs}; use build_helper::git::warn_old_master_branch; +use crate::Build; #[cfg(not(feature = "bootstrap-self-test"))] use crate::builder::Builder; use crate::builder::Kind; @@ -22,7 +23,6 @@ use crate::builder::Kind; use crate::core::build_steps::tool; use crate::core::config::Target; use crate::utils::exec::command; -use crate::Build; pub struct Finder { cache: HashMap>, @@ -294,19 +294,19 @@ than building it. } } - for host in &build.hosts { - if !build.config.dry_run() { + if !build.config.dry_run() { + for host in &build.hosts { cmd_finder.must_have(build.cxx(*host).unwrap()); - } - if build.config.llvm_enabled(*host) { - // Externally configured LLVM requires FileCheck to exist - let filecheck = build.llvm_filecheck(build.build); - if !filecheck.starts_with(&build.out) - && !filecheck.exists() - && build.config.codegen_tests - { - panic!("FileCheck executable {filecheck:?} does not exist"); + if build.config.llvm_enabled(*host) { + // Externally configured LLVM requires FileCheck to exist + let filecheck = build.llvm_filecheck(build.build); + if !filecheck.starts_with(&build.out) + && !filecheck.exists() + && build.config.codegen_tests + { + panic!("FileCheck executable {filecheck:?} does not exist"); + } } } } @@ -355,7 +355,8 @@ than building it. // There are three builds of cmake on windows: MSVC, MinGW, and // Cygwin. The Cygwin build does not have generators for Visual // Studio, so detect that here and error. - let out = command("cmake").arg("--help").run_capture_stdout(build).stdout(); + let out = + command("cmake").arg("--help").run_always().run_capture_stdout(build).stdout(); if !out.contains("Visual Studio") { panic!( " diff --git a/src/bootstrap/src/lib.rs b/src/bootstrap/src/lib.rs index 4ed2c72fd552c..7bf5b4e23d29b 100644 --- a/src/bootstrap/src/lib.rs +++ b/src/bootstrap/src/lib.rs @@ -35,8 +35,8 @@ use utils::helpers::hex_encode; use crate::core::builder; use crate::core::builder::{Builder, Kind}; -use crate::core::config::{flags, DryRun, LldMode, LlvmLibunwind, Target, TargetSelection}; -use crate::utils::exec::{command, BehaviorOnFailure, BootstrapCommand, CommandOutput, OutputMode}; +use crate::core::config::{DryRun, LldMode, LlvmLibunwind, Target, TargetSelection, flags}; +use crate::utils::exec::{BehaviorOnFailure, BootstrapCommand, CommandOutput, OutputMode, command}; use crate::utils::helpers::{ self, dir_is_empty, exe, libdir, mtime, output, set_file_times, symlink_dir, }; @@ -45,11 +45,11 @@ mod core; mod utils; pub use core::builder::PathSet; -pub use core::config::flags::{Flags, Subcommand}; pub use core::config::Config; +pub use core::config::flags::{Flags, Subcommand}; pub use utils::change_tracker::{ - find_recent_config_change_ids, human_readable_changes, CONFIG_CHANGE_HISTORY, + CONFIG_CHANGE_HISTORY, find_recent_config_change_ids, human_readable_changes, }; const LLVM_TOOLS: &[&str] = &[ @@ -596,15 +596,6 @@ impl Build { _ => (), } - { - let builder = builder::Builder::new(self); - if let Some(path) = builder.paths.first() { - if path == Path::new("nonexistent/path/to/trigger/cargo/metadata") { - return; - } - } - } - if !self.config.dry_run() { { // We first do a dry-run. This is a sanity-check to ensure that diff --git a/src/bootstrap/src/utils/cc_detect.rs b/src/bootstrap/src/utils/cc_detect.rs index c39415e7c1865..0df0046945220 100644 --- a/src/bootstrap/src/utils/cc_detect.rs +++ b/src/bootstrap/src/utils/cc_detect.rs @@ -26,7 +26,7 @@ use std::path::{Path, PathBuf}; use std::{env, iter}; use crate::core::config::TargetSelection; -use crate::utils::exec::{command, BootstrapCommand}; +use crate::utils::exec::{BootstrapCommand, command}; use crate::{Build, CLang, GitRepo}; // The `cc` crate doesn't provide a way to obtain a path to the detected archiver, diff --git a/src/bootstrap/src/utils/change_tracker/tests.rs b/src/bootstrap/src/utils/change_tracker/tests.rs index d2bfc07d1727b..730b65b4879c9 100644 --- a/src/bootstrap/src/utils/change_tracker/tests.rs +++ b/src/bootstrap/src/utils/change_tracker/tests.rs @@ -1,4 +1,4 @@ -use crate::{find_recent_config_change_ids, CONFIG_CHANGE_HISTORY}; +use crate::{CONFIG_CHANGE_HISTORY, find_recent_config_change_ids}; #[test] fn test_find_recent_config_change_ids() { diff --git a/src/bootstrap/src/utils/channel.rs b/src/bootstrap/src/utils/channel.rs index 3ae512ef7f1c2..c361abb9c9e13 100644 --- a/src/bootstrap/src/utils/channel.rs +++ b/src/bootstrap/src/utils/channel.rs @@ -9,8 +9,8 @@ use std::fs; use std::path::Path; use super::helpers; -use crate::utils::helpers::{output, t}; use crate::Build; +use crate::utils::helpers::{output, t}; #[derive(Clone, Default)] pub enum GitInfo { diff --git a/src/bootstrap/src/utils/helpers.rs b/src/bootstrap/src/utils/helpers.rs index 85246e390bc4f..2519ace92b9e0 100644 --- a/src/bootstrap/src/utils/helpers.rs +++ b/src/bootstrap/src/utils/helpers.rs @@ -12,10 +12,10 @@ use std::{env, fs, io, str}; use build_helper::util::fail; +use crate::LldMode; use crate::core::builder::Builder; use crate::core::config::{Config, TargetSelection}; pub use crate::utils::shared_helpers::{dylib_path, dylib_path_var}; -use crate::LldMode; #[cfg(test)] mod tests; @@ -46,7 +46,7 @@ macro_rules! t { } pub use t; -use crate::utils::exec::{command, BootstrapCommand}; +use crate::utils::exec::{BootstrapCommand, command}; pub fn exe(name: &str, target: TargetSelection) -> String { crate::utils::shared_helpers::exe(name, &target.triple) diff --git a/src/bootstrap/src/utils/helpers/tests.rs b/src/bootstrap/src/utils/helpers/tests.rs index 86016a91e49b1..f6fe6f47aa4fa 100644 --- a/src/bootstrap/src/utils/helpers/tests.rs +++ b/src/bootstrap/src/utils/helpers/tests.rs @@ -1,4 +1,4 @@ -use std::fs::{self, remove_file, File}; +use std::fs::{self, File, remove_file}; use std::io::Write; use std::path::PathBuf; diff --git a/src/bootstrap/src/utils/job.rs b/src/bootstrap/src/utils/job.rs index 4012f5167ff73..c5e892450c4c5 100644 --- a/src/bootstrap/src/utils/job.rs +++ b/src/bootstrap/src/utils/job.rs @@ -43,19 +43,19 @@ mod for_windows { use std::ffi::c_void; use std::{env, io, mem}; - use windows::core::PCWSTR; - use windows::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE}; + use windows::Win32::Foundation::{CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE}; use windows::Win32::System::Diagnostics::Debug::{ - SetErrorMode, SEM_NOGPFAULTERRORBOX, THREAD_ERROR_MODE, + SEM_NOGPFAULTERRORBOX, SetErrorMode, THREAD_ERROR_MODE, }; use windows::Win32::System::JobObjects::{ - AssignProcessToJobObject, CreateJobObjectW, JobObjectExtendedLimitInformation, - SetInformationJobObject, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, - JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOB_OBJECT_LIMIT_PRIORITY_CLASS, + AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, + JOB_OBJECT_LIMIT_PRIORITY_CLASS, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JobObjectExtendedLimitInformation, SetInformationJobObject, }; use windows::Win32::System::Threading::{ - GetCurrentProcess, OpenProcess, BELOW_NORMAL_PRIORITY_CLASS, PROCESS_DUP_HANDLE, + BELOW_NORMAL_PRIORITY_CLASS, GetCurrentProcess, OpenProcess, PROCESS_DUP_HANDLE, }; + use windows::core::PCWSTR; use crate::Build; diff --git a/src/bootstrap/src/utils/metrics.rs b/src/bootstrap/src/utils/metrics.rs index e9acb93363e76..3b31fa36e889e 100644 --- a/src/bootstrap/src/utils/metrics.rs +++ b/src/bootstrap/src/utils/metrics.rs @@ -15,9 +15,9 @@ use build_helper::metrics::{ }; use sysinfo::{CpuRefreshKind, RefreshKind, System}; +use crate::Build; use crate::core::builder::{Builder, Step}; use crate::utils::helpers::t; -use crate::Build; // Update this number whenever a breaking change is made to the build metrics. // diff --git a/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/src/main.rs b/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/src/main.rs index d75ee147799a7..89e4393cb5c7b 100644 --- a/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/src/main.rs +++ b/src/ci/docker/host-x86_64/test-various/uefi_qemu_test/src/main.rs @@ -6,7 +6,7 @@ use core::{panic, ptr}; -use r_efi::efi::{Char16, Handle, Status, SystemTable, RESET_SHUTDOWN}; +use r_efi::efi::{Char16, Handle, RESET_SHUTDOWN, Status, SystemTable}; #[panic_handler] fn panic_handler(_info: &panic::PanicInfo) -> ! { diff --git a/src/doc/book b/src/doc/book index e7d217be2a75e..99cf75a5414fa 160000 --- a/src/doc/book +++ b/src/doc/book @@ -1 +1 @@ -Subproject commit e7d217be2a75ef1753f0988d6ccaba4d7e376259 +Subproject commit 99cf75a5414fa8adbe3974bd0836661ca901708f diff --git a/src/doc/edition-guide b/src/doc/edition-guide index b3ca7ade0f87d..c7ebae25cb480 160000 --- a/src/doc/edition-guide +++ b/src/doc/edition-guide @@ -1 +1 @@ -Subproject commit b3ca7ade0f87d7e3fb538776defc5b2cc4188172 +Subproject commit c7ebae25cb4801a31b6f05353f6d85bfa6feedd1 diff --git a/src/doc/reference b/src/doc/reference index 687faf9958c52..24fb2687cdbc5 160000 --- a/src/doc/reference +++ b/src/doc/reference @@ -1 +1 @@ -Subproject commit 687faf9958c52116d003b41dfd29cc1cf44f5311 +Subproject commit 24fb2687cdbc54fa18ae4acf5d879cfceca77b2c diff --git a/src/doc/rustc-dev-guide b/src/doc/rustc-dev-guide index 0ed9229f5b6f7..555f3de2fa0d6 160000 --- a/src/doc/rustc-dev-guide +++ b/src/doc/rustc-dev-guide @@ -1 +1 @@ -Subproject commit 0ed9229f5b6f7824b333beabd7e3d5ba4b9bd971 +Subproject commit 555f3de2fa0d61c4294b74d245f1cbad6fcbf589 diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 827a7065f3e07..999eb9b8a7c60 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -138,7 +138,6 @@ target | std | notes [`aarch64-apple-ios`](platform-support/apple-ios.md) | ✓ | ARM64 iOS [`aarch64-apple-ios-macabi`](platform-support/apple-ios-macabi.md) | ✓ | Mac Catalyst on ARM64 [`aarch64-apple-ios-sim`](platform-support/apple-ios.md) | ✓ | Apple iOS Simulator on ARM64 -`aarch64-fuchsia` | ✓ | Alias for `aarch64-unknown-fuchsia` [`aarch64-unknown-fuchsia`](platform-support/fuchsia.md) | ✓ | ARM64 Fuchsia [`aarch64-linux-android`](platform-support/android.md) | ✓ | ARM64 Android [`aarch64-pc-windows-gnullvm`](platform-support/pc-windows-gnullvm.md) | ✓ | ARM64 MinGW (Windows 10+), LLVM ABI @@ -199,7 +198,6 @@ target | std | notes [`x86_64-apple-ios`](platform-support/apple-ios.md) | ✓ | 64-bit x86 iOS [`x86_64-apple-ios-macabi`](platform-support/apple-ios-macabi.md) | ✓ | Mac Catalyst on x86_64 [`x86_64-fortanix-unknown-sgx`](platform-support/x86_64-fortanix-unknown-sgx.md) | ✓ | [Fortanix ABI] for 64-bit Intel SGX -`x86_64-fuchsia` | ✓ | Alias for `x86_64-unknown-fuchsia` [`x86_64-unknown-fuchsia`](platform-support/fuchsia.md) | ✓ | 64-bit x86 Fuchsia [`x86_64-linux-android`](platform-support/android.md) | ✓ | 64-bit x86 Android `x86_64-pc-solaris` | ✓ | 64-bit Solaris 11, illumos @@ -315,6 +313,7 @@ target | std | host | notes `i686-uwp-windows-msvc` | ✓ | | [^x86_32-floats-return-ABI] [`i686-win7-windows-msvc`](platform-support/win7-windows-msvc.md) | ✓ | | 32-bit Windows 7 support [^x86_32-floats-return-ABI] [`i686-wrs-vxworks`](platform-support/vxworks.md) | ✓ | | [^x86_32-floats-return-ABI] +[`loongarch64-unknown-linux-ohos`](platform-support/openharmony.md) | ✓ | | LoongArch64 OpenHarmony [`m68k-unknown-linux-gnu`](platform-support/m68k-unknown-linux-gnu.md) | ? | | Motorola 680x0 Linux `mips-unknown-linux-gnu` | ✓ | ✓ | MIPS Linux (kernel 4.4, glibc 2.23) `mips-unknown-linux-musl` | ✓ | | MIPS Linux with musl 1.2.3 diff --git a/src/doc/rustc/src/platform-support/openharmony.md b/src/doc/rustc/src/platform-support/openharmony.md index b2ddbfdfa2918..1632f44aeecc0 100644 --- a/src/doc/rustc/src/platform-support/openharmony.md +++ b/src/doc/rustc/src/platform-support/openharmony.md @@ -2,6 +2,14 @@ **Tier: 2** +* aarch64-unknown-linux-ohos +* armv7-unknown-linux-ohos +* x86_64-unknown-linux-ohos + +**Tier: 3** + +* loongarch64-unknown-linux-ohos + Targets for the [OpenHarmony](https://gitee.com/openharmony/docs/) operating system. diff --git a/src/doc/unstable-book/src/compiler-flags/branch-protection.md b/src/doc/unstable-book/src/compiler-flags/branch-protection.md index ca5664835f26f..9276220f4473a 100644 --- a/src/doc/unstable-book/src/compiler-flags/branch-protection.md +++ b/src/doc/unstable-book/src/compiler-flags/branch-protection.md @@ -1,5 +1,9 @@ # `branch-protection` +The tracking issue for this feature is: [#113369](https://github.com/rust-lang/rust/issues/113369). + +------------------------ + This option lets you enable branch authentication instructions on AArch64. This option is only accepted when targeting AArch64 architectures. It takes some combination of the following values, separated by a `,`. diff --git a/src/doc/unstable-book/src/language-features/more-qualified-paths.md b/src/doc/unstable-book/src/language-features/more-qualified-paths.md index 857af577a6cfe..1a31ba8e14f9f 100644 --- a/src/doc/unstable-book/src/language-features/more-qualified-paths.md +++ b/src/doc/unstable-book/src/language-features/more-qualified-paths.md @@ -3,6 +3,10 @@ The `more_qualified_paths` feature can be used in order to enable the use of qualified paths in patterns. +The tracking issue for this feature is: [#86935](https://github.com/rust-lang/rust/issues/86935). + +------------------------ + ## Example ```rust diff --git a/src/doc/unstable-book/src/language-features/postfix-match.md b/src/doc/unstable-book/src/language-features/postfix-match.md index cd6b6a7442c5a..c931a85b14146 100644 --- a/src/doc/unstable-book/src/language-features/postfix-match.md +++ b/src/doc/unstable-book/src/language-features/postfix-match.md @@ -3,6 +3,10 @@ `postfix-match` adds the feature for matching upon values postfix the expressions that generate the values. +The tracking issue for this feature is: [#121618](https://github.com/rust-lang/rust/issues/121618). + +------------------------ + ```rust,edition2021 #![feature(postfix_match)] diff --git a/src/etc/test-float-parse/src/gen/fuzz.rs b/src/etc/test-float-parse/src/gen/fuzz.rs index 213bcfc64af0c..0c63e8aae26ea 100644 --- a/src/etc/test-float-parse/src/gen/fuzz.rs +++ b/src/etc/test-float-parse/src/gen/fuzz.rs @@ -1,14 +1,14 @@ -use std::any::{type_name, TypeId}; +use std::any::{TypeId, type_name}; use std::collections::BTreeMap; use std::fmt::Write; use std::marker::PhantomData; use std::ops::Range; use std::sync::Mutex; -use rand::distributions::{Distribution, Standard}; use rand::Rng; -use rand_chacha::rand_core::SeedableRng; +use rand::distributions::{Distribution, Standard}; use rand_chacha::ChaCha8Rng; +use rand_chacha::rand_core::SeedableRng; use crate::{Float, Generator, Int, SEED}; diff --git a/src/etc/test-float-parse/src/lib.rs b/src/etc/test-float-parse/src/lib.rs index f36e3928d26c0..71b1aa0667109 100644 --- a/src/etc/test-float-parse/src/lib.rs +++ b/src/etc/test-float-parse/src/lib.rs @@ -2,12 +2,12 @@ mod traits; mod ui; mod validate; -use std::any::{type_name, TypeId}; +use std::any::{TypeId, type_name}; use std::cmp::min; use std::ops::RangeInclusive; use std::process::ExitCode; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{mpsc, OnceLock}; +use std::sync::{OnceLock, mpsc}; use std::{fmt, time}; use indicatif::{MultiProgress, ProgressBar}; diff --git a/src/etc/test-float-parse/src/traits.rs b/src/etc/test-float-parse/src/traits.rs index dc009ea235f95..f5333d63b3693 100644 --- a/src/etc/test-float-parse/src/traits.rs +++ b/src/etc/test-float-parse/src/traits.rs @@ -3,8 +3,8 @@ use std::str::FromStr; use std::{fmt, ops}; -use num::bigint::ToBigInt; use num::Integer; +use num::bigint::ToBigInt; use crate::validate::Constants; diff --git a/src/librustdoc/clean/auto_trait.rs b/src/librustdoc/clean/auto_trait.rs index 7e3881c798b53..08c88fc950d7f 100644 --- a/src/librustdoc/clean/auto_trait.rs +++ b/src/librustdoc/clean/auto_trait.rs @@ -4,14 +4,14 @@ use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData}; use rustc_middle::bug; use rustc_middle::ty::{self, Region, Ty}; use rustc_span::def_id::DefId; -use rustc_span::symbol::{kw, Symbol}; +use rustc_span::symbol::{Symbol, kw}; use rustc_trait_selection::traits::auto_trait::{self, RegionTarget}; use thin_vec::ThinVec; use tracing::{debug, instrument}; use crate::clean::{ - self, clean_generic_param_def, clean_middle_ty, clean_predicate, - clean_trait_ref_with_constraints, clean_ty_generics, simplify, Lifetime, + self, Lifetime, clean_generic_param_def, clean_middle_ty, clean_predicate, + clean_trait_ref_with_constraints, clean_ty_generics, simplify, }; use crate::core::DocContext; diff --git a/src/librustdoc/clean/blanket_impl.rs b/src/librustdoc/clean/blanket_impl.rs index 95f6616cec345..3682129488598 100644 --- a/src/librustdoc/clean/blanket_impl.rs +++ b/src/librustdoc/clean/blanket_impl.rs @@ -2,8 +2,8 @@ use rustc_hir as hir; use rustc_infer::infer::{DefineOpaqueTypes, InferOk, TyCtxtInferExt}; use rustc_infer::traits; use rustc_middle::ty::{self, Upcast}; -use rustc_span::def_id::DefId; use rustc_span::DUMMY_SP; +use rustc_span::def_id::DefId; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; use thin_vec::ThinVec; use tracing::{debug, instrument, trace}; diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs index fb9754c7ffcb0..267392190858c 100644 --- a/src/librustdoc/clean/cfg.rs +++ b/src/librustdoc/clean/cfg.rs @@ -10,8 +10,8 @@ use rustc_ast::{LitKind, MetaItem, MetaItemKind, NestedMetaItem}; use rustc_data_structures::fx::FxHashSet; use rustc_feature::Features; use rustc_session::parse::ParseSess; -use rustc_span::symbol::{sym, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Symbol, sym}; use crate::html::escape::Escape; diff --git a/src/librustdoc/clean/cfg/tests.rs b/src/librustdoc/clean/cfg/tests.rs index a9b3abadb2044..0ab655103e293 100644 --- a/src/librustdoc/clean/cfg/tests.rs +++ b/src/librustdoc/clean/cfg/tests.rs @@ -1,6 +1,6 @@ use rustc_ast::{MetaItemLit, Path, Safety, StrStyle}; -use rustc_span::symbol::{kw, Ident}; -use rustc_span::{create_default_session_globals_then, DUMMY_SP}; +use rustc_span::symbol::{Ident, kw}; +use rustc_span::{DUMMY_SP, create_default_session_globals_then}; use thin_vec::thin_vec; use super::*; @@ -267,13 +267,10 @@ fn test_parse_ok() { let mi = dummy_meta_item_list!(not, [a]); assert_eq!(Cfg::parse(&mi), Ok(!word_cfg("a"))); - let mi = dummy_meta_item_list!( - not, - [dummy_meta_item_list!( - any, - [dummy_meta_item_word("a"), dummy_meta_item_list!(all, [b, c]),] - ),] - ); + let mi = dummy_meta_item_list!(not, [dummy_meta_item_list!(any, [ + dummy_meta_item_word("a"), + dummy_meta_item_list!(all, [b, c]), + ]),]); assert_eq!(Cfg::parse(&mi), Ok(!(word_cfg("a") | (word_cfg("b") & word_cfg("c"))))); let mi = dummy_meta_item_list!(all, [a, b, c]); @@ -296,16 +293,18 @@ fn test_parse_err() { let mi = dummy_meta_item_list!(foo, []); assert!(Cfg::parse(&mi).is_err()); - let mi = dummy_meta_item_list!( - all, - [dummy_meta_item_list!(foo, []), dummy_meta_item_word("b"),] - ); + let mi = + dummy_meta_item_list!( + all, + [dummy_meta_item_list!(foo, []), dummy_meta_item_word("b"),] + ); assert!(Cfg::parse(&mi).is_err()); - let mi = dummy_meta_item_list!( - any, - [dummy_meta_item_word("a"), dummy_meta_item_list!(foo, []),] - ); + let mi = + dummy_meta_item_list!( + any, + [dummy_meta_item_word("a"), dummy_meta_item_list!(foo, []),] + ); assert!(Cfg::parse(&mi).is_err()); let mi = dummy_meta_item_list!(not, [dummy_meta_item_list!(foo, []),]); diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 8383012885f96..b7d6b3dda72b4 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -4,25 +4,25 @@ use std::iter::once; use std::sync::Arc; use rustc_data_structures::fx::FxHashSet; +use rustc_hir::Mutability; use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, DefIdSet, LocalDefId, LocalModDefId}; -use rustc_hir::Mutability; use rustc_metadata::creader::{CStore, LoadedMacro}; use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::hygiene::MacroKind; -use rustc_span::symbol::{sym, Symbol}; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Symbol, sym}; +use thin_vec::{ThinVec, thin_vec}; use tracing::{debug, trace}; use {rustc_ast as ast, rustc_hir as hir}; use super::Item; use crate::clean::{ - self, clean_bound_vars, clean_generics, clean_impl_item, clean_middle_assoc_item, - clean_middle_field, clean_middle_ty, clean_poly_fn_sig, clean_trait_ref_with_constraints, - clean_ty, clean_ty_alias_inner_type, clean_ty_generics, clean_variant_def, utils, Attributes, - AttributesExt, ImplKind, ItemId, Type, + self, Attributes, AttributesExt, ImplKind, ItemId, Type, clean_bound_vars, clean_generics, + clean_impl_item, clean_middle_assoc_item, clean_middle_field, clean_middle_ty, + clean_poly_fn_sig, clean_trait_ref_with_constraints, clean_ty, clean_ty_alias_inner_type, + clean_ty_generics, clean_variant_def, utils, }; use crate::core::DocContext; use crate::formats::item_type::ItemType; @@ -373,7 +373,7 @@ pub(crate) fn build_impls( let tcx = cx.tcx; // for each implementation of an item represented by `did`, build the clean::Item for that impl - for &did in tcx.inherent_impls(did).into_iter().flatten() { + for &did in tcx.inherent_impls(did).into_iter() { cx.with_param_env(did, |cx| { build_impl(cx, did, attrs, ret); }); @@ -388,7 +388,7 @@ pub(crate) fn build_impls( if tcx.has_attr(did, sym::rustc_has_incoherent_inherent_impls) { let type_ = if tcx.is_trait(did) { SimplifiedType::Trait(did) } else { SimplifiedType::Adt(did) }; - for &did in tcx.incoherent_impls(type_).into_iter().flatten() { + for &did in tcx.incoherent_impls(type_).into_iter() { cx.with_param_env(did, |cx| { build_impl(cx, did, attrs, ret); }); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index e47ae7df77fb6..3d845cf878f4a 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -38,18 +38,18 @@ use rustc_ast::token::{Token, TokenKind}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet, IndexEntry}; use rustc_errors::codes::*; -use rustc_errors::{struct_span_code_err, FatalError}; -use rustc_hir::def::{CtorKind, DefKind, Res}; -use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId, LOCAL_CRATE}; +use rustc_errors::{FatalError, struct_span_code_err}; use rustc_hir::PredicateOrigin; +use rustc_hir::def::{CtorKind, DefKind, Res}; +use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LOCAL_CRATE, LocalDefId}; use rustc_hir_analysis::lower_ty; use rustc_middle::metadata::Reexport; use rustc_middle::middle::resolve_bound_vars as rbv; use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt}; use rustc_middle::{bug, span_bug}; -use rustc_span::hygiene::{AstPass, MacroKind}; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::ExpnKind; +use rustc_span::hygiene::{AstPass, MacroKind}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; use rustc_trait_selection::traits::wf::object_region_bounds; use thin_vec::ThinVec; use tracing::{debug, instrument}; @@ -536,18 +536,14 @@ fn clean_generic_param_def( } else { None }; - ( - def.name, - GenericParamDefKind::Type { - bounds: ThinVec::new(), // These are filled in from the where-clauses. - default: default.map(Box::new), - synthetic, - }, - ) + (def.name, GenericParamDefKind::Type { + bounds: ThinVec::new(), // These are filled in from the where-clauses. + default: default.map(Box::new), + synthetic, + }) } - ty::GenericParamDefKind::Const { has_default, synthetic, is_host_effect: _ } => ( - def.name, - GenericParamDefKind::Const { + ty::GenericParamDefKind::Const { has_default, synthetic, is_host_effect: _ } => { + (def.name, GenericParamDefKind::Const { ty: Box::new(clean_middle_ty( ty::Binder::dummy( cx.tcx @@ -569,8 +565,8 @@ fn clean_generic_param_def( None }, synthetic, - }, - ), + }) + } }; GenericParamDef { name, def_id: def.def_id, kind } @@ -615,25 +611,21 @@ fn clean_generic_param<'tcx>( } else { ThinVec::new() }; - ( - param.name.ident().name, - GenericParamDefKind::Type { - bounds, - default: default.map(|t| clean_ty(t, cx)).map(Box::new), - synthetic, - }, - ) + (param.name.ident().name, GenericParamDefKind::Type { + bounds, + default: default.map(|t| clean_ty(t, cx)).map(Box::new), + synthetic, + }) } - hir::GenericParamKind::Const { ty, default, synthetic, is_host_effect: _ } => ( - param.name.ident().name, - GenericParamDefKind::Const { + hir::GenericParamKind::Const { ty, default, synthetic, is_host_effect: _ } => { + (param.name.ident().name, GenericParamDefKind::Const { ty: Box::new(clean_ty(ty, cx)), default: default.map(|ct| { Box::new(ty::Const::from_const_arg(cx.tcx, ct, ty::FeedConstTy::No).to_string()) }), synthetic, - }, - ), + }) + } }; GenericParamDef { name, def_id: param.def_id.to_def_id(), kind } @@ -653,10 +645,9 @@ fn is_impl_trait(param: &hir::GenericParam<'_>) -> bool { /// /// See `lifetime_to_generic_param` in `rustc_ast_lowering` for more information. fn is_elided_lifetime(param: &hir::GenericParam<'_>) -> bool { - matches!( - param.kind, - hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Elided(_) } - ) + matches!(param.kind, hir::GenericParamKind::Lifetime { + kind: hir::LifetimeParamKind::Elided(_) + }) } pub(crate) fn clean_generics<'tcx>( @@ -1055,10 +1046,11 @@ fn clean_fn_decl_legacy_const_generics(func: &mut Function, attrs: &[ast::Attrib .. } = param { - func.decl - .inputs - .values - .insert(a.get() as _, Argument { name, type_: *ty, is_const: true }); + func.decl.inputs.values.insert(a.get() as _, Argument { + name, + type_: *ty, + is_const: true, + }); } else { panic!("unexpected non const in position {pos}"); } @@ -1402,15 +1394,12 @@ pub(crate) fn clean_middle_assoc_item(assoc_item: &ty::AssocItem, cx: &mut DocCo let bounds = tcx.explicit_item_bounds(assoc_item.def_id).iter_identity_copied(); predicates = tcx.arena.alloc_from_iter(bounds.chain(predicates.iter().copied())); } - let mut generics = clean_ty_generics( - cx, - tcx.generics_of(assoc_item.def_id), - ty::GenericPredicates { + let mut generics = + clean_ty_generics(cx, tcx.generics_of(assoc_item.def_id), ty::GenericPredicates { parent: None, predicates, effects_min_tys: ty::List::empty(), - }, - ); + }); simplify::move_bounds_to_generic_parameters(&mut generics); if let ty::TraitContainer = assoc_item.container { diff --git a/src/librustdoc/clean/render_macro_matchers.rs b/src/librustdoc/clean/render_macro_matchers.rs index 995919f73f83b..d39ecf83ac01c 100644 --- a/src/librustdoc/clean/render_macro_matchers.rs +++ b/src/librustdoc/clean/render_macro_matchers.rs @@ -1,11 +1,11 @@ use rustc_ast::token::{self, BinOpToken, Delimiter, IdentIsRaw}; use rustc_ast::tokenstream::{TokenStream, TokenTree}; -use rustc_ast_pretty::pprust::state::State as Printer; use rustc_ast_pretty::pprust::PrintState; +use rustc_ast_pretty::pprust::state::State as Printer; use rustc_middle::ty::TyCtxt; use rustc_session::parse::ParseSess; -use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::Span; +use rustc_span::symbol::{Ident, Symbol, kw}; /// Render a macro matcher in a format suitable for displaying to the user /// as part of an item declaration. diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 383efe568ae09..bc6b5a7d3e319 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -12,7 +12,7 @@ use rustc_attr::{ConstStability, Deprecation, Stability, StabilityLevel, StableS use rustc_const_eval::const_eval::is_unstable_const_fn; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::def::{CtorKind, DefKind, Res}; -use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId}; use rustc_hir::lang_items::LangItem; use rustc_hir::{BodyId, Mutability}; use rustc_hir_analysis::check::intrinsic::intrinsic_operation_unsafety; @@ -22,12 +22,12 @@ use rustc_middle::span_bug; use rustc_middle::ty::fast_reject::SimplifiedType; use rustc_middle::ty::{self, TyCtxt, Visibility}; use rustc_resolve::rustdoc::{ - add_doc_fragment, attrs_to_doc_fragments, inner_docs, span_of_fragments, DocFragment, + DocFragment, add_doc_fragment, attrs_to_doc_fragments, inner_docs, span_of_fragments, }; use rustc_session::Session; use rustc_span::hygiene::MacroKind; -use rustc_span::symbol::{kw, sym, Ident, Symbol}; -use rustc_span::{FileName, Loc, DUMMY_SP}; +use rustc_span::symbol::{Ident, Symbol, kw, sym}; +use rustc_span::{DUMMY_SP, FileName, Loc}; use rustc_target::abi::VariantIdx; use rustc_target::spec::abi::Abi; use thin_vec::ThinVec; @@ -384,7 +384,45 @@ fn is_field_vis_inherited(tcx: TyCtxt<'_>, def_id: DefId) -> bool { impl Item { pub(crate) fn stability(&self, tcx: TyCtxt<'_>) -> Option { - self.def_id().and_then(|did| tcx.lookup_stability(did)) + let (mut def_id, mut stability) = if let Some(inlined) = self.inline_stmt_id { + let inlined_def_id = inlined.to_def_id(); + if let Some(stability) = tcx.lookup_stability(inlined_def_id) { + (inlined_def_id, stability) + } else { + // For re-exports into crates without `staged_api`, reuse the original stability. + // This is necessary, because we always want to mark unstable items. + let def_id = self.def_id()?; + return tcx.lookup_stability(def_id); + } + } else { + let def_id = self.def_id()?; + let stability = tcx.lookup_stability(def_id)?; + (def_id, stability) + }; + + let StabilityLevel::Stable { mut since, allowed_through_unstable_modules: false } = + stability.level + else { + return Some(stability); + }; + + // If any of the item's ancestors was stabilized later or is still unstable, + // then report the ancestor's stability instead. + while let Some(parent_def_id) = tcx.opt_parent(def_id) { + if let Some(parent_stability) = tcx.lookup_stability(parent_def_id) { + match parent_stability.level { + StabilityLevel::Unstable { .. } => return Some(parent_stability), + StabilityLevel::Stable { since: parent_since, .. } => { + if parent_since > since { + stability = parent_stability; + since = parent_since; + } + } + } + } + def_id = parent_def_id; + } + Some(stability) } pub(crate) fn const_stability(&self, tcx: TyCtxt<'_>) -> Option { @@ -1064,10 +1102,14 @@ impl AttributesExt for [ast::Attribute] { } impl AttributesExt for [(Cow<'_, ast::Attribute>, Option)] { - type AttributeIterator<'a> = impl Iterator + 'a - where Self: 'a; - type Attributes<'a> = impl Iterator + 'a - where Self: 'a; + type AttributeIterator<'a> + = impl Iterator + 'a + where + Self: 'a; + type Attributes<'a> + = impl Iterator + 'a + where + Self: 'a; fn lists(&self, name: Symbol) -> Self::AttributeIterator<'_> { AttributesExt::iter(self) @@ -1809,8 +1851,8 @@ impl PrimitiveType { } pub(crate) fn simplified_types() -> &'static SimplifiedTypes { - use ty::{FloatTy, IntTy, UintTy}; use PrimitiveType::*; + use ty::{FloatTy, IntTy, UintTy}; static CELL: OnceCell = OnceCell::new(); let single = |x| iter::once(x).collect(); @@ -1859,7 +1901,7 @@ impl PrimitiveType { .get(self) .into_iter() .flatten() - .flat_map(move |&simp| tcx.incoherent_impls(simp).into_iter().flatten()) + .flat_map(move |&simp| tcx.incoherent_impls(simp).into_iter()) .copied() } @@ -1867,7 +1909,7 @@ impl PrimitiveType { Self::simplified_types() .values() .flatten() - .flat_map(move |&simp| tcx.incoherent_impls(simp).into_iter().flatten()) + .flat_map(move |&simp| tcx.incoherent_impls(simp).into_iter()) .copied() } diff --git a/src/librustdoc/clean/types/tests.rs b/src/librustdoc/clean/types/tests.rs index ddf6a11ec4e65..7ff5026150b16 100644 --- a/src/librustdoc/clean/types/tests.rs +++ b/src/librustdoc/clean/types/tests.rs @@ -1,4 +1,4 @@ -use rustc_resolve::rustdoc::{unindent_doc_fragments, DocFragmentKind}; +use rustc_resolve::rustdoc::{DocFragmentKind, unindent_doc_fragments}; use rustc_span::create_default_session_globals_then; use super::*; diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 885758c17cf8e..b91c1725d0c81 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -5,12 +5,12 @@ use std::sync::LazyLock as Lazy; use rustc_ast::tokenstream::TokenTree; use rustc_hir::def::{DefKind, Res}; -use rustc_hir::def_id::{DefId, LocalDefId, LOCAL_CRATE}; +use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; use rustc_metadata::rendered_const; use rustc_middle::mir; use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt, TypeVisitableExt}; -use rustc_span::symbol::{kw, sym, Symbol}; -use thin_vec::{thin_vec, ThinVec}; +use rustc_span::symbol::{Symbol, kw, sym}; +use thin_vec::{ThinVec, thin_vec}; use tracing::{debug, warn}; use {rustc_ast as ast, rustc_hir as hir}; @@ -18,10 +18,10 @@ use crate::clean::auto_trait::synthesize_auto_trait_impls; use crate::clean::blanket_impl::synthesize_blanket_impls; use crate::clean::render_macro_matchers::render_macro_matcher; use crate::clean::{ - clean_doc_module, clean_middle_const, clean_middle_region, clean_middle_ty, inline, AssocItemConstraint, AssocItemConstraintKind, Crate, ExternalCrate, Generic, GenericArg, GenericArgs, ImportSource, Item, ItemKind, Lifetime, Path, PathSegment, Primitive, - PrimitiveType, Term, Type, + PrimitiveType, Term, Type, clean_doc_module, clean_middle_const, clean_middle_region, + clean_middle_ty, inline, }; use crate::core::DocContext; use crate::html::format::visibility_to_src_with_space; diff --git a/src/librustdoc/config.rs b/src/librustdoc/config.rs index b3c87a725080f..7a37f5c70a592 100644 --- a/src/librustdoc/config.rs +++ b/src/librustdoc/config.rs @@ -8,15 +8,15 @@ use std::{fmt, io}; use rustc_data_structures::fx::FxHashMap; use rustc_errors::DiagCtxtHandle; use rustc_session::config::{ - self, get_cmd_lint_options, nightly_options, parse_crate_types_from_list, parse_externs, - parse_target_triple, CodegenOptions, CrateType, ErrorOutputType, Externs, Input, - JsonUnusedExterns, UnstableOptions, + self, CodegenOptions, CrateType, ErrorOutputType, Externs, Input, JsonUnusedExterns, + UnstableOptions, get_cmd_lint_options, nightly_options, parse_crate_types_from_list, + parse_externs, parse_target_triple, }; use rustc_session::lint::Level; use rustc_session::search_paths::SearchPath; -use rustc_session::{getopts, EarlyDiagCtxt}; -use rustc_span::edition::Edition; +use rustc_session::{EarlyDiagCtxt, getopts}; use rustc_span::FileName; +use rustc_span::edition::Edition; use rustc_target::spec::TargetTriple; use crate::core::new_dcx; diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index b5648bf2c131f..8e46d93c28e02 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -8,7 +8,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_data_structures::sync::Lrc; use rustc_data_structures::unord::UnordSet; use rustc_errors::codes::*; -use rustc_errors::emitter::{stderr_destination, DynEmitter, HumanEmitter}; +use rustc_errors::emitter::{DynEmitter, HumanEmitter, stderr_destination}; use rustc_errors::json::JsonEmitter; use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, TerminalUrl}; use rustc_feature::UnstableFeatures; @@ -17,14 +17,14 @@ use rustc_hir::def_id::{DefId, DefIdMap, DefIdSet, LocalDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{HirId, Path}; use rustc_interface::interface; -use rustc_lint::{late_lint_mod, MissingDoc}; +use rustc_lint::{MissingDoc, late_lint_mod}; use rustc_middle::hir::nested_filter; use rustc_middle::ty::{ParamEnv, Ty, TyCtxt}; use rustc_session::config::{self, CrateType, ErrorOutputType, Input, ResolveDocLinks}; pub(crate) use rustc_session::config::{Options, UnstableOptions}; -use rustc_session::{lint, Session}; +use rustc_session::{Session, lint}; use rustc_span::symbol::sym; -use rustc_span::{source_map, Span}; +use rustc_span::{Span, source_map}; use tracing::{debug, info}; use crate::clean::inline::build_external_trait; diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 73eafaf78ca58..3ee6b24ac92cb 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -16,14 +16,14 @@ pub(crate) use markdown::test as test_markdown; use rustc_ast as ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_errors::{ColorConfig, DiagCtxtHandle, ErrorGuaranteed, FatalError}; -use rustc_hir::def_id::LOCAL_CRATE; use rustc_hir::CRATE_HIR_ID; +use rustc_hir::def_id::LOCAL_CRATE; use rustc_interface::interface; use rustc_session::config::{self, CrateType, ErrorOutputType, Input}; use rustc_session::lint; +use rustc_span::FileName; use rustc_span::edition::Edition; use rustc_span::symbol::sym; -use rustc_span::FileName; use rustc_target::spec::{Target, TargetTriple}; use tempfile::{Builder as TempFileBuilder, TempDir}; use tracing::debug; diff --git a/src/librustdoc/doctest/make.rs b/src/librustdoc/doctest/make.rs index f4d9b78cc32a4..d560e3a476b1b 100644 --- a/src/librustdoc/doctest/make.rs +++ b/src/librustdoc/doctest/make.rs @@ -10,10 +10,10 @@ use rustc_errors::{ColorConfig, FatalError}; use rustc_parse::new_parser_from_source_str; use rustc_parse::parser::attr::InnerAttrPolicy; use rustc_session::parse::ParseSess; +use rustc_span::FileName; use rustc_span::edition::Edition; use rustc_span::source_map::SourceMap; use rustc_span::symbol::sym; -use rustc_span::FileName; use tracing::debug; use super::GlobalTestOptions; @@ -252,8 +252,8 @@ fn parse_source( info: &mut ParseSourceInfo, crate_name: &Option<&str>, ) -> ParsingResult { - use rustc_errors::emitter::{Emitter, HumanEmitter}; use rustc_errors::DiagCtxt; + use rustc_errors::emitter::{Emitter, HumanEmitter}; use rustc_parse::parser::ForceCollect; use rustc_span::source_map::FilePathMapping; @@ -441,8 +441,8 @@ fn check_if_attr_is_complete(source: &str, edition: Edition) -> Option rustc_driver::catch_fatal_errors(|| { rustc_span::create_session_if_not_set_then(edition, |_| { - use rustc_errors::emitter::HumanEmitter; use rustc_errors::DiagCtxt; + use rustc_errors::emitter::HumanEmitter; use rustc_span::source_map::FilePathMapping; let filename = FileName::anon_source_code(source); diff --git a/src/librustdoc/doctest/markdown.rs b/src/librustdoc/doctest/markdown.rs index 4f83bd5e8826a..a0d39ce749d83 100644 --- a/src/librustdoc/doctest/markdown.rs +++ b/src/librustdoc/doctest/markdown.rs @@ -8,10 +8,10 @@ use rustc_span::FileName; use tempfile::tempdir; use super::{ - generate_args_file, CreateRunnableDocTests, DocTestVisitor, GlobalTestOptions, ScrapedDocTest, + CreateRunnableDocTests, DocTestVisitor, GlobalTestOptions, ScrapedDocTest, generate_args_file, }; use crate::config::Options; -use crate::html::markdown::{find_testable_code, ErrorCodes, LangString, MdRelLine}; +use crate::html::markdown::{ErrorCodes, LangString, MdRelLine, find_testable_code}; struct MdCollector { tests: Vec, diff --git a/src/librustdoc/doctest/runner.rs b/src/librustdoc/doctest/runner.rs index 9cb220ef7ba4d..326ca4ee1e68f 100644 --- a/src/librustdoc/doctest/runner.rs +++ b/src/librustdoc/doctest/runner.rs @@ -4,8 +4,8 @@ use rustc_data_structures::fx::FxHashSet; use rustc_span::edition::Edition; use crate::doctest::{ - run_test, DocTestBuilder, GlobalTestOptions, IndividualTestOptions, RunnableDocTest, - RustdocOptions, ScrapedDocTest, TestFailure, UnusedExterns, + DocTestBuilder, GlobalTestOptions, IndividualTestOptions, RunnableDocTest, RustdocOptions, + ScrapedDocTest, TestFailure, UnusedExterns, run_test, }; use crate::html::markdown::{Ignore, LangString}; diff --git a/src/librustdoc/doctest/rust.rs b/src/librustdoc/doctest/rust.rs index 71a0e3d72deeb..cc85a73430b37 100644 --- a/src/librustdoc/doctest/rust.rs +++ b/src/librustdoc/doctest/rust.rs @@ -4,19 +4,19 @@ use std::env; use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::sync::Lrc; -use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID}; -use rustc_hir::{self as hir, intravisit, CRATE_HIR_ID}; +use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId}; +use rustc_hir::{self as hir, CRATE_HIR_ID, intravisit}; use rustc_middle::hir::map::Map; use rustc_middle::hir::nested_filter; use rustc_middle::ty::TyCtxt; use rustc_resolve::rustdoc::span_of_fragments; use rustc_session::Session; use rustc_span::source_map::SourceMap; -use rustc_span::{BytePos, FileName, Pos, Span, DUMMY_SP}; +use rustc_span::{BytePos, DUMMY_SP, FileName, Pos, Span}; use super::{DocTestVisitor, ScrapedDocTest}; -use crate::clean::types::AttributesExt; use crate::clean::Attributes; +use crate::clean::types::AttributesExt; use crate::html::markdown::{self, ErrorCodes, LangString, MdRelLine}; struct RustCollector { diff --git a/src/librustdoc/formats/cache.rs b/src/librustdoc/formats/cache.rs index 1b3176e7918b7..8597d2e2b63eb 100644 --- a/src/librustdoc/formats/cache.rs +++ b/src/librustdoc/formats/cache.rs @@ -10,12 +10,12 @@ use crate::clean::types::ExternalLocation; use crate::clean::{self, ExternalCrate, ItemId, PrimitiveType}; use crate::core::DocContext; use crate::fold::DocFolder; -use crate::formats::item_type::ItemType; use crate::formats::Impl; +use crate::formats::item_type::ItemType; use crate::html::format::join_with_double_colon; use crate::html::markdown::short_markdown_summary; -use crate::html::render::search_index::get_function_type_for_search; use crate::html::render::IndexItem; +use crate::html::render::search_index::get_function_type_for_search; use crate::visit_lib::RustdocEffectiveVisibilities; /// This cache is used to store information about the [`clean::Crate`] being diff --git a/src/librustdoc/formats/mod.rs b/src/librustdoc/formats/mod.rs index 0bdea36043ca6..2e8b5d9f59489 100644 --- a/src/librustdoc/formats/mod.rs +++ b/src/librustdoc/formats/mod.rs @@ -2,7 +2,7 @@ pub(crate) mod cache; pub(crate) mod item_type; pub(crate) mod renderer; -pub(crate) use renderer::{run_format, FormatRenderer}; +pub(crate) use renderer::{FormatRenderer, run_format}; use rustc_hir::def_id::DefId; use crate::clean::{self, ItemId}; diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index cf362272d7de9..2e70a8c080de0 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -22,12 +22,12 @@ use rustc_metadata::creader::{CStore, LoadedMacro}; use rustc_middle::ty; use rustc_middle::ty::TyCtxt; use rustc_span::symbol::kw; -use rustc_span::{sym, Symbol}; +use rustc_span::{Symbol, sym}; use rustc_target::spec::abi::Abi; use tracing::{debug, trace}; use {rustc_ast as ast, rustc_hir as hir}; -use super::url_parts_builder::{estimate_item_path_byte_length, UrlPartsBuilder}; +use super::url_parts_builder::{UrlPartsBuilder, estimate_item_path_byte_length}; use crate::clean::types::ExternalLocation; use crate::clean::utils::find_nearest_parent_module; use crate::clean::{self, ExternalCrate, PrimitiveType}; diff --git a/src/librustdoc/html/highlight.rs b/src/librustdoc/html/highlight.rs index e728da67dc2f5..69b3421f8881f 100644 --- a/src/librustdoc/html/highlight.rs +++ b/src/librustdoc/html/highlight.rs @@ -12,7 +12,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_lexer::{Cursor, LiteralKind, TokenKind}; use rustc_span::edition::Edition; use rustc_span::symbol::Symbol; -use rustc_span::{BytePos, Span, DUMMY_SP}; +use rustc_span::{BytePos, DUMMY_SP, Span}; use super::format::{self, Buffer}; use crate::clean::PrimitiveType; @@ -72,34 +72,26 @@ fn write_header( tooltip: Tooltip, extra_classes: &[String], ) { - write!( - out, - "

", - match tooltip { - Tooltip::Ignore => " ignore", - Tooltip::CompileFail => " compile_fail", - Tooltip::ShouldPanic => " should_panic", - Tooltip::Edition(_) => " edition", - Tooltip::None => "", - }, - ); + write!(out, "
", match tooltip { + Tooltip::Ignore => " ignore", + Tooltip::CompileFail => " compile_fail", + Tooltip::ShouldPanic => " should_panic", + Tooltip::Edition(_) => " edition", + Tooltip::None => "", + },); if tooltip != Tooltip::None { let edition_code; - write!( - out, - "", - match tooltip { - Tooltip::Ignore => "This example is not tested", - Tooltip::CompileFail => "This example deliberately fails to compile", - Tooltip::ShouldPanic => "This example panics", - Tooltip::Edition(edition) => { - edition_code = format!("This example runs with edition {edition}"); - &edition_code - } - Tooltip::None => unreachable!(), - }, - ); + write!(out, "", match tooltip { + Tooltip::Ignore => "This example is not tested", + Tooltip::CompileFail => "This example deliberately fails to compile", + Tooltip::ShouldPanic => "This example panics", + Tooltip::Edition(edition) => { + edition_code = format!("This example runs with edition {edition}"); + &edition_code + } + Tooltip::None => unreachable!(), + },); } if let Some(extra) = extra_content { diff --git a/src/librustdoc/html/highlight/tests.rs b/src/librustdoc/html/highlight/tests.rs index 9d511018decd6..75328e724fea8 100644 --- a/src/librustdoc/html/highlight/tests.rs +++ b/src/librustdoc/html/highlight/tests.rs @@ -2,7 +2,7 @@ use expect_test::expect_file; use rustc_data_structures::fx::FxHashMap; use rustc_span::create_default_session_globals_then; -use super::{write_code, DecorationInfo}; +use super::{DecorationInfo, write_code}; use crate::html::format::Buffer; const STYLE: &str = r#" diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index 780cda9b1cdf4..3684dc42ac73c 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -3,10 +3,10 @@ use std::path::PathBuf; use rinja::Template; use rustc_data_structures::fx::FxHashMap; -use super::static_files::{StaticFiles, STATIC_FILES}; +use super::static_files::{STATIC_FILES, StaticFiles}; use crate::externalfiles::ExternalHtml; use crate::html::format::{Buffer, Print}; -use crate::html::render::{ensure_trailing_slash, StylePath}; +use crate::html::render::{StylePath, ensure_trailing_slash}; #[derive(Clone)] pub(crate) struct Layout { diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 6f4665db6f1de..b18d621478c7d 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -35,8 +35,8 @@ use std::str::{self, CharIndices}; use std::sync::OnceLock; use pulldown_cmark::{ - html, BrokenLink, BrokenLinkCallback, CodeBlockKind, CowStr, Event, LinkType, OffsetIter, - Options, Parser, Tag, TagEnd, + BrokenLink, BrokenLinkCallback, CodeBlockKind, CowStr, Event, LinkType, OffsetIter, Options, + Parser, Tag, TagEnd, html, }; use rustc_data_structures::fx::FxHashMap; use rustc_errors::{Diag, DiagMessage}; @@ -261,7 +261,9 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { \
", added_classes = added_classes.join(" "), - text = Escape(&original_text), + text = Escape( + original_text.strip_suffix('\n').unwrap_or(&original_text) + ), ) .into(), )); diff --git a/src/librustdoc/html/markdown/tests.rs b/src/librustdoc/html/markdown/tests.rs index e490099a92e14..2001a763c09e8 100644 --- a/src/librustdoc/html/markdown/tests.rs +++ b/src/librustdoc/html/markdown/tests.rs @@ -1,8 +1,8 @@ -use rustc_span::edition::{Edition, DEFAULT_EDITION}; +use rustc_span::edition::{DEFAULT_EDITION, Edition}; use super::{ - find_testable_code, plain_text_summary, short_markdown_summary, ErrorCodes, HeadingOffset, - IdMap, Ignore, LangString, LangStringToken, Markdown, MarkdownItemInfo, TagIterator, + ErrorCodes, HeadingOffset, IdMap, Ignore, LangString, LangStringToken, Markdown, + MarkdownItemInfo, TagIterator, find_testable_code, plain_text_summary, short_markdown_summary, }; #[test] @@ -275,14 +275,14 @@ fn test_lang_string_tokenizer() { case("foo", &[LangStringToken::LangToken("foo")]); case("foo,bar", &[LangStringToken::LangToken("foo"), LangStringToken::LangToken("bar")]); case(".foo,.bar", &[]); - case( - "{.foo,.bar}", - &[LangStringToken::ClassAttribute("foo"), LangStringToken::ClassAttribute("bar")], - ); - case( - " {.foo,.bar} ", - &[LangStringToken::ClassAttribute("foo"), LangStringToken::ClassAttribute("bar")], - ); + case("{.foo,.bar}", &[ + LangStringToken::ClassAttribute("foo"), + LangStringToken::ClassAttribute("bar"), + ]); + case(" {.foo,.bar} ", &[ + LangStringToken::ClassAttribute("foo"), + LangStringToken::ClassAttribute("bar"), + ]); case("foo bar", &[LangStringToken::LangToken("foo"), LangStringToken::LangToken("bar")]); case("foo\tbar", &[LangStringToken::LangToken("foo"), LangStringToken::LangToken("bar")]); case("foo\t, bar", &[LangStringToken::LangToken("foo"), LangStringToken::LangToken("bar")]); @@ -524,15 +524,13 @@ fn test_ascii_with_prepending_hashtag() { ####.###..#....#....#..#. #..#.#....#....#....#..#. #..#.#....#....#....#..#. -#..#.####.####.####..##.. -
", +#..#.####.####.####..##..", ); t( r#"```markdown # hello ```"#, "
\
-# hello
-
", +# hello", ); } diff --git a/src/librustdoc/html/render/context.rs b/src/librustdoc/html/render/context.rs index a9b9377c0b972..bce3f21890857 100644 --- a/src/librustdoc/html/render/context.rs +++ b/src/librustdoc/html/render/context.rs @@ -3,7 +3,7 @@ use std::collections::BTreeMap; use std::io; use std::path::{Path, PathBuf}; use std::rc::Rc; -use std::sync::mpsc::{channel, Receiver}; +use std::sync::mpsc::{Receiver, channel}; use rinja::Template; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; @@ -11,24 +11,24 @@ use rustc_hir::def_id::{DefIdMap, LOCAL_CRATE}; use rustc_middle::ty::TyCtxt; use rustc_session::Session; use rustc_span::edition::Edition; -use rustc_span::{sym, FileName, Symbol}; +use rustc_span::{FileName, Symbol, sym}; use tracing::info; use super::print_item::{full_path, item_path, print_item}; -use super::sidebar::{print_sidebar, sidebar_module_like, ModuleLike, Sidebar}; -use super::{collect_spans_and_sources, scrape_examples_help, AllTypes, LinkFromSrc, StylePath}; +use super::sidebar::{ModuleLike, Sidebar, print_sidebar, sidebar_module_like}; +use super::{AllTypes, LinkFromSrc, StylePath, collect_spans_and_sources, scrape_examples_help}; use crate::clean::types::ExternalLocation; use crate::clean::utils::has_doc_flag; use crate::clean::{self, ExternalCrate}; use crate::config::{ModuleSorting, RenderOptions, ShouldMerge}; use crate::docfs::{DocFS, PathError}; use crate::error::Error; +use crate::formats::FormatRenderer; use crate::formats::cache::Cache; use crate::formats::item_type::ItemType; -use crate::formats::FormatRenderer; use crate::html::escape::Escape; -use crate::html::format::{join_with_double_colon, Buffer}; -use crate::html::markdown::{self, plain_text_summary, ErrorCodes, IdMap}; +use crate::html::format::{Buffer, join_with_double_colon}; +use crate::html::markdown::{self, ErrorCodes, IdMap, plain_text_summary}; use crate::html::render::write_shared::write_shared; use crate::html::url_parts_builder::UrlPartsBuilder; use crate::html::{layout, sources, static_files}; diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 668bd39134856..227df0c5f3930 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -48,30 +48,30 @@ use rinja::Template; use rustc_attr::{ConstStability, DeprecatedSince, Deprecation, StabilityLevel, StableSince}; use rustc_data_structures::captures::Captures; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_hir::def_id::{DefId, DefIdSet}; use rustc_hir::Mutability; +use rustc_hir::def_id::{DefId, DefIdSet}; use rustc_middle::ty::print::PrintTraitRefExt; use rustc_middle::ty::{self, TyCtxt}; use rustc_session::RustcVersion; -use rustc_span::symbol::{sym, Symbol}; -use rustc_span::{BytePos, FileName, RealFileName, DUMMY_SP}; +use rustc_span::symbol::{Symbol, sym}; +use rustc_span::{BytePos, DUMMY_SP, FileName, RealFileName}; use serde::ser::SerializeMap; use serde::{Serialize, Serializer}; use tracing::{debug, info}; pub(crate) use self::context::*; -pub(crate) use self::span_map::{collect_spans_and_sources, LinkFromSrc}; +pub(crate) use self::span_map::{LinkFromSrc, collect_spans_and_sources}; pub(crate) use self::write_shared::*; use crate::clean::{self, ItemId, RenderedLink}; use crate::error::Error; +use crate::formats::Impl; use crate::formats::cache::Cache; use crate::formats::item_type::ItemType; -use crate::formats::Impl; use crate::html::escape::Escape; use crate::html::format::{ - display_fn, href, join_with_double_colon, print_abi_with_space, print_constness_with_space, - print_default_space, print_generic_bounds, print_where_clause, visibility_print_with_space, - Buffer, Ending, HrefError, PrintWithSpace, + Buffer, Ending, HrefError, PrintWithSpace, display_fn, href, join_with_double_colon, + print_abi_with_space, print_constness_with_space, print_default_space, print_generic_bounds, + print_where_clause, visibility_print_with_space, }; use crate::html::markdown::{ HeadingOffset, IdMap, Markdown, MarkdownItemInfo, MarkdownSummaryLine, @@ -79,7 +79,7 @@ use crate::html::markdown::{ use crate::html::static_files::SCRAPE_EXAMPLES_HELP_MD; use crate::html::{highlight, sources}; use crate::scrape_examples::{CallData, CallLocation}; -use crate::{try_none, DOC_RUST_LANG_ORG_CHANNEL}; +use crate::{DOC_RUST_LANG_ORG_CHANNEL, try_none}; pub(crate) fn ensure_trailing_slash(v: &str) -> impl fmt::Display + '_ { crate::html::format::display_fn(move |f| { diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 52e2515277087..d120e7f36eb6a 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -13,27 +13,27 @@ use rustc_hir::def_id::DefId; use rustc_index::IndexVec; use rustc_middle::ty::{self, TyCtxt}; use rustc_span::hygiene::MacroKind; -use rustc_span::symbol::{kw, sym, Symbol}; +use rustc_span::symbol::{Symbol, kw, sym}; use rustc_target::abi::VariantIdx; use tracing::{debug, info}; use super::type_layout::document_type_layout; use super::{ + AssocItemLink, AssocItemRender, Context, ImplRenderingParameters, RenderMode, collect_paths_for_type, document, ensure_trailing_slash, get_filtered_impls_for_reference, item_ty_to_section, notable_traits_button, notable_traits_json, render_all_impls, render_assoc_item, render_assoc_items, render_attributes_in_code, render_attributes_in_pre, render_impl, render_rightside, render_stability_since_raw, - render_stability_since_raw_with_extra, write_section_heading, AssocItemLink, AssocItemRender, - Context, ImplRenderingParameters, RenderMode, + render_stability_since_raw_with_extra, write_section_heading, }; use crate::clean; use crate::config::ModuleSorting; -use crate::formats::item_type::ItemType; use crate::formats::Impl; +use crate::formats::item_type::ItemType; use crate::html::escape::{Escape, EscapeBodyTextWithWbr}; use crate::html::format::{ - display_fn, join_with_double_colon, print_abi_with_space, print_constness_with_space, - print_where_clause, visibility_print_with_space, Buffer, Ending, PrintWithSpace, + Buffer, Ending, PrintWithSpace, display_fn, join_with_double_colon, print_abi_with_space, + print_constness_with_space, print_where_clause, visibility_print_with_space, }; use crate::html::highlight; use crate::html::markdown::{HeadingOffset, MarkdownSummaryLine}; diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index 86b719c46e8b0..660ca3b2594cc 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -8,7 +8,7 @@ use rustc_data_structures::fx::{FxHashMap, FxIndexMap}; use rustc_middle::ty::TyCtxt; use rustc_span::def_id::DefId; use rustc_span::sym; -use rustc_span::symbol::{kw, Symbol}; +use rustc_span::symbol::{Symbol, kw}; use serde::ser::{Serialize, SerializeSeq, SerializeStruct, Serializer}; use thin_vec::ThinVec; use tracing::instrument; @@ -1169,14 +1169,13 @@ fn simplify_fn_type<'a, 'tcx>( *stored_bounds = type_bounds; } } - ty_constraints.push(( - RenderTypeId::AssociatedType(name), - vec![RenderType { + ty_constraints.push((RenderTypeId::AssociatedType(name), vec![ + RenderType { id: Some(RenderTypeId::Index(idx)), generics: None, bindings: None, - }], - )) + }, + ])) } } } diff --git a/src/librustdoc/html/render/sidebar.rs b/src/librustdoc/html/render/sidebar.rs index 842ee81624ef2..e7706e7fdeaec 100644 --- a/src/librustdoc/html/render/sidebar.rs +++ b/src/librustdoc/html/render/sidebar.rs @@ -8,10 +8,10 @@ use rustc_hir::def_id::DefIdSet; use rustc_middle::ty::{self, TyCtxt}; use tracing::debug; -use super::{item_ty_to_section, Context, ItemSection}; +use super::{Context, ItemSection, item_ty_to_section}; use crate::clean; -use crate::formats::item_type::ItemType; use crate::formats::Impl; +use crate::formats::item_type::ItemType; use crate::html::format::Buffer; use crate::html::markdown::{IdMap, MarkdownWithToc}; diff --git a/src/librustdoc/html/render/span_map.rs b/src/librustdoc/html/render/span_map.rs index 5b53277c059a9..2143f1ff23650 100644 --- a/src/librustdoc/html/render/span_map.rs +++ b/src/librustdoc/html/render/span_map.rs @@ -10,7 +10,7 @@ use rustc_middle::ty::TyCtxt; use rustc_span::hygiene::MacroKind; use rustc_span::{BytePos, ExpnKind, Span}; -use crate::clean::{self, rustc_span, PrimitiveType}; +use crate::clean::{self, PrimitiveType, rustc_span}; use crate::html::sources; /// This enum allows us to store two different kinds of information: diff --git a/src/librustdoc/html/render/write_shared.rs b/src/librustdoc/html/render/write_shared.rs index dc1a8cca6bc8f..1625379921577 100644 --- a/src/librustdoc/html/render/write_shared.rs +++ b/src/librustdoc/html/render/write_shared.rs @@ -29,26 +29,26 @@ use itertools::Itertools; use regex::Regex; use rustc_data_structures::flock; use rustc_data_structures::fx::{FxHashMap, FxHashSet}; -use rustc_middle::ty::fast_reject::DeepRejectCtxt; use rustc_middle::ty::TyCtxt; -use rustc_span::def_id::DefId; +use rustc_middle::ty::fast_reject::DeepRejectCtxt; use rustc_span::Symbol; +use rustc_span::def_id::DefId; use serde::de::DeserializeOwned; use serde::ser::SerializeSeq; use serde::{Deserialize, Serialize, Serializer}; -use super::{collect_paths_for_type, ensure_trailing_slash, Context, RenderMode}; +use super::{Context, RenderMode, collect_paths_for_type, ensure_trailing_slash}; use crate::clean::{Crate, Item, ItemId, ItemKind}; use crate::config::{EmitType, PathToParts, RenderOptions, ShouldMerge}; use crate::docfs::PathError; use crate::error::Error; +use crate::formats::Impl; use crate::formats::cache::Cache; use crate::formats::item_type::ItemType; -use crate::formats::Impl; use crate::html::format::Buffer; use crate::html::layout; use crate::html::render::ordered_json::{EscapedJson, OrderedJson}; -use crate::html::render::search_index::{build_index, SerializedSearchIndex}; +use crate::html::render::search_index::{SerializedSearchIndex, build_index}; use crate::html::render::sorted_template::{self, FileFormat, SortedTemplate}; use crate::html::render::{AssocItemLink, ImplRenderingParameters, StylePath}; use crate::html::static_files::{self, suffix_path}; diff --git a/src/librustdoc/html/sources.rs b/src/librustdoc/html/sources.rs index 0d6a4603cd292..9ba0fb7b83c95 100644 --- a/src/librustdoc/html/sources.rs +++ b/src/librustdoc/html/sources.rs @@ -10,7 +10,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir::def_id::LOCAL_CRATE; use rustc_middle::ty::TyCtxt; use rustc_session::Session; -use rustc_span::{sym, FileName}; +use rustc_span::{FileName, sym}; use tracing::info; use crate::clean; @@ -26,8 +26,11 @@ pub(crate) fn render(cx: &mut Context<'_>, krate: &clean::Crate) -> Result<(), E let dst = cx.dst.join("src").join(krate.name(cx.tcx()).as_str()); cx.shared.ensure_dir(&dst)?; + let crate_name = krate.name(cx.tcx()); + let crate_name = crate_name.as_str(); - let mut collector = SourceCollector { dst, cx, emitted_local_sources: FxHashSet::default() }; + let mut collector = + SourceCollector { dst, cx, emitted_local_sources: FxHashSet::default(), crate_name }; collector.visit_crate(krate); Ok(()) } @@ -115,6 +118,8 @@ struct SourceCollector<'a, 'tcx> { /// Root destination to place all HTML output into dst: PathBuf, emitted_local_sources: FxHashSet, + + crate_name: &'a str, } impl DocVisitor for SourceCollector<'_, '_> { @@ -210,6 +215,9 @@ impl SourceCollector<'_, '_> { }, ); + let src_fname = p.file_name().expect("source has no filename").to_os_string(); + let mut fname = src_fname.clone(); + let root_path = PathBuf::from("../../").join(root_path.into_inner()); let mut root_path = root_path.to_string_lossy(); if let Some(c) = root_path.as_bytes().last() @@ -217,12 +225,12 @@ impl SourceCollector<'_, '_> { { root_path += "/"; } + let mut file_path = Path::new(&self.crate_name).join(&*cur.borrow()); + file_path.push(&fname); + fname.push(".html"); let mut cur = self.dst.join(cur.into_inner()); shared.ensure_dir(&cur)?; - let src_fname = p.file_name().expect("source has no filename").to_os_string(); - let mut fname = src_fname.clone(); - fname.push(".html"); cur.push(&fname); let title = format!("{} - source", src_fname.to_string_lossy()); @@ -250,7 +258,7 @@ impl SourceCollector<'_, '_> { cx, &root_path, highlight::DecorationInfo::default(), - SourceContext::Standalone, + SourceContext::Standalone { file_path }, ) }, &shared.style_files, @@ -312,10 +320,11 @@ struct ScrapedSource<'a, Code: std::fmt::Display> { struct Source { lines: RangeInclusive, code_html: Code, + file_path: Option<(String, String)>, } pub(crate) enum SourceContext<'a> { - Standalone, + Standalone { file_path: PathBuf }, Embedded(ScrapedInfo<'a>), } @@ -344,9 +353,19 @@ pub(crate) fn print_src( }); let lines = s.lines().count(); match source_context { - SourceContext::Standalone => { - Source { lines: (1..=lines), code_html: code }.render_into(&mut writer).unwrap() + SourceContext::Standalone { file_path } => Source { + lines: (1..=lines), + code_html: code, + file_path: if let Some(file_name) = file_path.file_name() + && let Some(file_path) = file_path.parent() + { + Some((file_path.display().to_string(), file_name.display().to_string())) + } else { + None + }, } + .render_into(&mut writer) + .unwrap(), SourceContext::Embedded(info) => { let lines = (1 + info.offset)..=(lines + info.offset); ScrapedSource { info, lines, code_html: code }.render_into(&mut writer).unwrap(); diff --git a/src/librustdoc/html/static/css/noscript.css b/src/librustdoc/html/static/css/noscript.css index e62b16267f102..477a79d63e948 100644 --- a/src/librustdoc/html/static/css/noscript.css +++ b/src/librustdoc/html/static/css/noscript.css @@ -61,6 +61,8 @@ nav.sub { --copy-path-img-hover-filter: invert(35%); --code-example-button-color: #7f7f7f; --code-example-button-hover-color: #595959; + --settings-menu-filter: invert(50%); + --settings-menu-hover-filter: invert(35%); --codeblock-error-hover-color: rgb(255, 0, 0); --codeblock-error-color: rgba(255, 0, 0, .5); --codeblock-ignore-hover-color: rgb(255, 142, 0); @@ -87,7 +89,6 @@ nav.sub { --search-tab-button-not-selected-background: #e6e6e6; --search-tab-button-selected-border-top-color: #0089ff; --search-tab-button-selected-background: #fff; - --settings-menu-filter: none; --stab-background-color: #fff5d6; --stab-code-color: #000; --code-highlight-kw-color: #8959a8; @@ -192,6 +193,8 @@ nav.sub { --search-tab-button-not-selected-background: #252525; --search-tab-button-selected-border-top-color: #0089ff; --search-tab-button-selected-background: #353535; + --settings-menu-filter: invert(50%); + --settings-menu-hover-filter: invert(65%); --stab-background-color: #314559; --stab-code-color: #e6e1cf; --code-highlight-kw-color: #ab8ac1; diff --git a/src/librustdoc/html/static/css/rustdoc.css b/src/librustdoc/html/static/css/rustdoc.css index 04b0eba745090..ae9727a4d4f57 100644 --- a/src/librustdoc/html/static/css/rustdoc.css +++ b/src/librustdoc/html/static/css/rustdoc.css @@ -34,6 +34,8 @@ xmlns="http://www.w3.org/2000/svg" fill="black" height="18px">\ '); --button-left-margin: 4px; --button-border-radius: 2px; + --toolbar-button-border-radius: 6px; + --code-block-border-radius: 6px; } /* See FiraSans-LICENSE.txt for the Fira Sans license. */ @@ -165,7 +167,7 @@ h1, h2, h3, h4 { .main-heading h1 { margin: 0; padding: 0; - flex-grow: 1; + grid-area: main-heading-h1; /* We use overflow-wrap: break-word for Safari, which doesn't recognize `anywhere`: https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-wrap */ overflow-wrap: break-word; @@ -174,10 +176,28 @@ h1, h2, h3, h4 { overflow-wrap: anywhere; } .main-heading { - display: flex; - flex-wrap: wrap; + position: relative; + display: grid; + grid-template-areas: + "main-heading-breadcrumbs main-heading-breadcrumbs" + "main-heading-h1 main-heading-toolbar" + "main-heading-sub-heading main-heading-toolbar"; + grid-template-columns: 1fr max-content; + grid-template-rows: 25px min-content min-content; padding-bottom: 6px; - margin-bottom: 15px; + margin-bottom: 11px; +} +.rustdoc-breadcrumbs { + grid-area: main-heading-breadcrumbs; + height: 25px; + line-height: 1.25; + display: flex; + align-items: end; +} +.rustdoc-breadcrumbs a { + padding: 4px 0; + margin: -4px 0; + z-index: 1; } /* The only headings that get underlines are: Markdown-generated headings within the top-doc @@ -218,11 +238,13 @@ h1, h2, h3, h4, h5, h6, .search-results .result-name, .item-name > a, .out-of-band, +.sub-heading, span.since, a.src, -#help-button > a, +rustdoc-toolbar, summary.hideme, .scraped-example-list, +.rustdoc-breadcrumbs, /* This selector is for the items listed in the "all items" page. */ ul.all-items { font-family: "Fira Sans", Arial, NanumBarunGothic, sans-serif; @@ -891,14 +913,27 @@ both the code example and the line numbers, so we need to remove the radius in t overflow-x: auto; } -.out-of-band { +.sub-heading { + font-size: 1rem; flex-grow: 0; - font-size: 1.125rem; + grid-area: main-heading-sub-heading; + line-height: 1.25; + padding-bottom: 4px; +} + +.main-heading rustdoc-toolbar, .main-heading .out-of-band { + grid-area: main-heading-toolbar; +} +rustdoc-toolbar { + display: flex; + flex-direction: row; + flex-wrap: nowrap; } .docblock code, .docblock-short code, pre, .rustdoc.src .example-wrap, .example-wrap .src-line-numbers { background-color: var(--code-block-background-color); + border-radius: var(--code-block-border-radius); } #main-content { @@ -945,7 +980,7 @@ div.where { nav.sub { flex-grow: 1; flex-flow: row nowrap; - margin: 4px 0 25px 0; + margin: 4px 0 0 0; display: flex; align-items: center; } @@ -956,7 +991,7 @@ nav.sub { flex-grow: 1; } .src nav.sub { - margin: 0 0 15px 0; + margin: 0 0 -10px 0; } .section-header { @@ -1066,6 +1101,11 @@ table, with boxes (i.e. from the flex layout) */ align-items: baseline; } +.search-results-title + .sub-heading { + color: var(--main-color); + display: flex; + align-items: center; +} #crate-search-div { /* ensures that 100% in properties of #crate-search-div:after are relative to the size of this div */ @@ -1289,10 +1329,16 @@ so that we can apply CSS-filters to change the arrow color in themes */ border-color: var(--settings-input-color) !important; } +#settings.popover { + --popover-arrow-offset: 202px; + top: calc(100% - 16px); +} + /* use larger max-width for help popover, but not for help.html */ #help.popover { max-width: 600px; - --popover-arrow-offset: 48px; + --popover-arrow-offset: 118px; + top: calc(100% - 16px); } #help dt { @@ -1300,10 +1346,15 @@ so that we can apply CSS-filters to change the arrow color in themes */ clear: left; margin-right: 0.5rem; } +#help dd { + margin-bottom: 0.5rem; +} #help span.top, #help span.bottom { text-align: center; display: block; font-size: 1.125rem; + padding: 0 0.5rem; + text-wrap-style: balance; } #help span.top { margin: 10px 0; @@ -1315,10 +1366,13 @@ so that we can apply CSS-filters to change the arrow color in themes */ clear: both; border-top: 1px solid var(--border-color); } +.side-by-side { + display: flex; + margin-bottom: 20px; +} .side-by-side > div { width: 50%; - float: left; - padding: 0 20px 20px 17px; + padding: 0 20px 0 17px; } .item-info .stab { @@ -1381,7 +1435,9 @@ so that we can apply CSS-filters to change the arrow color in themes */ } .rightside:not(a), -.out-of-band { +.out-of-band, +.sub-heading, +rustdoc-toolbar { color: var(--right-side-color); } @@ -1595,8 +1651,8 @@ instead, we check that it's not a "finger" cursor. display: block; } -.out-of-band > span.since { - font-size: 1.25rem; +.main-heading span.since::before { + content: "Since "; } .sub-variant h4 { @@ -1698,6 +1754,7 @@ a.tooltip:hover::after { } #search-tabs { + margin-top: 0.25rem; display: flex; flex-direction: row; gap: 1px; @@ -1759,9 +1816,10 @@ a.tooltip:hover::after { border-bottom: 1px solid var(--border-color); } -#settings-menu, #help-button { +#settings-menu, #help-button, button#toggle-all-docs { margin-left: var(--button-left-margin); display: flex; + line-height: 1.25; } #sidebar-button { display: none; @@ -1785,33 +1843,36 @@ a.tooltip:hover::after { .hide-sidebar .src #sidebar-button { position: static; } -#settings-menu > a, #help-button > a, #sidebar-button > a { +#settings-menu > a, #help-button > a, #sidebar-button > a, button#toggle-all-docs { display: flex; align-items: center; justify-content: center; - background-color: var(--button-background-color); - border: 1px solid var(--border-color); + flex-direction: column; + border: 1px solid transparent; border-radius: var(--button-border-radius); - color: var(--settings-button-color); - /* Rare exception to specifying font sizes in rem. Since this is acting - as an icon, it's okay to specify their sizes in pixels. */ - font-size: 20px; + color: var(--main-color); +} +#settings-menu > a, #help-button > a, button#toggle-all-docs { + width: 80px; + border-radius: var(--toolbar-button-border-radius); +} +#sidebar-button > a { + background-color: var(--button-background-color); + border-color: var(--border-color); width: 33px; } -#settings-menu > a:hover, #settings-menu > a:focus, -#help-button > a:hover, #help-button > a:focus, -#sidebar-button > a:hover, #sidebar-button > a:focus { +#settings-menu > a:hover, #settings-menu > a:focus-visible, +#help-button > a:hover, #help-button > a:focus-visible, +#sidebar-button > a:hover, #sidebar-button > a:focus-visible, +button#toggle-all-docs:hover, button#toggle-all-docs:focus-visible { border-color: var(--settings-button-border-focus); + text-decoration: none; } -#settings-menu > a { - line-height: 0; - font-size: 0; -} #settings-menu > a:before { /* Wheel */ - content: url('data:image/svg+xml,\ '); - width: 22px; - height: 22px; + width: 18px; + height: 18px; + filter: var(--settings-menu-filter); +} + +button#toggle-all-docs:before { + /* Custom arrow icon */ + content: url('data:image/svg+xml,\ + '); + width: 18px; + height: 18px; + filter: var(--settings-menu-filter); +} + +#help-button > a:before { + /* Question mark with circle */ + content: url('data:image/svg+xml,\ + \ + ?'); + width: 18px; + height: 18px; + filter: var(--settings-menu-filter); +} + +button#toggle-all-docs:before, +#help-button > a:before, +#settings-menu > a:before { filter: var(--settings-menu-filter); + margin: 8px; +} + +@media not (pointer: coarse) { + button#toggle-all-docs:hover:before, + #help-button > a:hover:before, + #settings-menu > a:hover:before { + filter: var(--settings-menu-hover-filter); + } +} + +button[disabled]#toggle-all-docs { + opacity: 0.25; + border: solid 1px var(--main-background-color); + background-size: cover; +} + +button[disabled]#toggle-all-docs:hover { + border: solid 1px var(--main-background-color); + cursor: not-allowed; +} + +rustdoc-toolbar span.label { + font-size: 1rem; + flex-grow: 1; + padding-bottom: 4px; } #sidebar-button > a:before { /* sidebar resizer image */ content: url('data:image/svg+xml,\ - \ + \ \ '); width: 22px; @@ -1948,10 +2063,10 @@ details.toggle > summary.hideme > span { } details.toggle > summary::before { - /* toggle plus */ - background: url('data:image/svg+xml,') no-repeat top left; + /* arrow pointing left */ + background: url('data:image/svg+xml,\ + '); content: ""; cursor: pointer; width: 16px; @@ -2034,10 +2149,10 @@ details.toggle[open] > summary.hideme > span { } details.toggle[open] > summary::before { - /* toggle minus */ - background: url('data:image/svg+xml,') no-repeat top left; + /* arrow pointing down */ + background: url('data:image/svg+xml,\ + '); } details.toggle[open] > summary::after { @@ -2090,6 +2205,12 @@ However, it's not needed with smaller screen width because the doc/code block is #search-tabs .count { display: block; } + .side-by-side { + flex-direction: column-reverse; + } + .side-by-side > div { + width: auto; + } } /* @@ -2106,6 +2227,25 @@ in src-script.js and main.js scroll-margin-top: 45px; } + /* We don't display this button on mobile devices. */ + #copy-path { + display: none; + } + + /* Text label takes up too much space at this size. */ + rustdoc-toolbar span.label { + display: none; + } + #settings-menu > a, #help-button > a, button#toggle-all-docs { + width: 33px; + } + #settings.popover { + --popover-arrow-offset: 86px; + } + #help.popover { + --popover-arrow-offset: 48px; + } + .rustdoc { /* Sidebar should overlay main content, rather than pushing main content to the right. Turn off `display: flex` on the body element. */ @@ -2117,20 +2257,6 @@ in src-script.js and main.js padding-top: 0px; } - .main-heading { - flex-direction: column; - } - - .out-of-band { - text-align: left; - margin-left: initial; - padding: initial; - } - - .out-of-band .since::before { - content: "Since "; - } - /* Hide the logo and item name from the sidebar. Those are displayed in the mobile-topbar instead. */ .sidebar .logo-container, @@ -2163,6 +2289,9 @@ in src-script.js and main.js .src .search-form { margin-left: 40px; } + .src .main-heading { + margin-left: 8px; + } .hide-sidebar .search-form { margin-left: 32px; } @@ -2234,16 +2363,11 @@ in src-script.js and main.js left: -11px; } - /* We don't display these buttons on mobile devices. */ - #copy-path, #help-button { - display: none; - } - /* sidebar button becomes topbar button */ #sidebar-button > a:before { content: url('data:image/svg+xml,\ - \ + \ \ '); width: 22px; @@ -2305,7 +2429,7 @@ in src-script.js and main.js } .src nav.sub { - margin: 0; + margin: 0 0 -25px 0; padding: var(--nav-sub-mobile-padding); } } @@ -2543,6 +2667,8 @@ by default. --copy-path-img-hover-filter: invert(35%); --code-example-button-color: #7f7f7f; --code-example-button-hover-color: #595959; + --settings-menu-filter: invert(50%); + --settings-menu-hover-filter: invert(35%); --codeblock-error-hover-color: rgb(255, 0, 0); --codeblock-error-color: rgba(255, 0, 0, .5); --codeblock-ignore-hover-color: rgb(255, 142, 0); @@ -2569,7 +2695,6 @@ by default. --search-tab-button-not-selected-background: #e6e6e6; --search-tab-button-selected-border-top-color: #0089ff; --search-tab-button-selected-background: #fff; - --settings-menu-filter: none; --stab-background-color: #fff5d6; --stab-code-color: #000; --code-highlight-kw-color: #8959a8; @@ -2673,7 +2798,8 @@ by default. --search-tab-button-not-selected-background: #252525; --search-tab-button-selected-border-top-color: #0089ff; --search-tab-button-selected-background: #353535; - --settings-menu-filter: none; + --settings-menu-filter: invert(50%); + --settings-menu-hover-filter: invert(65%); --stab-background-color: #314559; --stab-code-color: #e6e1cf; --code-highlight-kw-color: #ab8ac1; @@ -2784,7 +2910,8 @@ Original by Dempfi (https://github.com/dempfi/ayu) --search-tab-button-not-selected-background: transparent !important; --search-tab-button-selected-border-top-color: none; --search-tab-button-selected-background: #141920 !important; - --settings-menu-filter: invert(100%); + --settings-menu-filter: invert(70%); + --settings-menu-hover-filter: invert(100%); --stab-background-color: #314559; --stab-code-color: #e6e1cf; --code-highlight-kw-color: #ff7733; diff --git a/src/librustdoc/html/static/js/main.js b/src/librustdoc/html/static/js/main.js index a0ec45b5ef38c..0d556e0a68274 100644 --- a/src/librustdoc/html/static/js/main.js +++ b/src/librustdoc/html/static/js/main.js @@ -1,6 +1,6 @@ // Local js definitions: /* global addClass, getSettingValue, hasClass, searchState, updateLocalStorage */ -/* global onEach, onEachLazy, removeClass, getVar */ +/* global onEachLazy, removeClass, getVar */ "use strict"; @@ -19,17 +19,25 @@ function resourcePath(basename, extension) { function hideMain() { addClass(document.getElementById(MAIN_ID), "hidden"); + const toggle = document.getElementById("toggle-all-docs"); + if (toggle) { + toggle.setAttribute("disabled", "disabled"); + } } function showMain() { - removeClass(document.getElementById(MAIN_ID), "hidden"); -} - -function blurHandler(event, parentElem, hideCallback) { - if (!parentElem.contains(document.activeElement) && - !parentElem.contains(event.relatedTarget) - ) { - hideCallback(); + const main = document.getElementById(MAIN_ID); + removeClass(main, "hidden"); + const mainHeading = main.querySelector(".main-heading"); + if (mainHeading && searchState.rustdocToolbar) { + if (searchState.rustdocToolbar.parentElement) { + searchState.rustdocToolbar.parentElement.removeChild(searchState.rustdocToolbar); + } + mainHeading.appendChild(searchState.rustdocToolbar); + } + const toggle = document.getElementById("toggle-all-docs"); + if (toggle) { + toggle.removeAttribute("disabled"); } } @@ -167,6 +175,14 @@ function switchDisplayedElement(elemToDisplay) { el.appendChild(elemToDisplay); hideMain(); removeClass(el, "hidden"); + + const mainHeading = elemToDisplay.querySelector(".main-heading"); + if (mainHeading && searchState.rustdocToolbar) { + if (searchState.rustdocToolbar.parentElement) { + searchState.rustdocToolbar.parentElement.removeChild(searchState.rustdocToolbar); + } + mainHeading.appendChild(searchState.rustdocToolbar); + } } function browserSupportsHistoryApi() { @@ -194,33 +210,36 @@ function preLoadCss(cssUrl) { document.head.append(script); } - getSettingsButton().onclick = event => { - if (event.ctrlKey || event.altKey || event.metaKey) { - return; - } - window.hideAllModals(false); - addClass(getSettingsButton(), "rotate"); - event.preventDefault(); - // Sending request for the CSS and the JS files at the same time so it will - // hopefully be loaded when the JS will generate the settings content. - loadScript(getVar("static-root-path") + getVar("settings-js")); - // Pre-load all theme CSS files, so that switching feels seamless. - // - // When loading settings.html as a standalone page, the equivalent HTML is - // generated in context.rs. - setTimeout(() => { - const themes = getVar("themes").split(","); - for (const theme of themes) { - // if there are no themes, do nothing - // "".split(",") == [""] - if (theme !== "") { - preLoadCss(getVar("root-path") + theme + ".css"); - } + if (getSettingsButton()) { + getSettingsButton().onclick = event => { + if (event.ctrlKey || event.altKey || event.metaKey) { + return; } - }, 0); - }; + window.hideAllModals(false); + addClass(getSettingsButton(), "rotate"); + event.preventDefault(); + // Sending request for the CSS and the JS files at the same time so it will + // hopefully be loaded when the JS will generate the settings content. + loadScript(getVar("static-root-path") + getVar("settings-js")); + // Pre-load all theme CSS files, so that switching feels seamless. + // + // When loading settings.html as a standalone page, the equivalent HTML is + // generated in context.rs. + setTimeout(() => { + const themes = getVar("themes").split(","); + for (const theme of themes) { + // if there are no themes, do nothing + // "".split(",") == [""] + if (theme !== "") { + preLoadCss(getVar("root-path") + theme + ".css"); + } + } + }, 0); + }; + } window.searchState = { + rustdocToolbar: document.querySelector("rustdoc-toolbar"), loadingText: "Loading search results...", input: document.getElementsByClassName("search-input")[0], outputElement: () => { @@ -919,8 +938,7 @@ function preLoadCss(cssUrl) { e.open = true; } }); - innerToggle.title = "collapse all docs"; - innerToggle.children[0].innerText = "\u2212"; // "\u2212" is "−" minus sign + innerToggle.children[0].innerText = "Summary"; } function collapseAllDocs() { @@ -934,8 +952,7 @@ function preLoadCss(cssUrl) { e.open = false; } }); - innerToggle.title = "expand all docs"; - innerToggle.children[0].innerText = "+"; + innerToggle.children[0].innerText = "Show all"; } function toggleAllDocs() { @@ -986,7 +1003,13 @@ function preLoadCss(cssUrl) { }()); window.rustdoc_add_line_numbers_to_examples = () => { - onEachLazy(document.getElementsByClassName("rust-example-rendered"), x => { + if (document.querySelector(".rustdoc.src")) { + // We are in the source code page, nothing to be done here! + return; + } + onEachLazy(document.querySelectorAll( + ":not(.scraped-example) > .example-wrap > pre:not(.example-line-numbers)", + ), x => { const parent = x.parentNode; const line_numbers = parent.querySelectorAll(".example-line-numbers"); if (line_numbers.length > 0) { @@ -1005,12 +1028,8 @@ function preLoadCss(cssUrl) { }; window.rustdoc_remove_line_numbers_from_examples = () => { - onEachLazy(document.getElementsByClassName("rust-example-rendered"), x => { - const parent = x.parentNode; - const line_numbers = parent.querySelectorAll(".example-line-numbers"); - for (const node of line_numbers) { - parent.removeChild(node); - } + onEachLazy(document.querySelectorAll(".example-wrap > .example-line-numbers"), x => { + x.parentNode.removeChild(x); }); }; @@ -1328,7 +1347,13 @@ function preLoadCss(cssUrl) { } function helpBlurHandler(event) { - blurHandler(event, getHelpButton(), window.hidePopoverMenus); + if (!getHelpButton().contains(document.activeElement) && + !getHelpButton().contains(event.relatedTarget) && + !getSettingsButton().contains(document.activeElement) && + !getSettingsButton().contains(event.relatedTarget) + ) { + window.hidePopoverMenus(); + } } function buildHelpMenu() { @@ -1431,9 +1456,13 @@ href="https://doc.rust-lang.org/${channel}/rustdoc/read-documentation/search.htm * Hide all the popover menus. */ window.hidePopoverMenus = () => { - onEachLazy(document.querySelectorAll(".search-form .popover"), elem => { + onEachLazy(document.querySelectorAll("rustdoc-toolbar .popover"), elem => { elem.style.display = "none"; }); + const button = getHelpButton(); + if (button) { + removeClass(button, "help-open"); + } }; /** @@ -1458,7 +1487,9 @@ href="https://doc.rust-lang.org/${channel}/rustdoc/read-documentation/search.htm function showHelp() { // Prevent `blur` events from being dispatched as a result of closing // other modals. - getHelpButton().querySelector("a").focus(); + const button = getHelpButton(); + addClass(button, "help-open"); + button.querySelector("a").focus(); const menu = getHelpMenu(true); if (menu.style.display === "none") { window.hideAllModals(); @@ -1466,28 +1497,15 @@ href="https://doc.rust-lang.org/${channel}/rustdoc/read-documentation/search.htm } } + const helpLink = document.querySelector(`#${HELP_BUTTON_ID} > a`); if (isHelpPage) { - showHelp(); - document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click", event => { - // Already on the help page, make help button a no-op. - const target = event.target; - if (target.tagName !== "A" || - target.parentElement.id !== HELP_BUTTON_ID || - event.ctrlKey || - event.altKey || - event.metaKey) { - return; - } - event.preventDefault(); - }); - } else { - document.querySelector(`#${HELP_BUTTON_ID} > a`).addEventListener("click", event => { + buildHelpMenu(); + } else if (helpLink) { + helpLink.addEventListener("click", event => { // By default, have help button open docs in a popover. // If user clicks with a moderator, though, use default browser behavior, // probably opening in a new window or tab. - const target = event.target; - if (target.tagName !== "A" || - target.parentElement.id !== HELP_BUTTON_ID || + if (!helpLink.contains(helpLink) || event.ctrlKey || event.altKey || event.metaKey) { @@ -1810,14 +1828,11 @@ href="https://doc.rust-lang.org/${channel}/rustdoc/read-documentation/search.htm return; } but.onclick = () => { - const parent = but.parentElement; const path = []; - - onEach(parent.childNodes, child => { - if (child.tagName === "A") { - path.push(child.textContent); - } + onEachLazy(document.querySelectorAll(".rustdoc-breadcrumbs a"), a => { + path.push(a.textContent); }); + path.push(document.querySelector("title").textContent.split(" ")[0]); copyContentToClipboard(path.join("::")); copyButtonAnimation(but); diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index 4da0bbc787d9e..eed64d024c046 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -3597,15 +3597,16 @@ async function showResults(results, go_to_first, filterCrates) { let crates = ""; if (rawSearchIndex.size > 1) { - crates = " in 
"; for (const c of rawSearchIndex.keys()) { crates += ``; } - crates += "
"; + crates += ""; } - let output = `

Results${crates}

`; + let output = `
\ +

Results

${crates}
`; if (results.query.error !== null) { const error = results.query.error; error.forEach((value, index) => { @@ -3662,6 +3663,9 @@ async function showResults(results, go_to_first, filterCrates) { resultsElem.appendChild(ret_returned[0]); search.innerHTML = output; + if (searchState.rustdocToolbar) { + search.querySelector(".main-heading").appendChild(searchState.rustdocToolbar); + } const crateSearch = document.getElementById("crate-search"); if (crateSearch) { crateSearch.addEventListener("input", updateCrate); diff --git a/src/librustdoc/html/static/js/settings.js b/src/librustdoc/html/static/js/settings.js index c52a19ef98738..183663b94fc28 100644 --- a/src/librustdoc/html/static/js/settings.js +++ b/src/librustdoc/html/static/js/settings.js @@ -1,7 +1,7 @@ // Local js definitions: /* global getSettingValue, updateLocalStorage, updateTheme */ -/* global addClass, removeClass, onEach, onEachLazy, blurHandler */ -/* global MAIN_ID, getVar, getSettingsButton */ +/* global addClass, removeClass, onEach, onEachLazy */ +/* global MAIN_ID, getVar, getSettingsButton, getHelpButton */ "use strict"; @@ -267,15 +267,16 @@ } function settingsBlurHandler(event) { - blurHandler(event, getSettingsButton(), window.hidePopoverMenus); + if (!getHelpButton().contains(document.activeElement) && + !getHelpButton().contains(event.relatedTarget) && + !getSettingsButton().contains(document.activeElement) && + !getSettingsButton().contains(event.relatedTarget) + ) { + window.hidePopoverMenus(); + } } - if (isSettingsPage) { - // We replace the existing "onclick" callback to do nothing if clicked. - getSettingsButton().onclick = event => { - event.preventDefault(); - }; - } else { + if (!isSettingsPage) { // We replace the existing "onclick" callback. const settingsButton = getSettingsButton(); const settingsMenu = document.getElementById("settings"); diff --git a/src/librustdoc/html/static/js/storage.js b/src/librustdoc/html/static/js/storage.js index d75fb7a7fb5ab..d77804d045e36 100644 --- a/src/librustdoc/html/static/js/storage.js +++ b/src/librustdoc/html/static/js/storage.js @@ -274,16 +274,29 @@ class RustdocSearchElement extends HTMLElement { spellcheck="false" placeholder="Type ‘S’ or ‘/’ to search, ‘?’ for more options…" type="search"> -
- ? -
- `; } } window.customElements.define("rustdoc-search", RustdocSearchElement); +class RustdocToolbarElement extends HTMLElement { + constructor() { + super(); + } + connectedCallback() { + // Avoid replacing the children after they're already here. + if (this.firstElementChild) { + return; + } + const rootPath = getVar("root-path"); + this.innerHTML = ` +
+ Settings +
+
+ Help +
+ `; + } +} +window.customElements.define("rustdoc-toolbar", RustdocToolbarElement); diff --git a/src/librustdoc/html/templates/print_item.html b/src/librustdoc/html/templates/print_item.html index 76e770453b6ea..32ded1fbe424f 100644 --- a/src/librustdoc/html/templates/print_item.html +++ b/src/librustdoc/html/templates/print_item.html @@ -1,26 +1,33 @@
{# #} + {% if !path_components.is_empty() %} + + {% for (i, component) in path_components.iter().enumerate() %} + {% if i != 0 %} + :: + {% endif %} + {{component.name}} + {% endfor %} + + {% endif %}

{{typ}} - {# The breadcrumbs of the item path, like std::string #} - {% for component in path_components %} - {{component.name}}:: - {% endfor %} - {{name}} {# #} + + {{name}} + {# #} {# #}

{# #} - + {# #} + {% if !stability_since_raw.is_empty() %} - {{ stability_since_raw|safe +}} · {#+ #} + {{ stability_since_raw|safe +}} {% endif %} {% match src_href %} {% when Some with (href) %} - source · {#+ #} + {% if !stability_since_raw.is_empty() +%} · {%+ endif %} + source {#+ #} {% else %} {% endmatch %} - {# #} {# #}
{# #} diff --git a/src/librustdoc/html/templates/source.html b/src/librustdoc/html/templates/source.html index 60a47f1b5de7d..9daa0cf8ff688 100644 --- a/src/librustdoc/html/templates/source.html +++ b/src/librustdoc/html/templates/source.html @@ -1,4 +1,15 @@ -
+{% match file_path %} +{% when Some with ((path, name)) %} +
{# #} +

{# #} +
{{path}}/
+ {{name}} +

{# #} + {# #} +
+{% else %} +{% endmatch %} +
{# #} {# https://developers.google.com/search/docs/crawling-indexing/robots-meta-tag#data-nosnippet-attr Do not show "1 2 3 4 5 ..." in web search results. #}
diff --git a/src/librustdoc/html/tests.rs b/src/librustdoc/html/tests.rs
index 059f99c0c9e63..b568942bbcb9b 100644
--- a/src/librustdoc/html/tests.rs
+++ b/src/librustdoc/html/tests.rs
@@ -1,4 +1,4 @@
-use rustc_span::{sym, Symbol};
+use rustc_span::{Symbol, sym};
 
 use crate::html::format::href_relative_parts;
 
diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs
index 82ce619a19d9a..b411f9a1a52d0 100644
--- a/src/librustdoc/json/conversions.rs
+++ b/src/librustdoc/json/conversions.rs
@@ -19,8 +19,8 @@ use rustc_target::spec::abi::Abi as RustcAbi;
 use rustdoc_json_types::*;
 
 use crate::clean::{self, ItemId};
-use crate::formats::item_type::ItemType;
 use crate::formats::FormatRenderer;
+use crate::formats::item_type::ItemType;
 use crate::json::JsonRenderer;
 use crate::passes::collect_intra_doc_links::UrlFragment;
 
diff --git a/src/librustdoc/json/mod.rs b/src/librustdoc/json/mod.rs
index f30a34cdccf0e..7f82fb5c68658 100644
--- a/src/librustdoc/json/mod.rs
+++ b/src/librustdoc/json/mod.rs
@@ -8,8 +8,8 @@ mod conversions;
 mod import_finder;
 
 use std::cell::RefCell;
-use std::fs::{create_dir_all, File};
-use std::io::{stdout, BufWriter, Write};
+use std::fs::{File, create_dir_all};
+use std::io::{BufWriter, Write, stdout};
 use std::path::PathBuf;
 use std::rc::Rc;
 
@@ -24,14 +24,14 @@ use rustdoc_json_types as types;
 use rustdoc_json_types::FxHashMap;
 use tracing::{debug, trace};
 
-use crate::clean::types::{ExternalCrate, ExternalLocation};
 use crate::clean::ItemKind;
+use crate::clean::types::{ExternalCrate, ExternalLocation};
 use crate::config::RenderOptions;
 use crate::docfs::PathError;
 use crate::error::Error;
-use crate::formats::cache::Cache;
 use crate::formats::FormatRenderer;
-use crate::json::conversions::{id_from_item, id_from_item_default, IntoWithTcx};
+use crate::formats::cache::Cache;
+use crate::json::conversions::{IntoWithTcx, id_from_item, id_from_item_default};
 use crate::{clean, try_err};
 
 #[derive(Clone)]
@@ -253,14 +253,11 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
                 .iter()
                 .chain(&self.cache.external_paths)
                 .map(|(&k, &(ref path, kind))| {
-                    (
-                        id_from_item_default(k.into(), self.tcx),
-                        types::ItemSummary {
-                            crate_id: k.krate.as_u32(),
-                            path: path.iter().map(|s| s.to_string()).collect(),
-                            kind: kind.into_tcx(self.tcx),
-                        },
-                    )
+                    (id_from_item_default(k.into(), self.tcx), types::ItemSummary {
+                        crate_id: k.krate.as_u32(),
+                        path: path.iter().map(|s| s.to_string()).collect(),
+                        kind: kind.into_tcx(self.tcx),
+                    })
                 })
                 .collect(),
             external_crates: self
@@ -269,16 +266,13 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
                 .iter()
                 .map(|(crate_num, external_location)| {
                     let e = ExternalCrate { crate_num: *crate_num };
-                    (
-                        crate_num.as_u32(),
-                        types::ExternalCrate {
-                            name: e.name(self.tcx).to_string(),
-                            html_root_url: match external_location {
-                                ExternalLocation::Remote(s) => Some(s.clone()),
-                                _ => None,
-                            },
+                    (crate_num.as_u32(), types::ExternalCrate {
+                        name: e.name(self.tcx).to_string(),
+                        html_root_url: match external_location {
+                            ExternalLocation::Remote(s) => Some(s.clone()),
+                            _ => None,
                         },
-                    )
+                    })
                 })
                 .collect(),
             format_version: types::FORMAT_VERSION,
diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs
index 6649e1721a48b..dd75f4d7928ae 100644
--- a/src/librustdoc/lib.rs
+++ b/src/librustdoc/lib.rs
@@ -10,6 +10,7 @@
 #![feature(iter_intersperse)]
 #![feature(let_chains)]
 #![feature(never_type)]
+#![feature(os_str_display)]
 #![feature(round_char_boundary)]
 #![feature(test)]
 #![feature(type_alias_impl_trait)]
@@ -73,14 +74,14 @@ extern crate jemalloc_sys;
 use std::env::{self, VarError};
 use std::io::{self, IsTerminal};
 use std::process;
-use std::sync::atomic::AtomicBool;
 use std::sync::Arc;
+use std::sync::atomic::AtomicBool;
 
 use rustc_errors::{DiagCtxtHandle, ErrorGuaranteed, FatalError};
 use rustc_interface::interface;
 use rustc_middle::ty::TyCtxt;
-use rustc_session::config::{make_crate_type_option, ErrorOutputType, RustcOptGroup};
-use rustc_session::{getopts, EarlyDiagCtxt};
+use rustc_session::config::{ErrorOutputType, RustcOptGroup, make_crate_type_option};
+use rustc_session::{EarlyDiagCtxt, getopts};
 use tracing::info;
 
 use crate::clean::utils::DOC_RUST_LANG_ORG_CHANNEL;
diff --git a/src/librustdoc/lint.rs b/src/librustdoc/lint.rs
index 754ba58648df6..bdfdeeabc5a39 100644
--- a/src/librustdoc/lint.rs
+++ b/src/librustdoc/lint.rs
@@ -2,8 +2,8 @@ use std::sync::LazyLock as Lazy;
 
 use rustc_data_structures::fx::FxHashMap;
 use rustc_lint::LintStore;
-use rustc_lint_defs::{declare_tool_lint, Lint, LintId};
-use rustc_session::{lint, Session};
+use rustc_lint_defs::{Lint, LintId, declare_tool_lint};
+use rustc_session::{Session, lint};
 
 /// This function is used to setup the lint initialization. By default, in rustdoc, everything
 /// is "allowed". Depending if we run in test mode or not, we want some of them to be at their
diff --git a/src/librustdoc/markdown.rs b/src/librustdoc/markdown.rs
index 581ebbbe58d7c..978f96f38bedf 100644
--- a/src/librustdoc/markdown.rs
+++ b/src/librustdoc/markdown.rs
@@ -1,5 +1,5 @@
 use std::fmt::Write as _;
-use std::fs::{create_dir_all, read_to_string, File};
+use std::fs::{File, create_dir_all, read_to_string};
 use std::io::prelude::*;
 use std::path::Path;
 
diff --git a/src/librustdoc/passes/calculate_doc_coverage.rs b/src/librustdoc/passes/calculate_doc_coverage.rs
index 7391909406e36..15c0d77e7ba8b 100644
--- a/src/librustdoc/passes/calculate_doc_coverage.rs
+++ b/src/librustdoc/passes/calculate_doc_coverage.rs
@@ -13,9 +13,9 @@ use tracing::debug;
 
 use crate::clean;
 use crate::core::DocContext;
-use crate::html::markdown::{find_testable_code, ErrorCodes};
-use crate::passes::check_doc_test_visibility::{should_have_doc_example, Tests};
+use crate::html::markdown::{ErrorCodes, find_testable_code};
 use crate::passes::Pass;
+use crate::passes::check_doc_test_visibility::{Tests, should_have_doc_example};
 use crate::visit::DocVisitor;
 
 pub(crate) const CALCULATE_DOC_COVERAGE: Pass = Pass {
diff --git a/src/librustdoc/passes/check_doc_test_visibility.rs b/src/librustdoc/passes/check_doc_test_visibility.rs
index 733fd919e712b..52b2cd7774da4 100644
--- a/src/librustdoc/passes/check_doc_test_visibility.rs
+++ b/src/librustdoc/passes/check_doc_test_visibility.rs
@@ -15,7 +15,7 @@ use crate::clean;
 use crate::clean::utils::inherits_doc_hidden;
 use crate::clean::*;
 use crate::core::DocContext;
-use crate::html::markdown::{find_testable_code, ErrorCodes, Ignore, LangString, MdRelLine};
+use crate::html::markdown::{ErrorCodes, Ignore, LangString, MdRelLine, find_testable_code};
 use crate::visit::DocVisitor;
 
 pub(crate) const CHECK_DOC_TEST_VISIBILITY: Pass = Pass {
diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs
index 676c972529bea..29342dcac592b 100644
--- a/src/librustdoc/passes/collect_intra_doc_links.rs
+++ b/src/librustdoc/passes/collect_intra_doc_links.rs
@@ -14,25 +14,25 @@ use rustc_data_structures::intern::Interned;
 use rustc_errors::{Applicability, Diag, DiagMessage};
 use rustc_hir::def::Namespace::*;
 use rustc_hir::def::{DefKind, Namespace, PerNS};
-use rustc_hir::def_id::{DefId, CRATE_DEF_ID};
+use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
 use rustc_hir::{Mutability, Safety};
 use rustc_middle::ty::{Ty, TyCtxt};
 use rustc_middle::{bug, span_bug, ty};
 use rustc_resolve::rustdoc::{
-    has_primitive_or_keyword_docs, prepare_to_doc_link_resolution, source_span_for_markdown_range,
-    strip_generics_from_path, MalformedGenerics,
+    MalformedGenerics, has_primitive_or_keyword_docs, prepare_to_doc_link_resolution,
+    source_span_for_markdown_range, strip_generics_from_path,
 };
 use rustc_session::lint::Lint;
-use rustc_span::hygiene::MacroKind;
-use rustc_span::symbol::{sym, Ident, Symbol};
 use rustc_span::BytePos;
-use smallvec::{smallvec, SmallVec};
+use rustc_span::hygiene::MacroKind;
+use rustc_span::symbol::{Ident, Symbol, sym};
+use smallvec::{SmallVec, smallvec};
 use tracing::{debug, info, instrument, trace};
 
 use crate::clean::utils::find_nearest_parent_module;
 use crate::clean::{self, Crate, Item, ItemLink, PrimitiveType};
 use crate::core::DocContext;
-use crate::html::markdown::{markdown_links, MarkdownLink, MarkdownLinkRange};
+use crate::html::markdown::{MarkdownLink, MarkdownLinkRange, markdown_links};
 use crate::lint::{BROKEN_INTRA_DOC_LINKS, PRIVATE_INTRA_DOC_LINKS};
 use crate::passes::Pass;
 use crate::visit::DocVisitor;
@@ -608,7 +608,6 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
                 let mut assoc_items: Vec<_> = tcx
                     .inherent_impls(did)
                     .into_iter()
-                    .flatten()
                     .flat_map(|&imp| {
                         filter_assoc_items_by_name_and_namespace(
                             tcx,
diff --git a/src/librustdoc/passes/lint/bare_urls.rs b/src/librustdoc/passes/lint/bare_urls.rs
index bac0e07f1c108..1397eadb2884c 100644
--- a/src/librustdoc/passes/lint/bare_urls.rs
+++ b/src/librustdoc/passes/lint/bare_urls.rs
@@ -77,10 +77,9 @@ fn find_raw_urls(
     // For now, we only check "full" URLs (meaning, starting with "http://" or "https://").
     for match_ in URL_REGEX.find_iter(text) {
         let url_range = match_.range();
-        f(
-            cx,
-            "this URL is not a hyperlink",
-            Range { start: range.start + url_range.start, end: range.start + url_range.end },
-        );
+        f(cx, "this URL is not a hyperlink", Range {
+            start: range.start + url_range.start,
+            end: range.start + url_range.end,
+        });
     }
 }
diff --git a/src/librustdoc/passes/lint/check_code_block_syntax.rs b/src/librustdoc/passes/lint/check_code_block_syntax.rs
index 1b2431a629b94..848e70a7bdbab 100644
--- a/src/librustdoc/passes/lint/check_code_block_syntax.rs
+++ b/src/librustdoc/passes/lint/check_code_block_syntax.rs
@@ -2,14 +2,14 @@
 
 use rustc_data_structures::sync::{Lock, Lrc};
 use rustc_errors::emitter::Emitter;
-use rustc_errors::translation::{to_fluent_args, Translate};
+use rustc_errors::translation::{Translate, to_fluent_args};
 use rustc_errors::{Applicability, DiagCtxt, DiagInner, LazyFallbackBundle};
 use rustc_parse::{source_str_to_stream, unwrap_or_emit_fatal};
 use rustc_resolve::rustdoc::source_span_for_markdown_range;
 use rustc_session::parse::ParseSess;
 use rustc_span::hygiene::{AstPass, ExpnData, ExpnKind, LocalExpnId, Transparency};
 use rustc_span::source_map::{FilePathMapping, SourceMap};
-use rustc_span::{FileName, InnerSpan, DUMMY_SP};
+use rustc_span::{DUMMY_SP, FileName, InnerSpan};
 
 use crate::clean;
 use crate::core::DocContext;
diff --git a/src/librustdoc/passes/lint/redundant_explicit_links.rs b/src/librustdoc/passes/lint/redundant_explicit_links.rs
index 9c37e11349a32..f3599688454b2 100644
--- a/src/librustdoc/passes/lint/redundant_explicit_links.rs
+++ b/src/librustdoc/passes/lint/redundant_explicit_links.rs
@@ -5,15 +5,15 @@ use pulldown_cmark::{
 };
 use rustc_ast::NodeId;
 use rustc_errors::SuggestionStyle;
-use rustc_hir::def::{DefKind, DocLinkResMap, Namespace, Res};
 use rustc_hir::HirId;
+use rustc_hir::def::{DefKind, DocLinkResMap, Namespace, Res};
 use rustc_lint_defs::Applicability;
 use rustc_resolve::rustdoc::{prepare_to_doc_link_resolution, source_span_for_markdown_range};
-use rustc_span::def_id::DefId;
 use rustc_span::Symbol;
+use rustc_span::def_id::DefId;
 
-use crate::clean::utils::{find_nearest_parent_module, inherits_doc_hidden};
 use crate::clean::Item;
+use crate::clean::utils::{find_nearest_parent_module, inherits_doc_hidden};
 use crate::core::DocContext;
 use crate::html::markdown::main_body_opts;
 
diff --git a/src/librustdoc/passes/strip_aliased_non_local.rs b/src/librustdoc/passes/strip_aliased_non_local.rs
index 6078ab3652891..155ad5438314e 100644
--- a/src/librustdoc/passes/strip_aliased_non_local.rs
+++ b/src/librustdoc/passes/strip_aliased_non_local.rs
@@ -3,7 +3,7 @@ use rustc_middle::ty::{TyCtxt, Visibility};
 use crate::clean;
 use crate::clean::Item;
 use crate::core::DocContext;
-use crate::fold::{strip_item, DocFolder};
+use crate::fold::{DocFolder, strip_item};
 use crate::passes::Pass;
 
 pub(crate) const STRIP_ALIASED_NON_LOCAL: Pass = Pass {
diff --git a/src/librustdoc/passes/strip_hidden.rs b/src/librustdoc/passes/strip_hidden.rs
index 7c5fbac94e4fc..430f3d8a574c3 100644
--- a/src/librustdoc/passes/strip_hidden.rs
+++ b/src/librustdoc/passes/strip_hidden.rs
@@ -2,7 +2,7 @@
 
 use std::mem;
 
-use rustc_hir::def_id::{LocalDefId, CRATE_DEF_ID};
+use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
 use rustc_middle::ty::TyCtxt;
 use rustc_span::symbol::sym;
 use tracing::debug;
@@ -11,7 +11,7 @@ use crate::clean;
 use crate::clean::utils::inherits_doc_hidden;
 use crate::clean::{Item, ItemIdSet};
 use crate::core::DocContext;
-use crate::fold::{strip_item, DocFolder};
+use crate::fold::{DocFolder, strip_item};
 use crate::passes::{ImplStripper, Pass};
 
 pub(crate) const STRIP_HIDDEN: Pass = Pass {
diff --git a/src/librustdoc/passes/stripper.rs b/src/librustdoc/passes/stripper.rs
index a85428f8742a0..98b3446c26d23 100644
--- a/src/librustdoc/passes/stripper.rs
+++ b/src/librustdoc/passes/stripper.rs
@@ -8,7 +8,7 @@ use tracing::debug;
 
 use crate::clean::utils::inherits_doc_hidden;
 use crate::clean::{self, Item, ItemId, ItemIdSet};
-use crate::fold::{strip_item, DocFolder};
+use crate::fold::{DocFolder, strip_item};
 use crate::formats::cache::Cache;
 use crate::visit_lib::RustdocEffectiveVisibilities;
 
diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs
index ba172f865391d..2cf703f57c0b6 100644
--- a/src/librustdoc/visit_ast.rs
+++ b/src/librustdoc/visit_ast.rs
@@ -7,19 +7,19 @@ use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
 use rustc_hir as hir;
 use rustc_hir::def::{DefKind, Res};
 use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId, LocalDefIdSet};
-use rustc_hir::intravisit::{walk_body, walk_item, Visitor};
-use rustc_hir::{Node, CRATE_HIR_ID};
+use rustc_hir::intravisit::{Visitor, walk_body, walk_item};
+use rustc_hir::{CRATE_HIR_ID, Node};
 use rustc_middle::hir::nested_filter;
 use rustc_middle::ty::TyCtxt;
+use rustc_span::Span;
 use rustc_span::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
 use rustc_span::hygiene::MacroKind;
-use rustc_span::symbol::{kw, sym, Symbol};
-use rustc_span::Span;
+use rustc_span::symbol::{Symbol, kw, sym};
 use tracing::debug;
 
 use crate::clean::cfg::Cfg;
 use crate::clean::utils::{inherits_doc_hidden, should_ignore_res};
-use crate::clean::{reexport_chain, AttributesExt, NestedAttributesExt};
+use crate::clean::{AttributesExt, NestedAttributesExt, reexport_chain};
 use crate::core;
 
 /// This module is used to store stuff from Rust's AST in a more convenient
diff --git a/src/llvm-project b/src/llvm-project
index 4b8d29c585687..56997739365e8 160000
--- a/src/llvm-project
+++ b/src/llvm-project
@@ -1 +1 @@
-Subproject commit 4b8d29c585687084bbcf21471e04f279d1eddc0a
+Subproject commit 56997739365e8132cc817e00899480746c09d7d9
diff --git a/src/stage0 b/src/stage0
index 1a603931792c3..0d6542d2dd707 100644
--- a/src/stage0
+++ b/src/stage0
@@ -14,456 +14,456 @@ nightly_branch=master
 # All changes below this comment will be overridden the next time the
 # tool is executed.
             
-compiler_date=2024-09-04
+compiler_date=2024-09-22
 compiler_version=beta
-rustfmt_date=2024-09-04
+rustfmt_date=2024-09-22
 rustfmt_version=nightly
 
-dist/2024-09-04/rustc-beta-aarch64-apple-darwin.tar.gz=cb6487c102a7c5822be2236d79a2c4737b0ff284931c61607518a0de8d300abf
-dist/2024-09-04/rustc-beta-aarch64-apple-darwin.tar.xz=2556c7c07811195e94639f6d6556a0f49f3c267e0e3bfc44b1fdc555aac1ffe5
-dist/2024-09-04/rustc-beta-aarch64-pc-windows-msvc.tar.gz=c207a307bf10a50e2884f4d9408528a22703e1010dd921459541ee11aecc2405
-dist/2024-09-04/rustc-beta-aarch64-pc-windows-msvc.tar.xz=d6f99991029db32be7527dbe1a6ae840600db6d7497123156e6672f7a0e83aa2
-dist/2024-09-04/rustc-beta-aarch64-unknown-linux-gnu.tar.gz=b57cb4d25045e23f897078216776f244a73498ea89240077bda7a84c31c2f4fe
-dist/2024-09-04/rustc-beta-aarch64-unknown-linux-gnu.tar.xz=2c2b95c852114d7b18c3db13234ac56f933b70c3cf8b5ac9fce65415434961fe
-dist/2024-09-04/rustc-beta-aarch64-unknown-linux-musl.tar.gz=1f216d67bcd5d1e011bd2c6c69b6791c94e29cf7da3ab7dea82ff71a911e149b
-dist/2024-09-04/rustc-beta-aarch64-unknown-linux-musl.tar.xz=86abb27afb03e347abff65e4e34f1ec2e943af14f04f8cd9dd8666338147562d
-dist/2024-09-04/rustc-beta-arm-unknown-linux-gnueabi.tar.gz=842754febca1a5c6f7ccacf231621ba4578d72718a950ddedbf07a73594fa55f
-dist/2024-09-04/rustc-beta-arm-unknown-linux-gnueabi.tar.xz=3094887ecd5e3432e1ada0bba4a425213215c50680dc30d0c1d15ffda5bc62a0
-dist/2024-09-04/rustc-beta-arm-unknown-linux-gnueabihf.tar.gz=27192e3423f2b580d7927ae788cf778ff9c092e2eb7cdd5d16b41aa94d2bf03c
-dist/2024-09-04/rustc-beta-arm-unknown-linux-gnueabihf.tar.xz=e57767bd767964d51533e2310f177827842bf49176895280b3de3860caf351ab
-dist/2024-09-04/rustc-beta-armv7-unknown-linux-gnueabihf.tar.gz=b639bfce72277714769d36efab294ef3578573b93037160be7dff9f4a6e6b5ef
-dist/2024-09-04/rustc-beta-armv7-unknown-linux-gnueabihf.tar.xz=fce2b931641d51e88eb3e34d60bebe75384c1981654937b16f1333438d8b0696
-dist/2024-09-04/rustc-beta-i686-pc-windows-gnu.tar.gz=b58f7013b41044260ab2f9456940d9ce017dcfea06059fae8a672664f8ba00df
-dist/2024-09-04/rustc-beta-i686-pc-windows-gnu.tar.xz=c91958645f3c4cd562a5eb800ddb843aabfa2f067f5659313fdedeb270935bf8
-dist/2024-09-04/rustc-beta-i686-pc-windows-msvc.tar.gz=9a5075768fe2d42195c639d8c1066a020b573eae24c0c63e9a8876b78c39d673
-dist/2024-09-04/rustc-beta-i686-pc-windows-msvc.tar.xz=e76c27a8892a5b7a74c4d18d10c745af226711dbf62450378a3034a706624ce1
-dist/2024-09-04/rustc-beta-i686-unknown-linux-gnu.tar.gz=c10ffb2db62b113af1feab8625f1d88d31c1d4a4246d00e19a3588c9f69c0164
-dist/2024-09-04/rustc-beta-i686-unknown-linux-gnu.tar.xz=0496fbfa32d6c22929fe94ae5dcaabc47d31d7482f0fe6748ef7b7eb7443b775
-dist/2024-09-04/rustc-beta-loongarch64-unknown-linux-gnu.tar.gz=64b55368e8044ea44588c98f1529f46d65f7607ebf2fa2d50785abecfb37c188
-dist/2024-09-04/rustc-beta-loongarch64-unknown-linux-gnu.tar.xz=e03528ee7e4e92d666199ebcdde7d10f1d0fbeb2766217fd95f98da93bc361d0
-dist/2024-09-04/rustc-beta-loongarch64-unknown-linux-musl.tar.gz=eeb913008ecfbaaa76b7690b2e68bd1e70efc1afda19f44a1aa551a76e4b536a
-dist/2024-09-04/rustc-beta-loongarch64-unknown-linux-musl.tar.xz=c94c3545fa2a491763b1e593419034294c57a3df2ca8064db0b11d2e82e76c85
-dist/2024-09-04/rustc-beta-powerpc-unknown-linux-gnu.tar.gz=54c97827079aa7646cf206517f603487f4634ab1a17f2a7882b0cd3d6ffae8db
-dist/2024-09-04/rustc-beta-powerpc-unknown-linux-gnu.tar.xz=ee98a0e07989de836ff8ff4e768c6f0f13aa15150d1b59543297f31b2768a5fc
-dist/2024-09-04/rustc-beta-powerpc64-unknown-linux-gnu.tar.gz=a0fcd0f7af5b05a22d9be0abb6f3aa44c028c2606195163d2ad4b0352455ed1f
-dist/2024-09-04/rustc-beta-powerpc64-unknown-linux-gnu.tar.xz=cf35d480a6c0b439d29baacc4ee4087c4d7b5c1b4050302f3146f0bdbffcd472
-dist/2024-09-04/rustc-beta-powerpc64le-unknown-linux-gnu.tar.gz=ef19ce4d791b1caad30bc5af9e30494161f343d936a3300eb0d7c5e8f37db441
-dist/2024-09-04/rustc-beta-powerpc64le-unknown-linux-gnu.tar.xz=12adfd58c851d1f7bb23c5698abf6dffa2c26348df55fbb518c27497f7ebdf17
-dist/2024-09-04/rustc-beta-riscv64gc-unknown-linux-gnu.tar.gz=818151529f1e445f9202d0092f09f02818a2c52ad6814a89b2bbfcb0227c5202
-dist/2024-09-04/rustc-beta-riscv64gc-unknown-linux-gnu.tar.xz=e195d07d37699d860ce97422bba7f68166292103cedf4932b3ba8c0d9fa7e186
-dist/2024-09-04/rustc-beta-s390x-unknown-linux-gnu.tar.gz=d4a73ddd7eafdffe7f23720a7202f48676ae0bc49248d3a455c997d718730c5f
-dist/2024-09-04/rustc-beta-s390x-unknown-linux-gnu.tar.xz=475bb6e51f37fc769480345982e14afeee099cdf769773d0d0215d01fc77ce41
-dist/2024-09-04/rustc-beta-x86_64-apple-darwin.tar.gz=c061d06da7d4a283136d8e80f307c1ef4157739898776f5579b8d92980be0775
-dist/2024-09-04/rustc-beta-x86_64-apple-darwin.tar.xz=330b580c90ace563c96db64f639668284d8ede835870acf76b106d4c4913f476
-dist/2024-09-04/rustc-beta-x86_64-pc-windows-gnu.tar.gz=27f9e3c2e9380c689ab0c5e8438f1969261a30445e9b2d38efa9417fba1f4ea2
-dist/2024-09-04/rustc-beta-x86_64-pc-windows-gnu.tar.xz=62fc92dac7be442dcf306ae1baef471447b80a6a221502bf7b14b249dd599db7
-dist/2024-09-04/rustc-beta-x86_64-pc-windows-msvc.tar.gz=c52202bf41aafb517959e01cac2e4bbb53144aa0164f9b31e7b9db0af32be6c6
-dist/2024-09-04/rustc-beta-x86_64-pc-windows-msvc.tar.xz=24db84f0de7573812fe36fed5653fc117c80fc35b02a9340f746ded6a11d3bc0
-dist/2024-09-04/rustc-beta-x86_64-unknown-freebsd.tar.gz=406f8a37572376fec7563664043b4fc3b0e7a48c738b6ef862da3fc41f33b1d3
-dist/2024-09-04/rustc-beta-x86_64-unknown-freebsd.tar.xz=93fa021ca3973a52cbccd51771536e2b9a355eae4f4ab95c7168f4af79e96d4e
-dist/2024-09-04/rustc-beta-x86_64-unknown-illumos.tar.gz=a2a5942342b2f5dc7a196500210075ac695f106a18fd487a3c694847013454f3
-dist/2024-09-04/rustc-beta-x86_64-unknown-illumos.tar.xz=c8b63f35f30bb1d6adb49834b3a42dfc07c27042e8411f1b4777adced6193298
-dist/2024-09-04/rustc-beta-x86_64-unknown-linux-gnu.tar.gz=145c5d6e0edb688dbe59f9c638959e11718e0bdc625db76bac1d2836efd9f116
-dist/2024-09-04/rustc-beta-x86_64-unknown-linux-gnu.tar.xz=82845313e17067dac361eada63fdf2479fc177e8aa97aba5cb40a50861e276bc
-dist/2024-09-04/rustc-beta-x86_64-unknown-linux-musl.tar.gz=8351011105a5a338adbd2433ff5aa24cd038a67c0f0d040e4b92926d4aecd28e
-dist/2024-09-04/rustc-beta-x86_64-unknown-linux-musl.tar.xz=b2a972069142d5fdab775fd7709d4bc85b1c2c4167e9c455d2ef1b72cc207fd1
-dist/2024-09-04/rustc-beta-x86_64-unknown-netbsd.tar.gz=327501931ce36eb5613e5e77fb5356ff24f60078516473cd7f664bc970aee994
-dist/2024-09-04/rustc-beta-x86_64-unknown-netbsd.tar.xz=6d940ec725fa4931c914c291977f63828fe71e9763a3b8195dda668541c9122f
-dist/2024-09-04/rust-std-beta-aarch64-apple-darwin.tar.gz=9bf325e98fa60fcb7d4f09b796f2fe0e7e7c54e83ffba6d5cf30776a0346972d
-dist/2024-09-04/rust-std-beta-aarch64-apple-darwin.tar.xz=45d632045f5e3f8150d82fdc5163aea1d5ad785cd16da2d46293581b09bda895
-dist/2024-09-04/rust-std-beta-aarch64-apple-ios.tar.gz=c42f808164d79e023dc4186e47a6032c0877536a0c9459f3e871c66c129b0f75
-dist/2024-09-04/rust-std-beta-aarch64-apple-ios.tar.xz=9bbe6ae21530fb0555472f9a540b7791d5dce059439608d797507057199e696e
-dist/2024-09-04/rust-std-beta-aarch64-apple-ios-macabi.tar.gz=ae8005ea419f9f19be0c2603529d8801dc77e5344c72c1bd42eed81046fe5113
-dist/2024-09-04/rust-std-beta-aarch64-apple-ios-macabi.tar.xz=0053948699aba18b2bee7473f335940573aaf4bad6aabb00f28f2a335d280dab
-dist/2024-09-04/rust-std-beta-aarch64-apple-ios-sim.tar.gz=5adc7721f8f7fc0537b11a28ee2df6d90b96222a07590c84fab4dbefe33087d1
-dist/2024-09-04/rust-std-beta-aarch64-apple-ios-sim.tar.xz=4f3a9b61500ef3a38961288784c61a520baabfa597e997195007e0e229d1e4bf
-dist/2024-09-04/rust-std-beta-aarch64-linux-android.tar.gz=7192a628d6605b437a7203c18d48ac9a5af4879674117e9aebafb5029a10e069
-dist/2024-09-04/rust-std-beta-aarch64-linux-android.tar.xz=845177bda3220a534b20c66cda3bf27b0681c2977dfbcedeaf41022bc518f832
-dist/2024-09-04/rust-std-beta-aarch64-pc-windows-gnullvm.tar.gz=1a0ced7e1fbcdd38fcb33f1753f3af8b23f075d4ce38c3d1256ba142ddf80a47
-dist/2024-09-04/rust-std-beta-aarch64-pc-windows-gnullvm.tar.xz=75272f629adfaacb58c511163ae9b73714fe3f60d5e39b4cd996a42226626518
-dist/2024-09-04/rust-std-beta-aarch64-pc-windows-msvc.tar.gz=3b19e6dca8515f28a2325d7cf2f098e82e194d4418fce7c3caa94c9c08023646
-dist/2024-09-04/rust-std-beta-aarch64-pc-windows-msvc.tar.xz=138e8e1a85efb4f66ec878db18dfa48681f3045589c7b9a749afd0104dafd278
-dist/2024-09-04/rust-std-beta-aarch64-unknown-fuchsia.tar.gz=6da128ca58f46d2608c4d9630c09de263b853f9fe8b6fa41def0749e99a128e0
-dist/2024-09-04/rust-std-beta-aarch64-unknown-fuchsia.tar.xz=67a2c04a9f4947b4c313220150521f494364c5e589ff23a4584fa60b924ae095
-dist/2024-09-04/rust-std-beta-aarch64-unknown-linux-gnu.tar.gz=85ccd5a6e81caa63d4d4cfe55eead8a3829a5636d41f7640ea393bf7652eec28
-dist/2024-09-04/rust-std-beta-aarch64-unknown-linux-gnu.tar.xz=fb91518e70808c659f6f078c0094ca471e4e4f5d81c29c1bdc8907f6bdffc64f
-dist/2024-09-04/rust-std-beta-aarch64-unknown-linux-musl.tar.gz=410b24f1372f84d60804b4bcf20fa2025adaee3c56ab7dabda1e320809acafdb
-dist/2024-09-04/rust-std-beta-aarch64-unknown-linux-musl.tar.xz=64d7fa38af8a1c38e42bc9b9ab909f476d3388b7d02a21ba92519145cb3a3df8
-dist/2024-09-04/rust-std-beta-aarch64-unknown-linux-ohos.tar.gz=f4722b2a656d4f87bd13d4c8da6116e993e916114c55a2fd1a588e51dfde4ab0
-dist/2024-09-04/rust-std-beta-aarch64-unknown-linux-ohos.tar.xz=cb9150701f21de444addcdc9a53c83eeed3aaa3bc447e8f6358825a2f889bff2
-dist/2024-09-04/rust-std-beta-aarch64-unknown-none.tar.gz=26cf0407f17db7645fc1a4051d08246f1325b17941dd5139cb69b782498aa043
-dist/2024-09-04/rust-std-beta-aarch64-unknown-none.tar.xz=9dcdfd018e2ca6f21d0689adb152917a8695c2f14c4f6a53a5b52280219c2540
-dist/2024-09-04/rust-std-beta-aarch64-unknown-none-softfloat.tar.gz=1d1e555bb8af601d8df16b80dd263391a4c0805e1203c618fb370de1911a5a17
-dist/2024-09-04/rust-std-beta-aarch64-unknown-none-softfloat.tar.xz=078d88a6d4882696b3764d10dbd10e0d756752255096690e895903cd83265c70
-dist/2024-09-04/rust-std-beta-aarch64-unknown-uefi.tar.gz=5933f618e5c99e06c8556871a85016eba58f6de1056468a1ad47823105908fba
-dist/2024-09-04/rust-std-beta-aarch64-unknown-uefi.tar.xz=322f61ff7a6f6b261bbb9c592f50a39fa179c1f870d911a57b2afda7d7b2d196
-dist/2024-09-04/rust-std-beta-arm-linux-androideabi.tar.gz=e66bc47a75e12569032c81f6c950513e3fc78cf75e496e9873792b4c83f3dca1
-dist/2024-09-04/rust-std-beta-arm-linux-androideabi.tar.xz=9a84da40c9e5fb55e1ebad0dc9b724fe9d71d86bea0d2227315590f290fdce13
-dist/2024-09-04/rust-std-beta-arm-unknown-linux-gnueabi.tar.gz=3e8b535ec051eaaf63490649b1258ae64f1786abca6967bdc3eb6c6da96a4d81
-dist/2024-09-04/rust-std-beta-arm-unknown-linux-gnueabi.tar.xz=4936561a884b3b725a9b78651ea05a36da5e643be4e574416e12ba1c1e5f37d9
-dist/2024-09-04/rust-std-beta-arm-unknown-linux-gnueabihf.tar.gz=00eb51ffccdac33a39da37878104dded2c5efa01da5adf8bd932a0d9fb49d17b
-dist/2024-09-04/rust-std-beta-arm-unknown-linux-gnueabihf.tar.xz=3eb187c4a6f416672a8a36997aca5f04bab9ec6aee3a0d1f4ad5a0ed950605c3
-dist/2024-09-04/rust-std-beta-arm-unknown-linux-musleabi.tar.gz=66752ad65876dad43c19973f8967a098236f2605d2aa82df5b0f040247e049c3
-dist/2024-09-04/rust-std-beta-arm-unknown-linux-musleabi.tar.xz=f508b8c7956209c87259b38bebe5576ca8a5662a4d4747941082dd39d991610e
-dist/2024-09-04/rust-std-beta-arm-unknown-linux-musleabihf.tar.gz=926f2839c6627c822aa9f494e99030873987b6fca66364cc12ba468928a93b9c
-dist/2024-09-04/rust-std-beta-arm-unknown-linux-musleabihf.tar.xz=e2be0999ea8df01c1029b0976861162c9c60e41a87b4097345f2c5822777ee2b
-dist/2024-09-04/rust-std-beta-arm64ec-pc-windows-msvc.tar.gz=ec912c9e372cd0ae1a754305f0645580cf40f9742c4cbcc54952e613d47f595e
-dist/2024-09-04/rust-std-beta-arm64ec-pc-windows-msvc.tar.xz=f86091e5d806a9b4efa388e036ee69fa63fca68feca174c6670cd04966e2725f
-dist/2024-09-04/rust-std-beta-armebv7r-none-eabi.tar.gz=d51aa780c5df5b8b2e1fbbe97f79914ed083ea13528c43cca797ab8931a418d2
-dist/2024-09-04/rust-std-beta-armebv7r-none-eabi.tar.xz=19cbb2d1d8a6a3a33669da9fab7eb48f78f0682d777d2c2f188daf6d91895bc7
-dist/2024-09-04/rust-std-beta-armebv7r-none-eabihf.tar.gz=a1ae798b4eaf206510c33d5af1d4c99ed553fce89413449a5f82d5b80a2558aa
-dist/2024-09-04/rust-std-beta-armebv7r-none-eabihf.tar.xz=a0cb421635b927e5b255238658c9f9f5a0b2da60e05c993ecbda35af9318d6bc
-dist/2024-09-04/rust-std-beta-armv5te-unknown-linux-gnueabi.tar.gz=5f9995804004211baefab1d230089a5719bce40b632bd3380044142a89ae5f2d
-dist/2024-09-04/rust-std-beta-armv5te-unknown-linux-gnueabi.tar.xz=66f410541f2f53d44b2a2931b10a229c8143d6e9caabadea2df40704aad71854
-dist/2024-09-04/rust-std-beta-armv5te-unknown-linux-musleabi.tar.gz=64b62816adc9574f6961832a4c469e1103057ed553a4c42796e3af4962dc694a
-dist/2024-09-04/rust-std-beta-armv5te-unknown-linux-musleabi.tar.xz=3c0b3741af7f9b50d041dd52fe86fb4144c295632a6eba0197e77ac4ca94ab27
-dist/2024-09-04/rust-std-beta-armv7-linux-androideabi.tar.gz=aa3d37e6fc483c798a9debecf2ae7609609d0560baebb90733582b9bee15c493
-dist/2024-09-04/rust-std-beta-armv7-linux-androideabi.tar.xz=ed88cf7c141efd01eceb81b3b85e4eef38f559d8652d2fc4bf3395f4e3d2ef48
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-gnueabi.tar.gz=f8b34e2dd9bb5b2ea008bf6a69944da389d8d086a1ece57c1572c749717f4df8
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-gnueabi.tar.xz=7ae6076c42fecf7b92305af4220abd3d724d49d96def617a67db1ef298b74bb5
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-gnueabihf.tar.gz=4e13553b0288f4cd046372c080f4968a2b69bcb489f6929e98e72682b601d4cc
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-gnueabihf.tar.xz=dbaeb0445cfc110d7879a23ea7c4034cebb4158cd9781d8719f51864356a15d4
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-musleabi.tar.gz=164fa06abffc38aaf81c86aeb50fde51c96d713bb78d759a6f7e668c7967bdfb
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-musleabi.tar.xz=2ec4d5e339593555d02ea738ae1815e27d108fce5faeffd503308780c80a1a8d
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-musleabihf.tar.gz=36a09d9287c9d89b3946dc6aea2ce846e754ca2b07b667035f62e8d00c81587c
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-musleabihf.tar.xz=573316d483a27930bd1423ae8c1f2624dba141865150a41a5be317cc53fd850a
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-ohos.tar.gz=487feddaa3b11ad15b544e3338f4dfeb1f5297ce5d851dec1df36eee7bc016a2
-dist/2024-09-04/rust-std-beta-armv7-unknown-linux-ohos.tar.xz=866f612bc4fce03e851eb0b370282b35b066018c2b2467d265cbdde4bcc8afbd
-dist/2024-09-04/rust-std-beta-armv7a-none-eabi.tar.gz=3b2f1fefd2d97006264e5ce50839c8c22e9f6553f639e95c8bcc5bd01c54bead
-dist/2024-09-04/rust-std-beta-armv7a-none-eabi.tar.xz=55294ba0b8da663399c427b57157f4a3e43b117c77e011801410a9bfb62584a0
-dist/2024-09-04/rust-std-beta-armv7r-none-eabi.tar.gz=60ef291da36a614ddfd38c8bac0519113dc1203603181ba3a581df074fb62f07
-dist/2024-09-04/rust-std-beta-armv7r-none-eabi.tar.xz=6dde05a2b3a57ae340f699f959e7032bb6e53cf7e1ea24bf1dd88766dba2dcdf
-dist/2024-09-04/rust-std-beta-armv7r-none-eabihf.tar.gz=cc2ae41c8c8ee69f26eb55a033e5c6c23ec1e968aaa4c2e03357b62056176725
-dist/2024-09-04/rust-std-beta-armv7r-none-eabihf.tar.xz=dc7d1e0637369b0a32f8730a771e4b059ce45131b51beb276de8c03e153834b5
-dist/2024-09-04/rust-std-beta-i586-pc-windows-msvc.tar.gz=d6ce6f7d1412c1e0ec60a09c9db3d9bcbd0075617dd1756fa82e93d3df0ef8e4
-dist/2024-09-04/rust-std-beta-i586-pc-windows-msvc.tar.xz=60ff61cf60ac63a6c1ce3c6558351e873968ea1f812afdc7516ae5d19d85e54e
-dist/2024-09-04/rust-std-beta-i586-unknown-linux-gnu.tar.gz=4f5204d8d51ecbf0768419076c94dde6e0c776a9403e3e108866eec3faa68d06
-dist/2024-09-04/rust-std-beta-i586-unknown-linux-gnu.tar.xz=3ba0815668b11d682a54bfc4731aca5f7a821d77ab8ac32f9922bf9d684d72b4
-dist/2024-09-04/rust-std-beta-i586-unknown-linux-musl.tar.gz=ac1094f3e22829c4e3e27a91dae48f84ab2bca4373a6e851bdee807887e145ab
-dist/2024-09-04/rust-std-beta-i586-unknown-linux-musl.tar.xz=6547347750eefb619ac15256a3e1ef09c3ee633d73b23aae239cfcf4261f0d16
-dist/2024-09-04/rust-std-beta-i686-linux-android.tar.gz=af1e7557a1008392a0c2eee4f9e6b26ca56b21be2838ff4a4e3784363b1c3423
-dist/2024-09-04/rust-std-beta-i686-linux-android.tar.xz=b5d395b1c6994447b3358058aaf2219f952cb9fe6d5df0d8a533b9c2ed84134c
-dist/2024-09-04/rust-std-beta-i686-pc-windows-gnu.tar.gz=a0c0535feb405bf313035cdbc690fd80c18e1975ef0da2fcaeaeab66eb8ee461
-dist/2024-09-04/rust-std-beta-i686-pc-windows-gnu.tar.xz=85b08876c40d2bc1b44bf7d64319d1dae3af2dbd75cf3e3f37b3ea20bd21209c
-dist/2024-09-04/rust-std-beta-i686-pc-windows-gnullvm.tar.gz=60c37fb7de68381a3665728eb6a74ea017d81e2dcae11acf683cebcef7267487
-dist/2024-09-04/rust-std-beta-i686-pc-windows-gnullvm.tar.xz=a97edc7de6792da17dbcb6b5a67da4aa79784921c2b160185b2c8a806bd4945b
-dist/2024-09-04/rust-std-beta-i686-pc-windows-msvc.tar.gz=ea25bfabaad2bc02b0d37672bdf9357f317fd27031ef6039460e25c066917b11
-dist/2024-09-04/rust-std-beta-i686-pc-windows-msvc.tar.xz=ef65a47d79945d6375347c9889c3ec3250d4635e1918689cc1f992b7daf4f547
-dist/2024-09-04/rust-std-beta-i686-unknown-freebsd.tar.gz=5c4ca0b3bca99fc468bc7ada8ef1d202e9be8ba9808298485654ceab545538e8
-dist/2024-09-04/rust-std-beta-i686-unknown-freebsd.tar.xz=59ffa74e46e807cacd4ea0a1b16ce0ec7152c4458ad9f86feea82162b1c53da6
-dist/2024-09-04/rust-std-beta-i686-unknown-linux-gnu.tar.gz=dc535c0b1fe81cc6d1bbd8fecbc0625cb85c44a6f10dd8641fb8ae88083febc5
-dist/2024-09-04/rust-std-beta-i686-unknown-linux-gnu.tar.xz=624ce72e0b60a7b0d9a06b6925fd0e9a3bd50d9d7ed59db4a16145ff5381c232
-dist/2024-09-04/rust-std-beta-i686-unknown-linux-musl.tar.gz=6d43cf9f2dc34205616b17eafa8bf28f951de538e6d80ab4993d9b840b72ba49
-dist/2024-09-04/rust-std-beta-i686-unknown-linux-musl.tar.xz=b397f611d609167ddf2b5699d7cfef9da9c6c78988c7ca2c32b2f81f6640eba6
-dist/2024-09-04/rust-std-beta-i686-unknown-uefi.tar.gz=878584e638e92902521231a4b578ae1828d1e06093104b6ceca9a22a6c05939d
-dist/2024-09-04/rust-std-beta-i686-unknown-uefi.tar.xz=2806b9124d6145b65bfefc2e72a8ec3f745d3972904b7a2546bcaf649028a332
-dist/2024-09-04/rust-std-beta-loongarch64-unknown-linux-gnu.tar.gz=eb2792e0b57b36ed03762eff460bfbb7d8b28aaa309702e7e6414eba0a7d0e63
-dist/2024-09-04/rust-std-beta-loongarch64-unknown-linux-gnu.tar.xz=c36d7526ad190b15a41a1695be4b813d09d649395b1e91bf6dadc336333c690d
-dist/2024-09-04/rust-std-beta-loongarch64-unknown-linux-musl.tar.gz=d891dc7b3c1d05a1c245076a6656f2ad33cba79073e36e8e1eb11ab0c0045cdd
-dist/2024-09-04/rust-std-beta-loongarch64-unknown-linux-musl.tar.xz=6dbbd097bba35b9f0465a6d6b4d19d8b4700dbeecc1b0919aa99c72cad564a0a
-dist/2024-09-04/rust-std-beta-loongarch64-unknown-none.tar.gz=54da489ea59169e39b50d0be0221e20cf03bdad413854e0f35f66c323bf4e88e
-dist/2024-09-04/rust-std-beta-loongarch64-unknown-none.tar.xz=4c360c531107de92b695dd389514dc0af053a04d28c566a06a25e467d5ab548f
-dist/2024-09-04/rust-std-beta-loongarch64-unknown-none-softfloat.tar.gz=7ce834710452cb0569cdd234698f647db87e774d3e964493e17017a81a417aba
-dist/2024-09-04/rust-std-beta-loongarch64-unknown-none-softfloat.tar.xz=3e554450f5107e02335fa14fc7c7a2a3d4718741001f0f4e43984a3c0841ddf4
-dist/2024-09-04/rust-std-beta-nvptx64-nvidia-cuda.tar.gz=e8c8607e58379162fe0ec072bd544c97d73619df88eb56aeccdf2ebd5357f1b3
-dist/2024-09-04/rust-std-beta-nvptx64-nvidia-cuda.tar.xz=1dd759c92e6c1f67d5b697e1034b4962434a17211383741d0cc71acda9fcf209
-dist/2024-09-04/rust-std-beta-powerpc-unknown-linux-gnu.tar.gz=83907d49dd4cf4f73c1295571400c9761bae7a3b2447c140a358a07710e28f93
-dist/2024-09-04/rust-std-beta-powerpc-unknown-linux-gnu.tar.xz=f1ec605497fb3d7d364f2dfb7bc5c4898940518c1712b0271372ee608d61fd34
-dist/2024-09-04/rust-std-beta-powerpc64-unknown-linux-gnu.tar.gz=ac2b94c0f76c1f23be43880c01aab0a45d47e48a6c53b5dcfcf4e9507aa481e9
-dist/2024-09-04/rust-std-beta-powerpc64-unknown-linux-gnu.tar.xz=129ff2031d8ae69c34e944516bb47e093a2f2b47972bd401337fc1dc8b0f2b93
-dist/2024-09-04/rust-std-beta-powerpc64le-unknown-linux-gnu.tar.gz=2dd17129ca857bfa97d8ae3429984f80a116cc9f967809b7e5bdcc5845398a30
-dist/2024-09-04/rust-std-beta-powerpc64le-unknown-linux-gnu.tar.xz=06426a601db3dfc60f01b03bc201d21cc6bdc9b633a564e7025518decb91fea1
-dist/2024-09-04/rust-std-beta-riscv32i-unknown-none-elf.tar.gz=80bcbeed550e6ac30e9826cb801be5206d7937d2d940fca2d40ddabec62e2111
-dist/2024-09-04/rust-std-beta-riscv32i-unknown-none-elf.tar.xz=2994ee26443be51f11e8cc6e66aa2ee38e7f9440efbe0aa6aa2c513b3fe07f33
-dist/2024-09-04/rust-std-beta-riscv32im-unknown-none-elf.tar.gz=09f2b6dd18ebff39077a252e0d4b63b3557a49fb3a4f218f50f127aa44f653ec
-dist/2024-09-04/rust-std-beta-riscv32im-unknown-none-elf.tar.xz=156c0ef4be19442b8f59269815e570faa464332ccd2a8db91828eff9ab702ea7
-dist/2024-09-04/rust-std-beta-riscv32imac-unknown-none-elf.tar.gz=037ceaaf4b1356f72d16f2a6c0dfe50b1df8a82743da79262b020712ffcfb7ff
-dist/2024-09-04/rust-std-beta-riscv32imac-unknown-none-elf.tar.xz=a6e6f00d5df339ac19ebe2c661a5a4ec9b648328767db864b3db1bde0b330bfe
-dist/2024-09-04/rust-std-beta-riscv32imafc-unknown-none-elf.tar.gz=6da55a90ba454e77dd2c90d5d5c5ed833befab415ba65adf27d8e36645b189c0
-dist/2024-09-04/rust-std-beta-riscv32imafc-unknown-none-elf.tar.xz=9213accb8bc2b3a678c3b3cb4300015b1cc52798157e3898d99699b96bac486d
-dist/2024-09-04/rust-std-beta-riscv32imc-unknown-none-elf.tar.gz=5504f5fe7b45570922f7901476b8ac1eb28e9a7643bf5ace75bb368a644a05f8
-dist/2024-09-04/rust-std-beta-riscv32imc-unknown-none-elf.tar.xz=50109eb03c075ced8ebcff0909450f173e00491efece5874b8b59ad750bfc9ad
-dist/2024-09-04/rust-std-beta-riscv64gc-unknown-linux-gnu.tar.gz=1ed3d0c1066b52dd2174ed45635386ff22798de8cee92765503fbcf71463094a
-dist/2024-09-04/rust-std-beta-riscv64gc-unknown-linux-gnu.tar.xz=e2b22ed31374775441c6d80da80a52bc7558a1363776363ae341e78d0abf34fb
-dist/2024-09-04/rust-std-beta-riscv64gc-unknown-linux-musl.tar.gz=eff055a0e773741c4c2101791feea744c57ae95c50ad32ebec616daab1d098c8
-dist/2024-09-04/rust-std-beta-riscv64gc-unknown-linux-musl.tar.xz=680c9c2de4c7abf391d073709988593eb1daffe19876bd789a0f810f9d8d8458
-dist/2024-09-04/rust-std-beta-riscv64gc-unknown-none-elf.tar.gz=ae71d4f0789955cc883948c75aad9e492e37c206a64561705c8b7a9fec243f3e
-dist/2024-09-04/rust-std-beta-riscv64gc-unknown-none-elf.tar.xz=f41ecbae85295dda2dde95653a059be1852eacc28c175d36cb82cdacbf97a5e9
-dist/2024-09-04/rust-std-beta-riscv64imac-unknown-none-elf.tar.gz=1db39d0674e227b0fcacbc9de7aea52a349f515aaa8ea595cfbd91c6138e0b4c
-dist/2024-09-04/rust-std-beta-riscv64imac-unknown-none-elf.tar.xz=971c6dd1c7e3c6ab14d6d5f563edf974c87cbfd2a2028bced6e01175c8abafe6
-dist/2024-09-04/rust-std-beta-s390x-unknown-linux-gnu.tar.gz=029150a3c19afdafaff023ffd80f7aa1c2cfce7d7464339b0873a6e3da10a923
-dist/2024-09-04/rust-std-beta-s390x-unknown-linux-gnu.tar.xz=22a4612a5a7b38adb3e63ec8526444e51fe222c125c2ba51499987a3906b1cf5
-dist/2024-09-04/rust-std-beta-sparc64-unknown-linux-gnu.tar.gz=069c8fc749bc2ed94179af8e38849b83912c84cd551c4bf27f95e99def8ed0fc
-dist/2024-09-04/rust-std-beta-sparc64-unknown-linux-gnu.tar.xz=5b436df8a26688cc9853f5e12735187e9924a44101e21c4e59fc3dd38778e39a
-dist/2024-09-04/rust-std-beta-sparcv9-sun-solaris.tar.gz=77f6b8e4760ea43aac97ebb177223ad943fbbcc55dc3656afa400d7d1ea35787
-dist/2024-09-04/rust-std-beta-sparcv9-sun-solaris.tar.xz=d2b3e49982ccdb966f420eaba9d582108b227f1acb485f0b176762871d41ef3c
-dist/2024-09-04/rust-std-beta-thumbv6m-none-eabi.tar.gz=5e511b55cc961482998cca16def2424e749cf83a46a52b235e902baf8a653cca
-dist/2024-09-04/rust-std-beta-thumbv6m-none-eabi.tar.xz=8491ec0a3233b04909ad307bf679d6a012fe153eb9ae544956c8fa87a57dd55c
-dist/2024-09-04/rust-std-beta-thumbv7em-none-eabi.tar.gz=9b4d4913146843b01b4b6b7d8e1230c01f764a2ae2433dbb3264bfad14d0b3c6
-dist/2024-09-04/rust-std-beta-thumbv7em-none-eabi.tar.xz=ee700f3dca7d811a230222627ecc6c22d9850151adf47c2a48fb840a079508aa
-dist/2024-09-04/rust-std-beta-thumbv7em-none-eabihf.tar.gz=d54ea14641f79deb2b661e1fe9e9ff56d85189da5ced0f96c16503892c4b367a
-dist/2024-09-04/rust-std-beta-thumbv7em-none-eabihf.tar.xz=cd1529c6f77a079fbf15bcf81d41b4f18a8572729975b2a3ac91e18841e93495
-dist/2024-09-04/rust-std-beta-thumbv7m-none-eabi.tar.gz=fe214540eafddf6dc65ca94f1dad3a12df9e92a157060a9c27a730d99a706b28
-dist/2024-09-04/rust-std-beta-thumbv7m-none-eabi.tar.xz=2b9b1289855f7d9520eab69bc8c4e8505857e44b1e498968e47e3e847ae5a7da
-dist/2024-09-04/rust-std-beta-thumbv7neon-linux-androideabi.tar.gz=dc28759dc83a72d5c8505e90abb98ee55fb0ac53736422c95b631e063f566e5f
-dist/2024-09-04/rust-std-beta-thumbv7neon-linux-androideabi.tar.xz=b25c463af699783e8df43d7ccc5d1692d97e8a1ade8322dcf0cd74246d1d94b8
-dist/2024-09-04/rust-std-beta-thumbv7neon-unknown-linux-gnueabihf.tar.gz=bb8ebf0008749bafb9cee686c7b09db4e4585178b506bc9bec6508577bc98713
-dist/2024-09-04/rust-std-beta-thumbv7neon-unknown-linux-gnueabihf.tar.xz=afb9a8ed9a5dccb0c43eb6a920c647735648a1378413ff1fae754a7e5f972b06
-dist/2024-09-04/rust-std-beta-thumbv8m.base-none-eabi.tar.gz=b090d076b04e7894a94c1ed892825a3f6d27aa3908d40d1a66f098b9d53f4309
-dist/2024-09-04/rust-std-beta-thumbv8m.base-none-eabi.tar.xz=3213f7cb7365420b767779edc091a35f9e3a39e9439d0bf542dcc099eff25ce7
-dist/2024-09-04/rust-std-beta-thumbv8m.main-none-eabi.tar.gz=5d977dc47e7c04d1f729a2a153e2c37ceab7d9a049b111505146e82b7b3bc30b
-dist/2024-09-04/rust-std-beta-thumbv8m.main-none-eabi.tar.xz=8e9cef53163ff70ec8868d11d7c237cf40ced06852fcb193b3ef45232c3cd90a
-dist/2024-09-04/rust-std-beta-thumbv8m.main-none-eabihf.tar.gz=01f1916e4de4401ef0b7c43bfb0df72169f36ab09eda9ee923ef0d6608b8fafb
-dist/2024-09-04/rust-std-beta-thumbv8m.main-none-eabihf.tar.xz=1a9a9fe79884bd8e8e35cc8bcf3d1fb7a82ee4a40c630b78a302aabb047959f1
-dist/2024-09-04/rust-std-beta-wasm32-unknown-emscripten.tar.gz=66da8c5a7e579df020ef012747f9c8ce6a3094bdf43a99dc3763a9234eda3fff
-dist/2024-09-04/rust-std-beta-wasm32-unknown-emscripten.tar.xz=34ba780c992a10428fac49c9149d1f613fac221dd92866a93795543a991c29af
-dist/2024-09-04/rust-std-beta-wasm32-unknown-unknown.tar.gz=485304f0705ea8ef1a3516cd01e9b63e010af514edc03774cd87284367ed5e04
-dist/2024-09-04/rust-std-beta-wasm32-unknown-unknown.tar.xz=414608d21dd7cd268ad57a6be916b0be2c95433e2bc14083ff8c4a7a7cc8952b
-dist/2024-09-04/rust-std-beta-wasm32-wasi.tar.gz=c745c8682a54abe37c2734bf0c7931b6d10269eb56c07765e39dd289dab67e01
-dist/2024-09-04/rust-std-beta-wasm32-wasi.tar.xz=732c12837772531eabc44a7d4a545e130e2ae220d3670748fa2050cd4c65a18b
-dist/2024-09-04/rust-std-beta-wasm32-wasip1.tar.gz=2b54c587ddd908481f5561d6de60c7fdbef234ca2ecec4eb4d4791416038f7db
-dist/2024-09-04/rust-std-beta-wasm32-wasip1.tar.xz=799ee151f0aa3c5ec132f03c42152393d966c9249972967133edef56b30d66ae
-dist/2024-09-04/rust-std-beta-wasm32-wasip1-threads.tar.gz=120b8cad5a2a153bee58ccf81824e6a1c7c16befdd2785f963a9b2dfc350b9f2
-dist/2024-09-04/rust-std-beta-wasm32-wasip1-threads.tar.xz=5d74a8dc4731ab433cf796e7568122c7ca1463c648d2b49876ae1deaeaefa314
-dist/2024-09-04/rust-std-beta-wasm32-wasip2.tar.gz=911e60f2976d3b98dc9f6e82f72c459c5e07713e2dde2c7337569a71db2d1218
-dist/2024-09-04/rust-std-beta-wasm32-wasip2.tar.xz=947d312ec07c6190dcd4abeb493a2b67ac64a9a549ef30372c8eee7164c74883
-dist/2024-09-04/rust-std-beta-x86_64-apple-darwin.tar.gz=7b6e65885f14982f1112a2c0e8dd3266b1c4313276342ed98f2681432720b8c6
-dist/2024-09-04/rust-std-beta-x86_64-apple-darwin.tar.xz=cdbe462e3935c5a34415275afe830a6b5edae2fda84ed35e836ae868c884d19f
-dist/2024-09-04/rust-std-beta-x86_64-apple-ios.tar.gz=f75e7896ed5c9b64f817e9b2d6ed4d637e19ff26a14f72a570b4eff532f5b32b
-dist/2024-09-04/rust-std-beta-x86_64-apple-ios.tar.xz=60db5599bdad826b32637dfd2989daa90597b278ac14b42ede3a7c15aed119e0
-dist/2024-09-04/rust-std-beta-x86_64-apple-ios-macabi.tar.gz=3f57688112d2d80010636724acec5083bce0bc0a901f9ccbd76a09bb21de2b17
-dist/2024-09-04/rust-std-beta-x86_64-apple-ios-macabi.tar.xz=841dcf3eba0ad5b7bc8a4d55fabca80a1a27a3d697431c251b48912131148b6e
-dist/2024-09-04/rust-std-beta-x86_64-fortanix-unknown-sgx.tar.gz=96af596e4bc63519decc0e17005006aee8a2f22258d86b6efa25a94fbbe62f23
-dist/2024-09-04/rust-std-beta-x86_64-fortanix-unknown-sgx.tar.xz=4215a327f11bc7fa02546e69cb52c6c7bfe6a1ca602a6bf7a266e11937204bef
-dist/2024-09-04/rust-std-beta-x86_64-linux-android.tar.gz=80849fc95791de8cf98da9ebd405a4e268445b22b9413c8545870fe83f5891c7
-dist/2024-09-04/rust-std-beta-x86_64-linux-android.tar.xz=f849ad9d7ccc7eda06404e3bd67f150c3d8dfa66609405435fb2ba09c00ca136
-dist/2024-09-04/rust-std-beta-x86_64-pc-solaris.tar.gz=f871244a44131b1e2f56ad7c77ccb4e7433f39d6b248951f449914a65178bea3
-dist/2024-09-04/rust-std-beta-x86_64-pc-solaris.tar.xz=933b3b634b5caf57213be093977b0f56ba3609dc9407ac026079f75f4783642d
-dist/2024-09-04/rust-std-beta-x86_64-pc-windows-gnu.tar.gz=28ef28c4b17b5e8a20ae5f19feeb4643864f64ac8e9c68b84f8cec067317c339
-dist/2024-09-04/rust-std-beta-x86_64-pc-windows-gnu.tar.xz=1e40daa830d390d57c0dd23331849edf45adc0a35d120725bfd9fae43edf13e1
-dist/2024-09-04/rust-std-beta-x86_64-pc-windows-gnullvm.tar.gz=b9a6e290d7b9c71b4a33164116cc523654c3147168a04fc7608a27397c100944
-dist/2024-09-04/rust-std-beta-x86_64-pc-windows-gnullvm.tar.xz=a6e1db0945d1a5243caf2d1ad7d24b4dd16f8882d3e88118f203c91ff5e2cd52
-dist/2024-09-04/rust-std-beta-x86_64-pc-windows-msvc.tar.gz=8d70d70a645b36e6de01b08a34a28a995c73f91e8a285607a5516180d3a93350
-dist/2024-09-04/rust-std-beta-x86_64-pc-windows-msvc.tar.xz=d5a6fc72bf9dc0b7083d364358232a5df68b2b9f03a1a553bbeecf2a84936cb8
-dist/2024-09-04/rust-std-beta-x86_64-unknown-freebsd.tar.gz=01e159405178d883deb8eb09e9101826e7591c8d8fd6840133c0e8f77e00e395
-dist/2024-09-04/rust-std-beta-x86_64-unknown-freebsd.tar.xz=7fddda753b5f3e244de9427de6399052c81df87bd2b76d2c1f9a0fa4d1d1cddf
-dist/2024-09-04/rust-std-beta-x86_64-unknown-fuchsia.tar.gz=2c37eaef53b50d812205ed24de580165bfa800658ab9a9ea503667105119a544
-dist/2024-09-04/rust-std-beta-x86_64-unknown-fuchsia.tar.xz=8d1e3d290c5736c4e7a48a6b1a88ba18b9e68876638896b31b61917c6fcd2af4
-dist/2024-09-04/rust-std-beta-x86_64-unknown-illumos.tar.gz=83a57ec9e9696a63dadf9307e0cce117b92be8e9b7d17edfe410d38f75629202
-dist/2024-09-04/rust-std-beta-x86_64-unknown-illumos.tar.xz=3db6747b556581f02e0cf058b93538785d1eca9aaefe36dc8b7667428fa05ef7
-dist/2024-09-04/rust-std-beta-x86_64-unknown-linux-gnu.tar.gz=fe737fb11bd2a16b7636013f37041a35126f0bf8b2c562ac38384d45e49088c4
-dist/2024-09-04/rust-std-beta-x86_64-unknown-linux-gnu.tar.xz=a7a3f5245067b2967bbc4bd010ac3a6e9613cc9b6462c53cdcf0b91eab6cddbb
-dist/2024-09-04/rust-std-beta-x86_64-unknown-linux-gnux32.tar.gz=8b3fa007713d4e37de79d5662a3de446d378e00fc631478e465fb170447c49ea
-dist/2024-09-04/rust-std-beta-x86_64-unknown-linux-gnux32.tar.xz=c2dd95e94f9a9bc2d31e807a3b7cc5cb43a994cd4400ac1636ade3005344146b
-dist/2024-09-04/rust-std-beta-x86_64-unknown-linux-musl.tar.gz=a294420b029900027530932ebd29cbd3f17672fffc60128122473088329f8cb8
-dist/2024-09-04/rust-std-beta-x86_64-unknown-linux-musl.tar.xz=72a1c8052534e1b986ebd1bb5364de9e9e67353cfc6de7341f759d8da370bf2d
-dist/2024-09-04/rust-std-beta-x86_64-unknown-linux-ohos.tar.gz=7227b14f3148302d954756bd4df570289aa8dedd8d889b5399821356ac097f8a
-dist/2024-09-04/rust-std-beta-x86_64-unknown-linux-ohos.tar.xz=61cf15b98ba67fb648ee87901bc33644efc342c2b6401ab8b6a14cae755cbd8d
-dist/2024-09-04/rust-std-beta-x86_64-unknown-netbsd.tar.gz=61b604f112031aadd7ad87e535cbb4966c53099e276fc76d99fecd0e912b2e28
-dist/2024-09-04/rust-std-beta-x86_64-unknown-netbsd.tar.xz=428a0a6955266ac0e74b11bb4c58a461c041f13f241d5a2d698139b4b5839ad5
-dist/2024-09-04/rust-std-beta-x86_64-unknown-none.tar.gz=c8b29984bf2b6d77893cda301e55dd128da76bad7dd87c751aa5585add2262fd
-dist/2024-09-04/rust-std-beta-x86_64-unknown-none.tar.xz=1460566b927586f6afa531aa1cefa9aec0d4e829a08a151638a42c255b6a7ef3
-dist/2024-09-04/rust-std-beta-x86_64-unknown-redox.tar.gz=17503716bb940d50db15bd1b467fe03ff15474f1b0b162eb3f2891699d898768
-dist/2024-09-04/rust-std-beta-x86_64-unknown-redox.tar.xz=66007a1f995597a697747886eacbe38c9d6a588b1ed365e6b4b522c72bc7b8af
-dist/2024-09-04/rust-std-beta-x86_64-unknown-uefi.tar.gz=b612bac841c9f93bc6189971bf82df47e8730cf1696d2d6f3344be67a6c28f0c
-dist/2024-09-04/rust-std-beta-x86_64-unknown-uefi.tar.xz=3dd0f70f8f226160700a52c19aebc2f27801360a8d2882702c5a0be94560da3b
-dist/2024-09-04/cargo-beta-aarch64-apple-darwin.tar.gz=3efe0d5356824c1620e223686c81cf10b629db0a0c385c3177b5fe1866776b5c
-dist/2024-09-04/cargo-beta-aarch64-apple-darwin.tar.xz=07deeec79d74a39b0cf971bd980936eb476005bf0e832adef9e4521bba3c010b
-dist/2024-09-04/cargo-beta-aarch64-pc-windows-msvc.tar.gz=c9da3632a36a2db512015580bd20e0b5207f8a0d98ae093a99755e4c512215f8
-dist/2024-09-04/cargo-beta-aarch64-pc-windows-msvc.tar.xz=b0b9aabd90863c1671ad80955277c2f006654779837cb1358774b8189fba357b
-dist/2024-09-04/cargo-beta-aarch64-unknown-linux-gnu.tar.gz=cb862535909b1f0fea6ee40a6a888f2f860f95b8700b1d5167bd7a41b9e33958
-dist/2024-09-04/cargo-beta-aarch64-unknown-linux-gnu.tar.xz=b1ff8f714cda2c98a7129e861adcf33245bd84bdfbdcec9fb1a89545dcd033f7
-dist/2024-09-04/cargo-beta-aarch64-unknown-linux-musl.tar.gz=5c3659e979393c8c1dbe1a6ccb09eea412671363e228f0c7ab4bd4896cd48470
-dist/2024-09-04/cargo-beta-aarch64-unknown-linux-musl.tar.xz=0435e1332b1bc40a280fc867eab54e925135eba774c3bc0553a8bb100d644f59
-dist/2024-09-04/cargo-beta-arm-unknown-linux-gnueabi.tar.gz=6f7f079ef04c4b1d14864cba67ec650a3e43f3baa81fea1797d00067f22a72a8
-dist/2024-09-04/cargo-beta-arm-unknown-linux-gnueabi.tar.xz=549607bdeacd26fa770ecb00ce54cb3ea72c5568e65966c1fddc3a540b9f6e6a
-dist/2024-09-04/cargo-beta-arm-unknown-linux-gnueabihf.tar.gz=e23b18a2a86bca5320b66c54d43a54d90db1b787443cb0e04d66e9d7428fece7
-dist/2024-09-04/cargo-beta-arm-unknown-linux-gnueabihf.tar.xz=5968c534ce88a2574a4f59a0ced82df36aef9c7338ed9c718e85aad514a792f4
-dist/2024-09-04/cargo-beta-armv7-unknown-linux-gnueabihf.tar.gz=3170e39d306e797e5631884c629ecb33a54635056b5a71fbebe5372c1c34da37
-dist/2024-09-04/cargo-beta-armv7-unknown-linux-gnueabihf.tar.xz=76b729642fdba25c015e49e444e158170d3ed2ac0a533ba7c6095ecdc0862ba5
-dist/2024-09-04/cargo-beta-i686-pc-windows-gnu.tar.gz=c58826189772af945c9d40868e80d64359f4108afa06d150a3d350323b0eb8df
-dist/2024-09-04/cargo-beta-i686-pc-windows-gnu.tar.xz=1b644d661778bfcbec892eab17bee06861940037992821c4ded8321a69c0f6a8
-dist/2024-09-04/cargo-beta-i686-pc-windows-msvc.tar.gz=e026eac2c2e891976e085d26591d85000dccf3c3654f3edd65e99c6c0ba43574
-dist/2024-09-04/cargo-beta-i686-pc-windows-msvc.tar.xz=e7307b2e55302228c5036991ca6141a5202a16f43b0148607f3802fdc90aa0cc
-dist/2024-09-04/cargo-beta-i686-unknown-linux-gnu.tar.gz=0a00604bad2096cd0b0db59a1b41b5737696015a4ddc60f9b1132829a4cd0a5f
-dist/2024-09-04/cargo-beta-i686-unknown-linux-gnu.tar.xz=a623eecb18a21b2dc6a4b62876b8fa4fc467c53fdd0cfdac493f89d619be5aa7
-dist/2024-09-04/cargo-beta-loongarch64-unknown-linux-gnu.tar.gz=64955892d99d0e7f0042016d7a5e3ac87f89b6f514b1934611050f89aa5f6a28
-dist/2024-09-04/cargo-beta-loongarch64-unknown-linux-gnu.tar.xz=3c7c3061c466fc4a1eb836c97cab95d511778d77d220189a6a77f8e5b46e4888
-dist/2024-09-04/cargo-beta-loongarch64-unknown-linux-musl.tar.gz=be1c255840307bd24c2c8b5c92e2fa0eed6037daf3ed9597e17bc56f313ef506
-dist/2024-09-04/cargo-beta-loongarch64-unknown-linux-musl.tar.xz=d0e456bc8b64a0ee778e69eac75b6a258c37f7b2d06496a8dfcc47d91e1c2dd1
-dist/2024-09-04/cargo-beta-powerpc-unknown-linux-gnu.tar.gz=b9cd94c4ac9a11eece8712b325d08007b641d5da7487fd38b30dbaf0f3d1b5a4
-dist/2024-09-04/cargo-beta-powerpc-unknown-linux-gnu.tar.xz=68dd4a74494fe8f02781a2b338eff5f5cc78d66048eddd3ed7cc3e31dcecd2c8
-dist/2024-09-04/cargo-beta-powerpc64-unknown-linux-gnu.tar.gz=b464ad7a1233e3ad5129340e623a60d2ad0882843acbef60a9aed45a453ccac1
-dist/2024-09-04/cargo-beta-powerpc64-unknown-linux-gnu.tar.xz=1167f3d38628c01b11dfb9f66eacdf4cd519b46ea1b8c9d182a390e7d552a933
-dist/2024-09-04/cargo-beta-powerpc64le-unknown-linux-gnu.tar.gz=eb16d3791a79aa384326e2e79aeafd8d3e27adf4733a5bcca441e278e578b60e
-dist/2024-09-04/cargo-beta-powerpc64le-unknown-linux-gnu.tar.xz=d100dcb6437e87b3b687a7059dd932567855f68d962a109268fcce5a5aa688c6
-dist/2024-09-04/cargo-beta-riscv64gc-unknown-linux-gnu.tar.gz=ee771d98286302d4a8a93ba5165c342a2fbe770bf7758f8bbc490ad188d2e5cc
-dist/2024-09-04/cargo-beta-riscv64gc-unknown-linux-gnu.tar.xz=d2e9eb5a1800545eec4186b5252737f3b3a02d232473e6864e4c6fd752a69623
-dist/2024-09-04/cargo-beta-s390x-unknown-linux-gnu.tar.gz=b35ef65a54c9dd068a699f4210c0c88bd2777308fd7ddad3c7d0b9a1c994657e
-dist/2024-09-04/cargo-beta-s390x-unknown-linux-gnu.tar.xz=eaee5c891aab499438427c2c965c2c8f4471a3b051effee139f251f544ac4ac4
-dist/2024-09-04/cargo-beta-x86_64-apple-darwin.tar.gz=917ba277cb3f050fb3e65126b587245bf89891256faec33a57e2b1a064075534
-dist/2024-09-04/cargo-beta-x86_64-apple-darwin.tar.xz=179d6fe24981d477eb806ba714bd639750577cb9de2d152116e994d3955ade38
-dist/2024-09-04/cargo-beta-x86_64-pc-windows-gnu.tar.gz=6aa52989d1ccb25b03433dec436507455256cb1e2ed305ba747c342551d0778f
-dist/2024-09-04/cargo-beta-x86_64-pc-windows-gnu.tar.xz=bc0403c00fa2093f09d95b1ad091850b2450f4e1d7fac225a730d7363074806b
-dist/2024-09-04/cargo-beta-x86_64-pc-windows-msvc.tar.gz=5c1e018191c296ddc443699e48c4f1a3e700983fc45ea230172f35881d09e103
-dist/2024-09-04/cargo-beta-x86_64-pc-windows-msvc.tar.xz=f1b44ff315f5332815263d5b0a1cd06f852431acbf5cc902bb6723c3398e11d6
-dist/2024-09-04/cargo-beta-x86_64-unknown-freebsd.tar.gz=7da980ccdb2d6bc0946749fcceaed7124f311b38bf28cef0797ca85909f5d5fb
-dist/2024-09-04/cargo-beta-x86_64-unknown-freebsd.tar.xz=a935462749686fb68eac699ea67ef1afaa22ed0b147d2e4d0a6712f225341fa2
-dist/2024-09-04/cargo-beta-x86_64-unknown-illumos.tar.gz=ccc3d29e88482885090f6fb954518bcb0b6bd3f54283702df9e0e80b78454c01
-dist/2024-09-04/cargo-beta-x86_64-unknown-illumos.tar.xz=c0cb33e5088f2b9f5fe8bedb3915fec10e7f65563013b914e0738486b5e8ebab
-dist/2024-09-04/cargo-beta-x86_64-unknown-linux-gnu.tar.gz=84fdbbc0912c4020dd1baec1d603c5d5c1986c7b321d3d9c0c42184aa6347f15
-dist/2024-09-04/cargo-beta-x86_64-unknown-linux-gnu.tar.xz=8f8948750141c3ee8a50e575f196bd972876e784cf1793b256a5a9462c9e3d44
-dist/2024-09-04/cargo-beta-x86_64-unknown-linux-musl.tar.gz=9ef6b7450b94ce202f1b603151075bf8f595022f2c52f6bcd1c4a72423db2b80
-dist/2024-09-04/cargo-beta-x86_64-unknown-linux-musl.tar.xz=5b63b98d67e211057fbaeb1db3721b90252a331143ca267bb30eebca4ac01cdd
-dist/2024-09-04/cargo-beta-x86_64-unknown-netbsd.tar.gz=69d500e2fca1c44fea31310b0636a9af009d4ec96b5ed2335864c47350fa7b59
-dist/2024-09-04/cargo-beta-x86_64-unknown-netbsd.tar.xz=7da3c2641f0ecdbd8b770402356416750a52265a6848d3734fce2195c889768a
-dist/2024-09-04/clippy-beta-aarch64-apple-darwin.tar.gz=15395c04235f2475d5e41371e2797f181af71275f82f04fbb885b1cd7a197f45
-dist/2024-09-04/clippy-beta-aarch64-apple-darwin.tar.xz=8be6fb9e0cafcd262594cfc4a36807bede9e158cbf7eb38c0f25144bf3bfdd1e
-dist/2024-09-04/clippy-beta-aarch64-pc-windows-msvc.tar.gz=b043e41facce81a5fc607f2268330b279d7e26975e409158ac2cbbc841d10f85
-dist/2024-09-04/clippy-beta-aarch64-pc-windows-msvc.tar.xz=ba41705b213f863416120c28fa4a7959cf41e261cce8233b12fd91aa0157d601
-dist/2024-09-04/clippy-beta-aarch64-unknown-linux-gnu.tar.gz=b093269be813ea76964de2c03c7380bcefab1e7d6e31c93fd3f374619a99a5f0
-dist/2024-09-04/clippy-beta-aarch64-unknown-linux-gnu.tar.xz=06d71273208fcbfa5958987038eacda066d4518b5cd6bd7405a981bf841868ae
-dist/2024-09-04/clippy-beta-aarch64-unknown-linux-musl.tar.gz=aa159e61c4986def9d27f55504d822d6023c277a546e95079161577ae2991df4
-dist/2024-09-04/clippy-beta-aarch64-unknown-linux-musl.tar.xz=7a3023b98a1c72c993d176c85f4790b234c41f35184636d29deeba40d51587a2
-dist/2024-09-04/clippy-beta-arm-unknown-linux-gnueabi.tar.gz=8e30a0377b780311bf51bdc48dcf233a344cb2fd9ae9aec174bc87d29f94c34b
-dist/2024-09-04/clippy-beta-arm-unknown-linux-gnueabi.tar.xz=488c28d10f45a498b1054fad9feb72a848d0668cd12d29b3a81f5569b1145018
-dist/2024-09-04/clippy-beta-arm-unknown-linux-gnueabihf.tar.gz=db25c9aa95b08acdaeaba407367a823e9e2094b0616c80b0c8a84d7c2f6c4292
-dist/2024-09-04/clippy-beta-arm-unknown-linux-gnueabihf.tar.xz=7c320cc979ebdde8753093a0e4b1da850b1b680c1ecd10c5d3e33242af12e4dd
-dist/2024-09-04/clippy-beta-armv7-unknown-linux-gnueabihf.tar.gz=835c0912556cd5b0b180856359db8d75204830984fb1b5f72bf436f137955fa2
-dist/2024-09-04/clippy-beta-armv7-unknown-linux-gnueabihf.tar.xz=836a54126122c2abfc649982708d97b6451eaf3a31ba556ed73ec1f4269be738
-dist/2024-09-04/clippy-beta-i686-pc-windows-gnu.tar.gz=90b52880cbd51bacb9597ee4fed07fa13fc399f03c5ba840c0c9e6c0a096b772
-dist/2024-09-04/clippy-beta-i686-pc-windows-gnu.tar.xz=c41be130f3276c4c905eab580e866682e4f3bbdd11b348f4d1438c67602fb036
-dist/2024-09-04/clippy-beta-i686-pc-windows-msvc.tar.gz=f023406dc34bb09d020a41fdf6ceb3e60c90dd38380fbbcc26e9f4e144eebca0
-dist/2024-09-04/clippy-beta-i686-pc-windows-msvc.tar.xz=b21746ec1a2c9fc76ce82917b65c8e73482aaefe5f99282f0c5e9682a3af486e
-dist/2024-09-04/clippy-beta-i686-unknown-linux-gnu.tar.gz=cce9cd9d470250c73437e151622b02f804fff3db045c6de25ee949aed435c383
-dist/2024-09-04/clippy-beta-i686-unknown-linux-gnu.tar.xz=9565f70c8d90540d464fb1f3b8bff52b77bf55189ab938b2c18bdeed751e9e4c
-dist/2024-09-04/clippy-beta-loongarch64-unknown-linux-gnu.tar.gz=0d1d63a8eca4d0812446f94bc793fbb7660da11babf5d8607d2798749c938a6b
-dist/2024-09-04/clippy-beta-loongarch64-unknown-linux-gnu.tar.xz=db178c0eaddcb318653d4b05fe0d97738440713f0cd120657cc2a3e758d52432
-dist/2024-09-04/clippy-beta-loongarch64-unknown-linux-musl.tar.gz=a604be9f091f88e97f702f619d86b91bff0a20fbd267200ac1e66df2bd823766
-dist/2024-09-04/clippy-beta-loongarch64-unknown-linux-musl.tar.xz=93c395e07a8457b8904c470751490326303e2ceaa93b737f8fc521b49dfbd69b
-dist/2024-09-04/clippy-beta-powerpc-unknown-linux-gnu.tar.gz=08aa4a8ccd7569a0513c2443e2b10993cbb92bed531370891452bd3dd8c0eb82
-dist/2024-09-04/clippy-beta-powerpc-unknown-linux-gnu.tar.xz=f6b0222261e1e2b1465549eda331c16d4ea6729d15e6fe208dbc4cce115e75e7
-dist/2024-09-04/clippy-beta-powerpc64-unknown-linux-gnu.tar.gz=96e2dca5adb7f5ffe41e5ff30e9419575f3991adde8bdbba023d11f344044dc1
-dist/2024-09-04/clippy-beta-powerpc64-unknown-linux-gnu.tar.xz=3ced511aca7268960c616d0105da02a92d83b7983b6accbb37eba722eff64cbf
-dist/2024-09-04/clippy-beta-powerpc64le-unknown-linux-gnu.tar.gz=421c27b25b79b9c88e4b65ac7cd0a4f06934a63324c56870cd7fff905869a33e
-dist/2024-09-04/clippy-beta-powerpc64le-unknown-linux-gnu.tar.xz=63254a01ab1a9a21cdb5a0b3a4da9e8ae7921b9ceec2339df4bbfb19ea7c6454
-dist/2024-09-04/clippy-beta-riscv64gc-unknown-linux-gnu.tar.gz=4ee751b09816886f8edbc431ab8c63df6c664dbedc40a67748fb17a639a070f1
-dist/2024-09-04/clippy-beta-riscv64gc-unknown-linux-gnu.tar.xz=7e9ffb62ab6c8f1cbb5f9e0b0a3c79cf104dfac09be2ef1d5e6b6c0c34b406c7
-dist/2024-09-04/clippy-beta-s390x-unknown-linux-gnu.tar.gz=0a49c1e844859f27b1283087c476a559c4c3a4c33c8ce2748165cc5c0b0ed039
-dist/2024-09-04/clippy-beta-s390x-unknown-linux-gnu.tar.xz=6daec872df52125b3de854ff0962433ba13b7cbe5519edfb29944fbc4cc817ad
-dist/2024-09-04/clippy-beta-x86_64-apple-darwin.tar.gz=6611771ce0e7cc19fbbb9383875edaf7de975b6cf154fcd5cd18a09f09793a36
-dist/2024-09-04/clippy-beta-x86_64-apple-darwin.tar.xz=1c90c63f87b43797aa04b88e4c1d0fe0f2ad131060fc8495be190d0ebd89a43e
-dist/2024-09-04/clippy-beta-x86_64-pc-windows-gnu.tar.gz=53a04c1426bc151fec4699848e33141df1b04097d4883c07fc07d2bf0bcddf8a
-dist/2024-09-04/clippy-beta-x86_64-pc-windows-gnu.tar.xz=be748b65b238e3e948e2421f82a72d1108ec79651381b1dcdaaa97df15c981df
-dist/2024-09-04/clippy-beta-x86_64-pc-windows-msvc.tar.gz=24ea01230bbf6b4f43094cfcf6c7c72e6d319c493ff3817456c667b89026c608
-dist/2024-09-04/clippy-beta-x86_64-pc-windows-msvc.tar.xz=37130d66eeaed68f0780b1dc19f2f59a2a0419350920521690d4870d7d71d8f1
-dist/2024-09-04/clippy-beta-x86_64-unknown-freebsd.tar.gz=4e427b7ea0f334bd6ea8c2de7fc1d5bf43d5333bc7a435cf65543c564fab6e41
-dist/2024-09-04/clippy-beta-x86_64-unknown-freebsd.tar.xz=b221491159f5352dd392f6ee6419f9d5d693ac347df9863fdac77f2ca1cf6a67
-dist/2024-09-04/clippy-beta-x86_64-unknown-illumos.tar.gz=9d835b4369fb51ab8c1eafb553b9304548e91dd32784ae81cb783b40985d2eee
-dist/2024-09-04/clippy-beta-x86_64-unknown-illumos.tar.xz=a6780c72c71f2e6c6e1bbc8bc4e639389ab9b7aed0ee7e2e0c21819156b5578e
-dist/2024-09-04/clippy-beta-x86_64-unknown-linux-gnu.tar.gz=613bf471668edb8209910dd13086cbefed0da6dea46dce2013a000ecc4315e45
-dist/2024-09-04/clippy-beta-x86_64-unknown-linux-gnu.tar.xz=e3328f37cfc89de1aabd89653a42ff54b8dadcc49e651b22fda325c00644309d
-dist/2024-09-04/clippy-beta-x86_64-unknown-linux-musl.tar.gz=d6a7a5ee37587c0b92aabfc5b9466d175cb8d05d209412a5beee8a61c241396f
-dist/2024-09-04/clippy-beta-x86_64-unknown-linux-musl.tar.xz=dc73b566be162eef2032eccb69b3542ab3c72b760fe7eeaacfcd367ee0b20f12
-dist/2024-09-04/clippy-beta-x86_64-unknown-netbsd.tar.gz=6f1e0be96b59a63a6616b68717c0a393fd99ec1a768affdd5c86249e5eb5d210
-dist/2024-09-04/clippy-beta-x86_64-unknown-netbsd.tar.xz=30fff8aceaedf6d76c6fc0636c2ddecc97fb66f9219b86299550b7312f043e38
-dist/2024-09-04/rustfmt-nightly-aarch64-apple-darwin.tar.gz=37a5383ba608540ed57484e221e87f3cd78fd35f068e98f0da1d3932d86d2eff
-dist/2024-09-04/rustfmt-nightly-aarch64-apple-darwin.tar.xz=a3935c24f5ac1d69756f4598f227e43304ede4e35f9808b3db9f04adfecc5445
-dist/2024-09-04/rustfmt-nightly-aarch64-pc-windows-msvc.tar.gz=0b21dd8c54055102a41f7ad622565c1fc36ff97642f2e2998e48d1cb1ebae196
-dist/2024-09-04/rustfmt-nightly-aarch64-pc-windows-msvc.tar.xz=2a543dbf79042924e8c05aaeed97ff37089c8f6994977b932bacb0403f11584c
-dist/2024-09-04/rustfmt-nightly-aarch64-unknown-linux-gnu.tar.gz=8d9b19108587e6d8d12270ff025579dc559173245e08b94113bb91a7ada80670
-dist/2024-09-04/rustfmt-nightly-aarch64-unknown-linux-gnu.tar.xz=d288770b8a85e24b35561129cc2a09c848006c547ce5fa35d33c8ed7e85d5322
-dist/2024-09-04/rustfmt-nightly-aarch64-unknown-linux-musl.tar.gz=2e69adc7e75efcd889108d185f200db6280494b05de6a06291dbf26ef32e5d42
-dist/2024-09-04/rustfmt-nightly-aarch64-unknown-linux-musl.tar.xz=fca74af6db1c53a79a4412a020f56ec9c61603d3373eaa936a57dad45f3751d7
-dist/2024-09-04/rustfmt-nightly-arm-unknown-linux-gnueabi.tar.gz=b2be0123cde401aaed259a9387e04f3978fbddce98096b3a8a654b76f92f2e6b
-dist/2024-09-04/rustfmt-nightly-arm-unknown-linux-gnueabi.tar.xz=c44c42a59887f1479383694f43688f9f2a8174ac89fdf657b2e8619372e0bcef
-dist/2024-09-04/rustfmt-nightly-arm-unknown-linux-gnueabihf.tar.gz=3d99bab3656d0318173c414dcb8930291ab43285883ca80a04d854023a4201a3
-dist/2024-09-04/rustfmt-nightly-arm-unknown-linux-gnueabihf.tar.xz=29e506c1a18449b84a643f0075f1263cd8512662f55e2c5b18305213e4246783
-dist/2024-09-04/rustfmt-nightly-armv7-unknown-linux-gnueabihf.tar.gz=b486ff8e1e136ba15c9bb14db08dcd14b612adf1617cf1f820a23ee403958049
-dist/2024-09-04/rustfmt-nightly-armv7-unknown-linux-gnueabihf.tar.xz=b4d593b5a89bb42e7f9eaa17df12778dd816c75e8997e964371286041691cbbf
-dist/2024-09-04/rustfmt-nightly-i686-pc-windows-gnu.tar.gz=dcf94a642166b0664a63c4162a2d303c75fdef6f2a7f9b3e502ba5baae117f69
-dist/2024-09-04/rustfmt-nightly-i686-pc-windows-gnu.tar.xz=4b27ac17748d8cdcd2bc7b9956541333997c6ec56f7a770628dc8e57fc7f442f
-dist/2024-09-04/rustfmt-nightly-i686-pc-windows-msvc.tar.gz=8a3caf2dc2b786ca58f6d37c011dc210e883398a3734f9f13678a9e57c5ccf5d
-dist/2024-09-04/rustfmt-nightly-i686-pc-windows-msvc.tar.xz=e129b88dd69200e305cc5ae16231952d85f9461dad13fd3bae5e889dac89d9c6
-dist/2024-09-04/rustfmt-nightly-i686-unknown-linux-gnu.tar.gz=1bc390abb8f754d5b8679b33186b97262dadff9c6db7268cfbcfe605c628a681
-dist/2024-09-04/rustfmt-nightly-i686-unknown-linux-gnu.tar.xz=8420198b0a22aaa5951678b954bcce636c78ba6567a06484c830b3eded815228
-dist/2024-09-04/rustfmt-nightly-loongarch64-unknown-linux-gnu.tar.gz=05071fe12ed4030464f996fe36dd2e3f60d3701956275499acaeaf03a16e36eb
-dist/2024-09-04/rustfmt-nightly-loongarch64-unknown-linux-gnu.tar.xz=2bfdabab0d03e570c073463a8867bbdb54879f501b0822906fa2aa5705603d7c
-dist/2024-09-04/rustfmt-nightly-loongarch64-unknown-linux-musl.tar.gz=0c7e3b10626a9d9a3f8522175085169ea4e34568a7be0093c6682bb9659bf65f
-dist/2024-09-04/rustfmt-nightly-loongarch64-unknown-linux-musl.tar.xz=deb2b51a41dae2e72188fa6c06c4a7bdb08c2723b3ce823602087bd9eb36eb07
-dist/2024-09-04/rustfmt-nightly-powerpc-unknown-linux-gnu.tar.gz=e34590ec2cbd481ffd237101c239f27bd2298517bb7fc9c9f9b6d71abfff69e4
-dist/2024-09-04/rustfmt-nightly-powerpc-unknown-linux-gnu.tar.xz=9cd0d3dd57b764ad054d4295f822a7fd74a1b1ee5babf77ed2dc2c39ee60b7a2
-dist/2024-09-04/rustfmt-nightly-powerpc64-unknown-linux-gnu.tar.gz=62566938d97058dd38b1e0c97aa4421d709ce988544956d6a4aaf3e54425dbce
-dist/2024-09-04/rustfmt-nightly-powerpc64-unknown-linux-gnu.tar.xz=8f27c6fc5b56092302e49da973ff08f0d3131465bf9a701a9ddc91d373acc435
-dist/2024-09-04/rustfmt-nightly-powerpc64le-unknown-linux-gnu.tar.gz=7637f3b8060635595a3d2fb83fef68e9990ff1adb1bd3288c7c41767b37ee2c4
-dist/2024-09-04/rustfmt-nightly-powerpc64le-unknown-linux-gnu.tar.xz=3275f15e3d7e9ccb991f6f9a7059acefd0bee49bfd4cf0724aed11e51e3772db
-dist/2024-09-04/rustfmt-nightly-riscv64gc-unknown-linux-gnu.tar.gz=29379bab930e7b350cec51be33663ad67a0d30922d658006911f895221dcbffd
-dist/2024-09-04/rustfmt-nightly-riscv64gc-unknown-linux-gnu.tar.xz=4f71e948ec587836315d7ec98e6f3c6125a298faf1321b4524257d3c9664f9eb
-dist/2024-09-04/rustfmt-nightly-s390x-unknown-linux-gnu.tar.gz=5b9361317481269e090b4270bcf754caca8a1797f6b2d83a4c570a4024bb0dc3
-dist/2024-09-04/rustfmt-nightly-s390x-unknown-linux-gnu.tar.xz=db3bf98663017bec6b6beba5848a350d4d34f39e3f98bacb321866112cff7c15
-dist/2024-09-04/rustfmt-nightly-x86_64-apple-darwin.tar.gz=9d5b8c84f82ededb2370c20afdb6b7d06d97161a65348f4ee2b6ab2171236cd0
-dist/2024-09-04/rustfmt-nightly-x86_64-apple-darwin.tar.xz=e880f57ba68bce871fa67230db19aab1f146548254867f09e0d83750bbb50a1c
-dist/2024-09-04/rustfmt-nightly-x86_64-pc-windows-gnu.tar.gz=8b2c79814b202661c74584d7c4aeb35cc0c8520c4df1c81f2fb2896a22385191
-dist/2024-09-04/rustfmt-nightly-x86_64-pc-windows-gnu.tar.xz=c193e2f2b859239aa0489c65663fb83c4bd7a87571d5b6ca6572f722c46cef64
-dist/2024-09-04/rustfmt-nightly-x86_64-pc-windows-msvc.tar.gz=8d6583366248882490371ef5d4532f82ba1779cb993b0078ca6903f9b6a0c5be
-dist/2024-09-04/rustfmt-nightly-x86_64-pc-windows-msvc.tar.xz=0b69fdd8edb566a75cdff616e09223b10796a91eaf8bd90aa11ddd6af61381b9
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-freebsd.tar.gz=0a452883a9a494f1613f9b0c796d13745e56eb85597142a677c78daeca95a67c
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-freebsd.tar.xz=01eb4d938f6e9228cae297688340daf298bf6e5322a4e3cdb4e06554fa131deb
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-illumos.tar.gz=4d9220bee07e3576f34c3a3dd327723ed660a774c4391f7a4a7e6a78ea2ca88c
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-illumos.tar.xz=2e2cd60bbb356d7b702c511ba56b480ffe0bbceef8f945be0f7b8e338d7998a0
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-linux-gnu.tar.gz=4aac5347a6011ff27609b4a6b413454d610a5687253a7e09d1bcc8c0e3aa0e6f
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-linux-gnu.tar.xz=ad3a0127c2cc09893fb19e4c58faa6188afeb575996ee4708eae6c5713ff9646
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-linux-musl.tar.gz=869fbf24ca816b0bf931da79920ae8edaef8a749271434c6522f7ff55920a507
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-linux-musl.tar.xz=f4870110759f28ad1cdde912fd3f79bd8eb0073bd42e436a456f0d04e7c2bd26
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-netbsd.tar.gz=eac75028d080b3d4ab86dbbb4f46c7734c60bd747e0325afbaa3b7a7cf0003be
-dist/2024-09-04/rustfmt-nightly-x86_64-unknown-netbsd.tar.xz=fe13bf3e0ec3088b35608d65b76f77014e0b90886ba81decfa21019ff222c79b
-dist/2024-09-04/rustc-nightly-aarch64-apple-darwin.tar.gz=ecda4ccde26bf6f8405ddbb838239c4f42e9136001e8954b21357d86343ad06d
-dist/2024-09-04/rustc-nightly-aarch64-apple-darwin.tar.xz=cdb1b12e6acf5b2bc5a5328f7cb292760d391b3e269d2b2143c87a344efcc9dd
-dist/2024-09-04/rustc-nightly-aarch64-pc-windows-msvc.tar.gz=46af634f433b9c7182637880f7b910ef13d2da9b1d7d4e255f9cd302691b99fc
-dist/2024-09-04/rustc-nightly-aarch64-pc-windows-msvc.tar.xz=a14935b0b82835388886c826b703057af093dfe16f0367c058dd6d352e585859
-dist/2024-09-04/rustc-nightly-aarch64-unknown-linux-gnu.tar.gz=68ced431fa8682f83dd79901ccb986accc5a6d948c837c43eb5fa244c19eab88
-dist/2024-09-04/rustc-nightly-aarch64-unknown-linux-gnu.tar.xz=fa078e5edc9f6c7be5a39eac722f142d526b68e30acc8f81bd001035fd657a83
-dist/2024-09-04/rustc-nightly-aarch64-unknown-linux-musl.tar.gz=c88a3c5cbb7a8a55f18d27f2c573192d824e33657a143641d1c8fa1504cbc805
-dist/2024-09-04/rustc-nightly-aarch64-unknown-linux-musl.tar.xz=00170baf596aa6e043598e3c38153f29c1cbfe4a63298d4007979877e9c3e1c2
-dist/2024-09-04/rustc-nightly-arm-unknown-linux-gnueabi.tar.gz=19a55b89192897c77240404ff7ed8c64cdba106db13be4a1ae86a9ac44753c30
-dist/2024-09-04/rustc-nightly-arm-unknown-linux-gnueabi.tar.xz=42937abfd803faed251cecc7ac74abcc3c40332b8466535cc1727138fe03beeb
-dist/2024-09-04/rustc-nightly-arm-unknown-linux-gnueabihf.tar.gz=3cc5d6e89cd8b53db0c2900a73e59c188e90d042b2e43502e384f44d229b93e7
-dist/2024-09-04/rustc-nightly-arm-unknown-linux-gnueabihf.tar.xz=4e1ff68b91e0cc730ca6012aa577aaf73dd5108d0b26575eaade0a2380914fe0
-dist/2024-09-04/rustc-nightly-armv7-unknown-linux-gnueabihf.tar.gz=082a2efdf341bdfd9bbe3e2340ae8dbf71bff71908439696d30fa25d00c5fe1b
-dist/2024-09-04/rustc-nightly-armv7-unknown-linux-gnueabihf.tar.xz=0b480d334a3709ca23dfd4839b518391031b6afde4cea0c30f08f160e39592a0
-dist/2024-09-04/rustc-nightly-i686-pc-windows-gnu.tar.gz=bf06c7a0faebb7dbfa2c09d02f506410f05abc6aa2ba54c515f2a429e904de2a
-dist/2024-09-04/rustc-nightly-i686-pc-windows-gnu.tar.xz=c49f577fa788bb6b40350dd9e9f9088ded647f0a5cf5df69135a83d2e085d9ca
-dist/2024-09-04/rustc-nightly-i686-pc-windows-msvc.tar.gz=e42254e299e367c9414c4b61715125410ddc3ecb30f2457e4eb843725c6b6abd
-dist/2024-09-04/rustc-nightly-i686-pc-windows-msvc.tar.xz=91a752b8a61b81281203297712b1bc775a227d9626b4c84d9e10130f428f843d
-dist/2024-09-04/rustc-nightly-i686-unknown-linux-gnu.tar.gz=6f23df634f3e7028d9a6e9989e1edbc2d00e9b435473807f526fd58c150baf3d
-dist/2024-09-04/rustc-nightly-i686-unknown-linux-gnu.tar.xz=de7cef873379e3d5ef80b402b9d98bdf74366de27e8f928125081628937baf76
-dist/2024-09-04/rustc-nightly-loongarch64-unknown-linux-gnu.tar.gz=ef0946845c41e096dced01baf6e843c57fcf695c82d5408a1b7c0a5bbd150b39
-dist/2024-09-04/rustc-nightly-loongarch64-unknown-linux-gnu.tar.xz=d43bb8987a3bb394d7d2cf39d78f54505700525b250cb30741b903bf8712f3bf
-dist/2024-09-04/rustc-nightly-loongarch64-unknown-linux-musl.tar.gz=00013767600b1a5153ed4faa9d227fd55a905c375f712a7ca59573a317684c97
-dist/2024-09-04/rustc-nightly-loongarch64-unknown-linux-musl.tar.xz=cf1c4351f70e951290583213dade06fe4a61e6dcbc2d0e69be54ea91210051de
-dist/2024-09-04/rustc-nightly-powerpc-unknown-linux-gnu.tar.gz=be1957674fdda24a9cd8935789db35a17d3a0d71219bb6f1256af74c64ffc697
-dist/2024-09-04/rustc-nightly-powerpc-unknown-linux-gnu.tar.xz=20541daa3925834012ab68f186a1f1ab4d060cced96646e2142a0f14c04b6ad6
-dist/2024-09-04/rustc-nightly-powerpc64-unknown-linux-gnu.tar.gz=0eb6741b87d430573c9b0d5b9ba9725c0c03caabc01d5ee258867ea19aedafdc
-dist/2024-09-04/rustc-nightly-powerpc64-unknown-linux-gnu.tar.xz=8ad4670b74093e3c7055149649145a4af2b2a3d24a68bf893ed72202cc934946
-dist/2024-09-04/rustc-nightly-powerpc64le-unknown-linux-gnu.tar.gz=2d7b60aa2d4853eba2bb2644cb14768a5a864386da0854aca7c1f6397374dca2
-dist/2024-09-04/rustc-nightly-powerpc64le-unknown-linux-gnu.tar.xz=17792328178392ad96b1a0c05405c61d0b1e7196bdca9e55baebff12a4949725
-dist/2024-09-04/rustc-nightly-riscv64gc-unknown-linux-gnu.tar.gz=2db9fe19d4e1d7f68a0802868d9344e23932190e2d46407523208a67b5ba053a
-dist/2024-09-04/rustc-nightly-riscv64gc-unknown-linux-gnu.tar.xz=f0d4df5e4cfeff06eb2cb07c6f9ac0596130923133571fd1702d56a0251ebb99
-dist/2024-09-04/rustc-nightly-s390x-unknown-linux-gnu.tar.gz=4d3fea9ec53336195c0daa2b2937507c2216537647829466a19acee2ce9e201a
-dist/2024-09-04/rustc-nightly-s390x-unknown-linux-gnu.tar.xz=84ca3dccf7af68a343fed4d209771bac7439149695f63517bd048287f4539add
-dist/2024-09-04/rustc-nightly-x86_64-apple-darwin.tar.gz=f6f43ebb82851edae301033a2cfbd02724849c7fda42294818f3081f74d3a1a3
-dist/2024-09-04/rustc-nightly-x86_64-apple-darwin.tar.xz=55b0db99f02bd4c5595117663f6b6cc739f63723999062ced0096727e627f072
-dist/2024-09-04/rustc-nightly-x86_64-pc-windows-gnu.tar.gz=6cb63e57f9873e40695b735b8cdb9f0de70306f1692161cd8f7767b4016dcf39
-dist/2024-09-04/rustc-nightly-x86_64-pc-windows-gnu.tar.xz=79bf54beceda0a7f6580d3ef336d8deae3991b3b57e4c6aba635f9d848cc860d
-dist/2024-09-04/rustc-nightly-x86_64-pc-windows-msvc.tar.gz=7757651c78d5000926bd5e91996ea8abdc32db8e67b31271cb70680f551edd5f
-dist/2024-09-04/rustc-nightly-x86_64-pc-windows-msvc.tar.xz=4671e03fc7100bac43cf332e387161c0ccde77d3f893a9dfdd27be63fff39932
-dist/2024-09-04/rustc-nightly-x86_64-unknown-freebsd.tar.gz=675f49fc6a51d5e715789bc9ad92b9db12a94a033254e34efb65358700207bb5
-dist/2024-09-04/rustc-nightly-x86_64-unknown-freebsd.tar.xz=f9efc43f26600caf2ef7c8084fe94ae31ba540ae7e9f104e6a587c6e4272cd6b
-dist/2024-09-04/rustc-nightly-x86_64-unknown-illumos.tar.gz=9bd74b7ee78a02306f47640b99d752ea373ffdd88067376d9f03564f07edfb24
-dist/2024-09-04/rustc-nightly-x86_64-unknown-illumos.tar.xz=67c5d546df9fa451d42804de2d439229e9b21eb9329ff16eeadcc52f5b6393d1
-dist/2024-09-04/rustc-nightly-x86_64-unknown-linux-gnu.tar.gz=dfc427db6a14237a12fd077ccc44c07e7bb46a1b2965a3fb1ddd78a2ec334b81
-dist/2024-09-04/rustc-nightly-x86_64-unknown-linux-gnu.tar.xz=8d307dce871ae5f7cc1410e85bb7b38f80aed5c1138030b4f112e727fb8c654b
-dist/2024-09-04/rustc-nightly-x86_64-unknown-linux-musl.tar.gz=b7f84d8aab03afcf2bab8ed21fa3ece6ac418d076e0195381110adfac2aa1fbc
-dist/2024-09-04/rustc-nightly-x86_64-unknown-linux-musl.tar.xz=296083c6b50b7dffe8a62884bac7e831e29487a31c8e6fb319f04f0e62157175
-dist/2024-09-04/rustc-nightly-x86_64-unknown-netbsd.tar.gz=96986595ce82c735b87fe75f00722514c49e7118d38c4bced554c9017377ec91
-dist/2024-09-04/rustc-nightly-x86_64-unknown-netbsd.tar.xz=bf8c9411ff7279fd56bb7e3c68ac29c8ce79ba031317b76aac6a74d20f1511f0
\ No newline at end of file
+dist/2024-09-22/rustc-beta-aarch64-apple-darwin.tar.gz=59b70ccc04680e74bbd1e13368bbf5639679fb8e1e7ba39ae4a235f9a96522f6
+dist/2024-09-22/rustc-beta-aarch64-apple-darwin.tar.xz=d4b18e0a269e7b66dbbdf03d7da6b478c6cff9cd52ef34f110b68a9ff0111d0f
+dist/2024-09-22/rustc-beta-aarch64-pc-windows-msvc.tar.gz=7cc2e8511801c27360e17cc0380e30e5eb6cc185224aba94bf9ed852e5ff2ce0
+dist/2024-09-22/rustc-beta-aarch64-pc-windows-msvc.tar.xz=a9f8f8e691b9a307ddc4468cc34964063253292f18869d21dc91ca437bbc08fd
+dist/2024-09-22/rustc-beta-aarch64-unknown-linux-gnu.tar.gz=5940e8c99d329fae3cc4b1d5709e9481e8f2b1dc799363ae0a1429ea4df4ad41
+dist/2024-09-22/rustc-beta-aarch64-unknown-linux-gnu.tar.xz=c7c36aada972ea10e50e0904530d06b2df074f9981dec4dcc66efeaa16499c1b
+dist/2024-09-22/rustc-beta-aarch64-unknown-linux-musl.tar.gz=2ae2b1e2d90c130be5274806db1e4dcdfe0b588fe72f967e58b128aa1d28a7eb
+dist/2024-09-22/rustc-beta-aarch64-unknown-linux-musl.tar.xz=d8297b214d4ef841bb5963e71353ce08a4d3aead47a2cdf234e0846ad0b1ccbb
+dist/2024-09-22/rustc-beta-arm-unknown-linux-gnueabi.tar.gz=256b62cd5f1bc17c081277752a49d38104ce438e83342e6bbb467442e9250563
+dist/2024-09-22/rustc-beta-arm-unknown-linux-gnueabi.tar.xz=457ea31587b8ff8c9fcc7a9ed4bf958625c7b9e55d640329ccdf432309a6583f
+dist/2024-09-22/rustc-beta-arm-unknown-linux-gnueabihf.tar.gz=4cc8f851eff833100fe4d7c421c25e65d4779d8cdbb9b5e2cb3c8f5ebf9f8e98
+dist/2024-09-22/rustc-beta-arm-unknown-linux-gnueabihf.tar.xz=6ab386aaab687a253b3d28b12307ad5c8df2ea1a0af281a8fab6fe6d24ee6130
+dist/2024-09-22/rustc-beta-armv7-unknown-linux-gnueabihf.tar.gz=0b548c45c2ec840942b29a68ad38debd8a2ec7c920d3be7cda91365e0a8fce80
+dist/2024-09-22/rustc-beta-armv7-unknown-linux-gnueabihf.tar.xz=bc1ce3524199c62230fc08b9dab1282d2f31d3cd1a892cbc8bfab0257e0ff5dc
+dist/2024-09-22/rustc-beta-i686-pc-windows-gnu.tar.gz=a407a4dda4c24e8e9d510843aa9e8f06291622d240538a14c1d924d8b7d84e33
+dist/2024-09-22/rustc-beta-i686-pc-windows-gnu.tar.xz=fe3b235ed043d14856f47babf433ae214d9b64480b1824053fee8b99ca69cc69
+dist/2024-09-22/rustc-beta-i686-pc-windows-msvc.tar.gz=a156aa0fb17b5edf476f97b8e839f9fe550ed3edd63a2fe2936a7fe0f388ece4
+dist/2024-09-22/rustc-beta-i686-pc-windows-msvc.tar.xz=0e46e75722b10bbbd2631c2676089665f92ce092408ed63aa14c99b1fc385369
+dist/2024-09-22/rustc-beta-i686-unknown-linux-gnu.tar.gz=5523e67362db0840d6f0ab6a1deec99c1b64c32fae94362792b0aa031bfd39d6
+dist/2024-09-22/rustc-beta-i686-unknown-linux-gnu.tar.xz=45a820f2ebd182ec3237436a567960d2bd0f92e9e603aa394b1a6eafbd9ba0fa
+dist/2024-09-22/rustc-beta-loongarch64-unknown-linux-gnu.tar.gz=bdbe165ffd50974b32f4b570da7908c125739c0321f700d12cc481f32ab76eaa
+dist/2024-09-22/rustc-beta-loongarch64-unknown-linux-gnu.tar.xz=997a8387989676848355e30dea1b131fa96945e62cef8f011025c52351db1269
+dist/2024-09-22/rustc-beta-loongarch64-unknown-linux-musl.tar.gz=a49f46df49a9aa974ff10361ae29267d2c86c10486399803a5a6879e638212f2
+dist/2024-09-22/rustc-beta-loongarch64-unknown-linux-musl.tar.xz=ee236f4dab4a06d23b6040a47afdf73496bc9093b3b29fae896f5f5bbe87c222
+dist/2024-09-22/rustc-beta-powerpc-unknown-linux-gnu.tar.gz=e83c1253643c4ff70301bab198db731ac65c6d3b0ec847d7aa68bd6afef6ee93
+dist/2024-09-22/rustc-beta-powerpc-unknown-linux-gnu.tar.xz=f7f09a5028ca3f45475cedec7518ead06b2e305554292462d82b2032e5d83f73
+dist/2024-09-22/rustc-beta-powerpc64-unknown-linux-gnu.tar.gz=9ef2829f5b2bc9666bba319875eecbda37840d204f7c1493dce2a4f2f45d45c5
+dist/2024-09-22/rustc-beta-powerpc64-unknown-linux-gnu.tar.xz=140489beedcf46e02931ce8f69e9008ea4c7e3c332d0a3482d4495d7fff21b81
+dist/2024-09-22/rustc-beta-powerpc64le-unknown-linux-gnu.tar.gz=63a34f34425d6c11d62768a3cdfc4602d96ae0f11d82344412a69a3b1ec550b9
+dist/2024-09-22/rustc-beta-powerpc64le-unknown-linux-gnu.tar.xz=108d429397a5cef93151439646b684109d1b619c1a6f11544062e407258f4897
+dist/2024-09-22/rustc-beta-riscv64gc-unknown-linux-gnu.tar.gz=77cb4dea8b55779e0f3de1f48e74de966d3a2dc27946228b42b0eae654d53e5a
+dist/2024-09-22/rustc-beta-riscv64gc-unknown-linux-gnu.tar.xz=93b7dc39c3da7560cbabef5a35dddec111a4d9c0ec0e2b0648925975c5042b31
+dist/2024-09-22/rustc-beta-s390x-unknown-linux-gnu.tar.gz=58b1eed6046552703f8993b36d2a571d12db806ca9665d276c338fc89f79b980
+dist/2024-09-22/rustc-beta-s390x-unknown-linux-gnu.tar.xz=39ad5c20dd703e5949f008ed21e671b1438a1160b4aece5ba434ae03f32004cf
+dist/2024-09-22/rustc-beta-x86_64-apple-darwin.tar.gz=c5082f7773f1573a1f60148ed744f148169b3c58ca38539e72688cb31221003e
+dist/2024-09-22/rustc-beta-x86_64-apple-darwin.tar.xz=a797564192dc84184d5af88ecb4d295ab266cde4a1c4407b06c56f656800e336
+dist/2024-09-22/rustc-beta-x86_64-pc-windows-gnu.tar.gz=0f29dc08756a36f42e9937cf9e2f8c5cc7771fab5b791b58dd7b038dcb20e2ca
+dist/2024-09-22/rustc-beta-x86_64-pc-windows-gnu.tar.xz=9a9f6178208f01487a132ab91ffb1251722df3f6e3ccc7f4b3e79dc389b7217a
+dist/2024-09-22/rustc-beta-x86_64-pc-windows-msvc.tar.gz=2f2b828b46dea57c9896149a5ffc5cc6db368d90067c498f554b9ea75de0990f
+dist/2024-09-22/rustc-beta-x86_64-pc-windows-msvc.tar.xz=42c64410633bf748134ba004ef397f2319556e44fc2862a4f3a5e847e334fdbf
+dist/2024-09-22/rustc-beta-x86_64-unknown-freebsd.tar.gz=9ba0fdecbd343606bbdf2d4b401d64ed5de82e4bd508c0e6b6bcc21365c4b840
+dist/2024-09-22/rustc-beta-x86_64-unknown-freebsd.tar.xz=aeabedce922b315fb872127a6102a76e9fe5e1932b14a7210f31191f9a85488b
+dist/2024-09-22/rustc-beta-x86_64-unknown-illumos.tar.gz=4d5348b0ef100a1691f655acee54447866d76b46f88e23ee641eb5e4b4318b4c
+dist/2024-09-22/rustc-beta-x86_64-unknown-illumos.tar.xz=046b8d0139b97d78a741251ef7094629394f67cbb817a7239de704b4ff3a8963
+dist/2024-09-22/rustc-beta-x86_64-unknown-linux-gnu.tar.gz=81ba8a28534746a9c33c98a98aeeea89f6c057333827d919b2f404991e0ded45
+dist/2024-09-22/rustc-beta-x86_64-unknown-linux-gnu.tar.xz=358bbda124aa68416d55d8ed6c9a184f8ea7ae166f3f0427e8c9ac40900bd4b6
+dist/2024-09-22/rustc-beta-x86_64-unknown-linux-musl.tar.gz=8594ed15236342879b4c486e4d5e2440891e9dec52302e1bb6393008eaf876e7
+dist/2024-09-22/rustc-beta-x86_64-unknown-linux-musl.tar.xz=e45cdb771899998e42bf3f9e965a4b4557199b1632843c0472731d48ea664834
+dist/2024-09-22/rustc-beta-x86_64-unknown-netbsd.tar.gz=ba1d8b89c65441cfe6fa1341c6a7e21dc596df13cef8e8038d8d7ac376bd91fc
+dist/2024-09-22/rustc-beta-x86_64-unknown-netbsd.tar.xz=95fb21a9730eaf815ba6da5f42b997accca0b578870207912a2ea359b588421e
+dist/2024-09-22/rust-std-beta-aarch64-apple-darwin.tar.gz=60127b21a176a56664e537a8e6d81c18c5406706f12e3a406ebad8c86f5fc442
+dist/2024-09-22/rust-std-beta-aarch64-apple-darwin.tar.xz=04d163b5bb40aa4ed7e712006155549eb5ca094e71b89b4a3e5142c40d0b2102
+dist/2024-09-22/rust-std-beta-aarch64-apple-ios.tar.gz=1463a6f3a55b1c7795c0417040423f2dc1d9a3df343ee4bd2d9c96b2de5c84e8
+dist/2024-09-22/rust-std-beta-aarch64-apple-ios.tar.xz=74a06570dd6bd8b501ccdcdf25b9b5ccac25936b883b37be6a0296d5e59394b6
+dist/2024-09-22/rust-std-beta-aarch64-apple-ios-macabi.tar.gz=ccdf0df40f435ca4c5f8d6b67cf06b48c1792d5b1592cb129e7e40e7690c3c5b
+dist/2024-09-22/rust-std-beta-aarch64-apple-ios-macabi.tar.xz=4388b9b3ab0e048b6c8349a3ceae6afc078bdc217172d7ef0271afb5e181fb6f
+dist/2024-09-22/rust-std-beta-aarch64-apple-ios-sim.tar.gz=4428d02fe8e43b5d082149991e88a4c9d342157fa1c2cd91903812240fb5bb08
+dist/2024-09-22/rust-std-beta-aarch64-apple-ios-sim.tar.xz=21f9c521dc8203584ce0c56536818431ec19f259f86b8d8cab5a33f7e44165cf
+dist/2024-09-22/rust-std-beta-aarch64-linux-android.tar.gz=d9d238db60d1e54366cfb4f20e2a6c6b8bc055f83716837970261b074cc93218
+dist/2024-09-22/rust-std-beta-aarch64-linux-android.tar.xz=aab44af6a7f1dc483c943be9fd0b2ade0c938a844acc8deab76843e3dc514355
+dist/2024-09-22/rust-std-beta-aarch64-pc-windows-gnullvm.tar.gz=fccf8f5199da8c0fe2d1dec6ee384c9761f2e6334e5dce28add413f29207e902
+dist/2024-09-22/rust-std-beta-aarch64-pc-windows-gnullvm.tar.xz=d6373d38a862120c08afa569ea9941945b43ce1676f45ca995fb3b30c34500ec
+dist/2024-09-22/rust-std-beta-aarch64-pc-windows-msvc.tar.gz=e0b31c36068626fbf2133a352002cbd8f4c2b6a1b5379a0ab0fd3bc640576e9d
+dist/2024-09-22/rust-std-beta-aarch64-pc-windows-msvc.tar.xz=d10defe0175f8872ebb68d2dd331fa9bbbeb1fa892188371665547567f7f2738
+dist/2024-09-22/rust-std-beta-aarch64-unknown-fuchsia.tar.gz=dda6f7b74035c963dd89a2e003d6c7baca2e2db9bfdd3007f95743e44bd08cb0
+dist/2024-09-22/rust-std-beta-aarch64-unknown-fuchsia.tar.xz=23944ba7752e89e860f19f3c18d2951bb5c7c6b707bd6e06914f7d48aafee40c
+dist/2024-09-22/rust-std-beta-aarch64-unknown-linux-gnu.tar.gz=b00fa5fea66b2af7d173d6405a59c529a1dd0b793d735c2d97fcab7775693ed4
+dist/2024-09-22/rust-std-beta-aarch64-unknown-linux-gnu.tar.xz=34bd748cc5bc0a6b6d8e6d8ea23693d7628bed11ebcd886860cd5c0b31ac3c0d
+dist/2024-09-22/rust-std-beta-aarch64-unknown-linux-musl.tar.gz=ecb1b709c48556fabc527d976e6cc69b8b69384cb4c45e691195a12b9cdba383
+dist/2024-09-22/rust-std-beta-aarch64-unknown-linux-musl.tar.xz=2c90df930935dcf9f9725588ed6579100fdf676267305f715f03e413a04c3032
+dist/2024-09-22/rust-std-beta-aarch64-unknown-linux-ohos.tar.gz=56782db097cca16a0d6e8466b83b35bfd7334d5f48b9ac5c500767eeba30c122
+dist/2024-09-22/rust-std-beta-aarch64-unknown-linux-ohos.tar.xz=9b41b551b5f88dfa3fdcc1d22102f102627c5c88e42353edaceda6da3b76d97b
+dist/2024-09-22/rust-std-beta-aarch64-unknown-none.tar.gz=087fccd0b40fe73a545885a58758eafb86e9bb7b9588d047c9536e5bd8c201b6
+dist/2024-09-22/rust-std-beta-aarch64-unknown-none.tar.xz=60039451dc07ada83944606e67363ca32b22879293bc41a6d66f6545e7e3f1aa
+dist/2024-09-22/rust-std-beta-aarch64-unknown-none-softfloat.tar.gz=0e1f73720beaecff935d0a90272448f5dfb0c912b2e366239c46c6ab3b854cfc
+dist/2024-09-22/rust-std-beta-aarch64-unknown-none-softfloat.tar.xz=c2670b262833415d43b22485c2734d87d8748315e6471a2a384249b2cba6e581
+dist/2024-09-22/rust-std-beta-aarch64-unknown-uefi.tar.gz=edfd391f36b6aa6758649ca6f9706d671956f078e572ea9ce5f9423a1310e817
+dist/2024-09-22/rust-std-beta-aarch64-unknown-uefi.tar.xz=59b09f6cef1d97b273262d3ccdd95d9c46766b82e935cb46538514292cd04a39
+dist/2024-09-22/rust-std-beta-arm-linux-androideabi.tar.gz=f84267d71217b79a5e622a281ce926c1a54ee9122e19b2647d1aa85afa9132be
+dist/2024-09-22/rust-std-beta-arm-linux-androideabi.tar.xz=57e80fea8463416012339fc6f74e9ae4da7d92042d05311bc8a9620fec3541b2
+dist/2024-09-22/rust-std-beta-arm-unknown-linux-gnueabi.tar.gz=556ff5b6947ed37f5215953fbcbe3e82313e7deb9d32d5b86feabe46c8328e56
+dist/2024-09-22/rust-std-beta-arm-unknown-linux-gnueabi.tar.xz=3f0721bc56fa232ca4203dcb43f1ef8f453373d9a0fa4720d89c51b827407a91
+dist/2024-09-22/rust-std-beta-arm-unknown-linux-gnueabihf.tar.gz=57b81555f7d7695e985e1538795c97b9f0573cd84d6fda25a09d49ac54bd1a24
+dist/2024-09-22/rust-std-beta-arm-unknown-linux-gnueabihf.tar.xz=66d5af25be1dfc99fbeb1aa0c7eee30dc2d3e5766affb73e6e7c0e7b9a78abff
+dist/2024-09-22/rust-std-beta-arm-unknown-linux-musleabi.tar.gz=23cfcb1cde1e95f55442ebb8ba155a0e13ec932cd7a8ab20a2ad09596a79b3a4
+dist/2024-09-22/rust-std-beta-arm-unknown-linux-musleabi.tar.xz=660d3f7b05da3d5b01775989546a687fe40090d193289c3ad24317c07c5eb445
+dist/2024-09-22/rust-std-beta-arm-unknown-linux-musleabihf.tar.gz=ee453c78eacca64fd0a6f1c066a6728ddca0ecbd6e184b63a4b4455f77183f07
+dist/2024-09-22/rust-std-beta-arm-unknown-linux-musleabihf.tar.xz=b003790997ebe0bfa095b0fe38db67db179a2f9e93f4b49852f5ec04828337f4
+dist/2024-09-22/rust-std-beta-arm64ec-pc-windows-msvc.tar.gz=60f03912a464169464800a603606e2cb8a302c998bd59f582cdd3b9bf39ecc82
+dist/2024-09-22/rust-std-beta-arm64ec-pc-windows-msvc.tar.xz=6d1858acf2f2cfb3daac89ae21cfc7a7df3e1f57dac0aaa3ee70057b1974c0f2
+dist/2024-09-22/rust-std-beta-armebv7r-none-eabi.tar.gz=b23fd4380d20e289e58b86afaad1df0636004c74a03d7f3ff861f26c6ca308f8
+dist/2024-09-22/rust-std-beta-armebv7r-none-eabi.tar.xz=beac209cec83a56315c109fc3a0e3b6b16f8044de270e23cdd9dc3e2b5db3af3
+dist/2024-09-22/rust-std-beta-armebv7r-none-eabihf.tar.gz=731064c4b9b35d420f740ff5fbc4f6dd1f038e3225db19ca861af6db5f283ea7
+dist/2024-09-22/rust-std-beta-armebv7r-none-eabihf.tar.xz=04b406b44da8aee6a077f9f971b5ba62bc98fb09413fe47fd892c67798381d5b
+dist/2024-09-22/rust-std-beta-armv5te-unknown-linux-gnueabi.tar.gz=26dc6030f28453478e790879547f22a63ae810572cac790d4ed944eb68c96d87
+dist/2024-09-22/rust-std-beta-armv5te-unknown-linux-gnueabi.tar.xz=2aa9589c9512388e75c3c93e53b6a90ce5c973d98830a64388b0ec22618504c5
+dist/2024-09-22/rust-std-beta-armv5te-unknown-linux-musleabi.tar.gz=0020c2142cef0ab6bd62c4212f01dce2675104e0da5e701cbf03ee7c45a0fb2c
+dist/2024-09-22/rust-std-beta-armv5te-unknown-linux-musleabi.tar.xz=b891ccdcbd8abf7d56d31b84800a17cbe1f6d4242584598433e38eff5a9a16c0
+dist/2024-09-22/rust-std-beta-armv7-linux-androideabi.tar.gz=128b86795a07b47088fbc51a251f6b112379454940878150547b54ffb95890e9
+dist/2024-09-22/rust-std-beta-armv7-linux-androideabi.tar.xz=26497ef07fb7f42198b4fc02b122497fc09bd215eb7e3e01c789b481bd2d86ae
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-gnueabi.tar.gz=933f22ab901b9de042b17548e0218de699275a8553b8056d2d85430858f4e1bc
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-gnueabi.tar.xz=495f8186e0c589882d1e1f1cf21ab28ea5531bad327b6d5ae1ca83d26c77944e
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-gnueabihf.tar.gz=53c87859857618a011e94c14c5641927503c5543831acd16498d7fb244eb00b8
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-gnueabihf.tar.xz=7ee039186087e320396e56cdd9e5a6b7993c44783e3a80fd86e74e41be646a57
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-musleabi.tar.gz=fa9f256a201c4fe5cd95363c2cb02d87565a321e27554e83d63f1d61ed55dfda
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-musleabi.tar.xz=fd3eced91b52924bb6d4acb3cc6c3bd7b45a1879e353f22442cb1e76ed5a7f28
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-musleabihf.tar.gz=b683d929fd6a6b60a786ec154970338158cc2b7bce28601b70966b898017b131
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-musleabihf.tar.xz=518fa28ee0292b95322bea4c0b714146a1b94c730e49bb6a84038520c91a668b
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-ohos.tar.gz=d0f8659cddfc6da0b0dd815794f86ec1ffa0a243020dc9190c4358c6cdc03fdf
+dist/2024-09-22/rust-std-beta-armv7-unknown-linux-ohos.tar.xz=89f39595aa42f23efa2b3853c466cddd6a932043bae3373193c25b788c15efd6
+dist/2024-09-22/rust-std-beta-armv7a-none-eabi.tar.gz=c1fc1973cc683c313e50542f1a6b69f1b5a5b4ac558b45954f79ef4dff9d5f75
+dist/2024-09-22/rust-std-beta-armv7a-none-eabi.tar.xz=00c45dfc370ea40d8993519bdb5cce8f5167401434f0b7553b6fdf7c5b49da87
+dist/2024-09-22/rust-std-beta-armv7r-none-eabi.tar.gz=ef54f8762f1d190b822e58b845889ac9c2dba4250cf0d693a3b1cbf64e2cf8a2
+dist/2024-09-22/rust-std-beta-armv7r-none-eabi.tar.xz=9375a15e96f7b3da4394bcda8ce34c452417f4278f07926830d5b00b155cb338
+dist/2024-09-22/rust-std-beta-armv7r-none-eabihf.tar.gz=85a5ae26f11c47872649699eaf01557aac746831b4c30de7b892438cc736b679
+dist/2024-09-22/rust-std-beta-armv7r-none-eabihf.tar.xz=e9dde209b4e0de6ae76b316c5e3aa2923f208bd9aa7858fef5177ba2e3b06119
+dist/2024-09-22/rust-std-beta-i586-pc-windows-msvc.tar.gz=652bc4cbf176d0780a81cff637684fd8f1cdc99c7a58d68325f54564942d46dc
+dist/2024-09-22/rust-std-beta-i586-pc-windows-msvc.tar.xz=367eca53e9c4be297454751d2d8b7f5503caf669962a44ea92290b0772969fb6
+dist/2024-09-22/rust-std-beta-i586-unknown-linux-gnu.tar.gz=7c48fb48b02628358ae3572c92d5cc112734e99606c78d04b29e665ee03f36ec
+dist/2024-09-22/rust-std-beta-i586-unknown-linux-gnu.tar.xz=4ac829df3b8b5e7864b883713a90ed18a9b08f45a3da2af2c6b3f700c8d7c27c
+dist/2024-09-22/rust-std-beta-i586-unknown-linux-musl.tar.gz=7786d5b5e0cb8489df5456854cbbdfefbb8b4a3755f61e62747abc224e48dfc6
+dist/2024-09-22/rust-std-beta-i586-unknown-linux-musl.tar.xz=e2ec9458a99a159480a45b8107041b3b4054316ba15adaf802690d2bf66b2f22
+dist/2024-09-22/rust-std-beta-i686-linux-android.tar.gz=54edc2ca229e1a5aad5077800c492cf5038da341555eda11fc4b77d1a3896def
+dist/2024-09-22/rust-std-beta-i686-linux-android.tar.xz=a75135f1e04b716855fce5b830797ea87bd428d54c06190cc8067ba5952d7215
+dist/2024-09-22/rust-std-beta-i686-pc-windows-gnu.tar.gz=4c5b54eecd6efbb03a3a01f57c265d47c49df49dd584e67b493205fcec92a59b
+dist/2024-09-22/rust-std-beta-i686-pc-windows-gnu.tar.xz=7ec6292ac497b450277c17cca3ca87321d5b6bd545bd479b37698ceebdcbf719
+dist/2024-09-22/rust-std-beta-i686-pc-windows-gnullvm.tar.gz=0deb2de1b9830099bb6de1bb99e4658c8e4e3438e555f239c85309b771293e6b
+dist/2024-09-22/rust-std-beta-i686-pc-windows-gnullvm.tar.xz=f35566df72b302dd446d449ffc8a775015b30970911c5284a3d4c1866e004a6b
+dist/2024-09-22/rust-std-beta-i686-pc-windows-msvc.tar.gz=17e505c8ece5c89988896b1c14400b203e2588bc7777189bef89335cc868fb1d
+dist/2024-09-22/rust-std-beta-i686-pc-windows-msvc.tar.xz=197fe430d6fce984ca397ba664beb25d4a0216180cd8fc2797710a8c541573a8
+dist/2024-09-22/rust-std-beta-i686-unknown-freebsd.tar.gz=9d7ff528d75e80ebb8255c9b6ef3f5ec6db579524e03dc3aad540690401fb7b8
+dist/2024-09-22/rust-std-beta-i686-unknown-freebsd.tar.xz=81152e616efe27a4ae80d2ffc86b79211c31ab324faa7847606f6ed839a3d470
+dist/2024-09-22/rust-std-beta-i686-unknown-linux-gnu.tar.gz=b1913a26f2258531596e1ef31fc42d720f807f04b068802ea3a0164d877d694c
+dist/2024-09-22/rust-std-beta-i686-unknown-linux-gnu.tar.xz=3be89fd0c0f0a5b6d5cea23feffd32573be29ec1ce6c96b88ac35e04cf1eaa46
+dist/2024-09-22/rust-std-beta-i686-unknown-linux-musl.tar.gz=e446e4cbb904f89fbaf7bd48be6975671db2cc2ad018fc03e967dff2bbce0e3d
+dist/2024-09-22/rust-std-beta-i686-unknown-linux-musl.tar.xz=453d6a6b1872e884aeae40936e950b7c2d0ce291c9f5882fc9c15a6b3e9c86fe
+dist/2024-09-22/rust-std-beta-i686-unknown-uefi.tar.gz=a330462d4b0ade7028d2c2bd8764b1225cc9eac90b014c8899f971fadf002cba
+dist/2024-09-22/rust-std-beta-i686-unknown-uefi.tar.xz=8fdb9e12d0cf92e0c4fcbcdc57daceb2cf17b21786e1252904ec0faba4b90a9d
+dist/2024-09-22/rust-std-beta-loongarch64-unknown-linux-gnu.tar.gz=82859d2feb163fa7ac068db184e8c76261771dc47838bd952301ffd8037d885a
+dist/2024-09-22/rust-std-beta-loongarch64-unknown-linux-gnu.tar.xz=1fa1ae996cd7010b4ab9006bfcb69098fcadbfc7a8f6988bdd34c62d2d6309f3
+dist/2024-09-22/rust-std-beta-loongarch64-unknown-linux-musl.tar.gz=e4200a2c1eb5a1420071fde891266849da5d46aaf46031129ae329175a3708f8
+dist/2024-09-22/rust-std-beta-loongarch64-unknown-linux-musl.tar.xz=15fc279f0c1370d05543af48c493d91687e3de2dc25123a1b657919494a0653c
+dist/2024-09-22/rust-std-beta-loongarch64-unknown-none.tar.gz=4cc49f8231bca8c19e4d449cf3b3cd84d5db9e4665394ebada29ea626cee4dc4
+dist/2024-09-22/rust-std-beta-loongarch64-unknown-none.tar.xz=b3b7959a696c75575edb3676520f64178151df1d523128c6ed6e28cd0c8051b9
+dist/2024-09-22/rust-std-beta-loongarch64-unknown-none-softfloat.tar.gz=7b15fd753967116653b4372e10796ae2ea35910872f517a2d1c6dd3539717915
+dist/2024-09-22/rust-std-beta-loongarch64-unknown-none-softfloat.tar.xz=87f88922e5c3a17af392bade5af1ce94f03aac275e6ed3dbadc9d6c720223c7f
+dist/2024-09-22/rust-std-beta-nvptx64-nvidia-cuda.tar.gz=f1d4f6887d12f1316bcf515bd07f9474bb9e036dfe78171720d72e98de580791
+dist/2024-09-22/rust-std-beta-nvptx64-nvidia-cuda.tar.xz=2dcaa78854d5b619e9609db70fa805cdf1e5baf2fac35f3eefb66ae854e78891
+dist/2024-09-22/rust-std-beta-powerpc-unknown-linux-gnu.tar.gz=c4ae30e180d94550da74b09f6005a6224136d8b5d752e9cdb1b44081a95b8c9f
+dist/2024-09-22/rust-std-beta-powerpc-unknown-linux-gnu.tar.xz=c6438a341e8008b3c475e3250d52df2cb0a505862a14ed70e89884086a56e54f
+dist/2024-09-22/rust-std-beta-powerpc64-unknown-linux-gnu.tar.gz=8ff723f008f1ff81541f2f14d68ad1e77a2842577dcbe4f5109f6c54fdc42726
+dist/2024-09-22/rust-std-beta-powerpc64-unknown-linux-gnu.tar.xz=c5704ef9d690721790d127ca341e4747d572bd34f636894fe897d23660a11467
+dist/2024-09-22/rust-std-beta-powerpc64le-unknown-linux-gnu.tar.gz=13d46982612f710d7aacf1a9636502418fdc673dde21641e1c52d2c55c8c35a1
+dist/2024-09-22/rust-std-beta-powerpc64le-unknown-linux-gnu.tar.xz=9e33e5c0ffd8511705258a741b448e167fdb13229d1d8bb36ef0b41a1f9c49ec
+dist/2024-09-22/rust-std-beta-riscv32i-unknown-none-elf.tar.gz=f7e0cc15730cfcd05ac904a3fb6012a99310c15402db19e915860fc4bc1f55ce
+dist/2024-09-22/rust-std-beta-riscv32i-unknown-none-elf.tar.xz=af179ee477d53727d01feeb704776370482f8aa6f6bd51d7dcbcf90010d36b74
+dist/2024-09-22/rust-std-beta-riscv32im-unknown-none-elf.tar.gz=9673565000aebce56cddf905d27ec651d2c2845e9a2768ec38d10e18443924d8
+dist/2024-09-22/rust-std-beta-riscv32im-unknown-none-elf.tar.xz=38a5d0812838d5596a7a4804ee46e97bc5f4814056f93ad0988b7f2f34a90325
+dist/2024-09-22/rust-std-beta-riscv32imac-unknown-none-elf.tar.gz=cb397f91bf2c66a0f7d704c320964885aaeacec90a0f562358e8678e749c1e64
+dist/2024-09-22/rust-std-beta-riscv32imac-unknown-none-elf.tar.xz=ff95fa7f5598ed1f25e2aa0be9fb89ef0a7b145ffa9bcba7479bb3c0d83808b5
+dist/2024-09-22/rust-std-beta-riscv32imafc-unknown-none-elf.tar.gz=9049a87a4bea3319c7bf8162d5289ce252897e3ee637a0b6bca841c3507b98c4
+dist/2024-09-22/rust-std-beta-riscv32imafc-unknown-none-elf.tar.xz=e24970b400b30728a9ee5202b0fdb9734c115e015178817629220390badb7e50
+dist/2024-09-22/rust-std-beta-riscv32imc-unknown-none-elf.tar.gz=aa06101ff7386aac69a1dafeb39645344fae3c0ca02537078029c4ba073aa1af
+dist/2024-09-22/rust-std-beta-riscv32imc-unknown-none-elf.tar.xz=13e358d57a5bfe3e4ca2c8ca5e6c8d026cfac417b3c050ebd9bcd5d24f3a5f6c
+dist/2024-09-22/rust-std-beta-riscv64gc-unknown-linux-gnu.tar.gz=5d880502cba47ed72006ef6e60fe004885c0f215d589a20456d41dcec8238503
+dist/2024-09-22/rust-std-beta-riscv64gc-unknown-linux-gnu.tar.xz=a242f39d05716b72aeebdf83357835bae0d2386feca6759f343721148b7a0d4d
+dist/2024-09-22/rust-std-beta-riscv64gc-unknown-linux-musl.tar.gz=117ec2433159f057fcd7fbae9d85042979340ab00f8d1b940c3adc5d3c791803
+dist/2024-09-22/rust-std-beta-riscv64gc-unknown-linux-musl.tar.xz=be0f262d8ed5122fee6b67abd4b78e419839e4005cfff1db9813ae655fbea23f
+dist/2024-09-22/rust-std-beta-riscv64gc-unknown-none-elf.tar.gz=78e28d3d341cedd0fe5ef0036b3b3c246b9f86e5e61d3bfd7e03e95d03920985
+dist/2024-09-22/rust-std-beta-riscv64gc-unknown-none-elf.tar.xz=43bb14df9b4947f111c1e4ba9c4092b73a895c9431a299e4b076d387477f5687
+dist/2024-09-22/rust-std-beta-riscv64imac-unknown-none-elf.tar.gz=e325c2ad8623b87456c12e17b29aa7f52ad243971002b4763677052f9b305eff
+dist/2024-09-22/rust-std-beta-riscv64imac-unknown-none-elf.tar.xz=ca02e01254defcfbf0a48ab574dc4b5aecd6a6be2ddc835704986284916019d8
+dist/2024-09-22/rust-std-beta-s390x-unknown-linux-gnu.tar.gz=79044a23a910bfd8488c382a3d2eab0c6a7ba9677165878b02f28a6c75d3a0b5
+dist/2024-09-22/rust-std-beta-s390x-unknown-linux-gnu.tar.xz=6a1196d2b2f30e22497a739e3b1ee302339ed442e0b807c707d1c4eb7c53ff3b
+dist/2024-09-22/rust-std-beta-sparc64-unknown-linux-gnu.tar.gz=fa3ad826bcf924094ad5cf19779fbfa70f656c1d2e66f4aee5dcf51792af74f4
+dist/2024-09-22/rust-std-beta-sparc64-unknown-linux-gnu.tar.xz=d5f701446546c6cb64b413be37f3c4a0739010f25616b6a295adfcefb16e8642
+dist/2024-09-22/rust-std-beta-sparcv9-sun-solaris.tar.gz=1ac5c327d5a0d0256d16968aab3bf35828c995c818ba73788421da56404f165e
+dist/2024-09-22/rust-std-beta-sparcv9-sun-solaris.tar.xz=fd6c7f163d2d6006eb85cc68e2794850f82dfe09f9173390cd0c167d90622d8d
+dist/2024-09-22/rust-std-beta-thumbv6m-none-eabi.tar.gz=8f082a38dfe968d8f987bfec0822e221d0ab8ab73dfd451b63de7644ccaeb239
+dist/2024-09-22/rust-std-beta-thumbv6m-none-eabi.tar.xz=044bca675ac6b621ced7f2bc9a9909814c0b0818505ca1bfcd765c1859a9ed7f
+dist/2024-09-22/rust-std-beta-thumbv7em-none-eabi.tar.gz=f3e1789a409b58b9769db8587ddbd21352e6634ff5a508b6ad82237cc85409be
+dist/2024-09-22/rust-std-beta-thumbv7em-none-eabi.tar.xz=5f36d0504401bf6cbd2eed78e4575a190300ae26c581ee8599ab8d6e32dfafaf
+dist/2024-09-22/rust-std-beta-thumbv7em-none-eabihf.tar.gz=a0ed6b4c71570e900e1605302ef865f7df9405e19245ed45ff5f7654eb3cbea7
+dist/2024-09-22/rust-std-beta-thumbv7em-none-eabihf.tar.xz=6fd7fac23460b49ca5246a6471de4f39d92764231ef2eac5f51d177c9d14ce2a
+dist/2024-09-22/rust-std-beta-thumbv7m-none-eabi.tar.gz=21e1983e3f9c481677db7c839d5b2b301bae748ef52e1d0b5c3fbf9347732c66
+dist/2024-09-22/rust-std-beta-thumbv7m-none-eabi.tar.xz=ade8b1a2c128c298ba1d20ea7c7585af2a2b3a17b55a8dc6d39f0eebf0f01e66
+dist/2024-09-22/rust-std-beta-thumbv7neon-linux-androideabi.tar.gz=29c7c493c9fee6afa8aea0f337da66118216ee21b373303432ccfb6375cd8428
+dist/2024-09-22/rust-std-beta-thumbv7neon-linux-androideabi.tar.xz=d63e1c8cf97c0834a3825d9a552ed0ce744b2471028f49cbad6f7df1f7bfad7c
+dist/2024-09-22/rust-std-beta-thumbv7neon-unknown-linux-gnueabihf.tar.gz=0cec39208ae369c146d49dbc98984edb993c318a5dcbff205d3fa6b651400bc0
+dist/2024-09-22/rust-std-beta-thumbv7neon-unknown-linux-gnueabihf.tar.xz=158f249f6446503ad5c558dba966ca69f57161aa90fa995a9e9b68fb3e38e732
+dist/2024-09-22/rust-std-beta-thumbv8m.base-none-eabi.tar.gz=8df09685f21eb9285adff2493ea6a9b3a04ce2e24b0761a47b44f0257b3485ff
+dist/2024-09-22/rust-std-beta-thumbv8m.base-none-eabi.tar.xz=0a119d100a6bddf66047e98d453b8c54ab0952712c38b1e396bbef81114d4423
+dist/2024-09-22/rust-std-beta-thumbv8m.main-none-eabi.tar.gz=e7e234a7a8f687f0649654f562b12e09d332229dfd9e8d81a780afd9d8eac8ea
+dist/2024-09-22/rust-std-beta-thumbv8m.main-none-eabi.tar.xz=a3c6c68ad6c24d080af8034168b36bbb24edc30e1fce2ac91bc3fa09ac34a678
+dist/2024-09-22/rust-std-beta-thumbv8m.main-none-eabihf.tar.gz=1662be2b7ec3db6331ef545ac59c844733c3d1cdc728aef78049fecf37a416c5
+dist/2024-09-22/rust-std-beta-thumbv8m.main-none-eabihf.tar.xz=b19dd77e7582da1785f78e85e39a9d966c7a747641e6772dd18cbd489b4940b8
+dist/2024-09-22/rust-std-beta-wasm32-unknown-emscripten.tar.gz=a7ae18e142b5b7a3fbab372bbf4e829626b52a67a10496f2cdecc89aab029310
+dist/2024-09-22/rust-std-beta-wasm32-unknown-emscripten.tar.xz=75a9a2dae5117b714a08024588cb4f5e5a6f07f28af55013f49fbe7cc8e2a690
+dist/2024-09-22/rust-std-beta-wasm32-unknown-unknown.tar.gz=25bf0342788e03ad52ee4835f280f3d92bf2324db3acfcf2654c5f5d37d43431
+dist/2024-09-22/rust-std-beta-wasm32-unknown-unknown.tar.xz=21798a2663b6d0e7347404666d5341b51c5d5de108cd68efbd1466b7c4002a62
+dist/2024-09-22/rust-std-beta-wasm32-wasi.tar.gz=02c1fcc01d28005432f6e53b6f8cecda2b555d482f713ec70ac92b1507121ec7
+dist/2024-09-22/rust-std-beta-wasm32-wasi.tar.xz=f2b4ae22141d39202bddd45e3373a8520684dd71460ceb3cdc9bc7d09aedd774
+dist/2024-09-22/rust-std-beta-wasm32-wasip1.tar.gz=f59a67c3acc927e72278f66553cd10bb3d81e16045c76671d38d09c8a462c78f
+dist/2024-09-22/rust-std-beta-wasm32-wasip1.tar.xz=0f4eea80dcd13008f55d7120f2239aed87a6dcf693f70983caffc36a4be72ffb
+dist/2024-09-22/rust-std-beta-wasm32-wasip1-threads.tar.gz=2581846fe64f1d9547ec293875be715251174c5b163a7c533dcae81fd55ea6d6
+dist/2024-09-22/rust-std-beta-wasm32-wasip1-threads.tar.xz=ad6d869148eea87192f786fca0302983094b25a1afec2813012ba3133e8994c8
+dist/2024-09-22/rust-std-beta-wasm32-wasip2.tar.gz=091057da389eb1d464353acca41e158130f969ad20f90827a4dc38bd363a68fa
+dist/2024-09-22/rust-std-beta-wasm32-wasip2.tar.xz=c91b4440326443a4987758ac161b79f5aa30d23662a5c99a3c0adfedc0eb8e51
+dist/2024-09-22/rust-std-beta-x86_64-apple-darwin.tar.gz=180a9b1d5fb71ec3e88dd4e3a88f6f1da433a191125ecdf98c0169bd7b0511b3
+dist/2024-09-22/rust-std-beta-x86_64-apple-darwin.tar.xz=7d066c7b394c5b15027472fa388b9379ae8a7d4a990e02c0785f63a6f1b7f0c7
+dist/2024-09-22/rust-std-beta-x86_64-apple-ios.tar.gz=4ebdf9f16075859830e76e40547d1d56230ed8715e57f254c82d467634aa63e5
+dist/2024-09-22/rust-std-beta-x86_64-apple-ios.tar.xz=0bdcf11914a169b86b945df232a30c69f991393e3871956b55ca88a0ad65bf79
+dist/2024-09-22/rust-std-beta-x86_64-apple-ios-macabi.tar.gz=45ea8961f12b31e8404ebd178586711f7e4d4729d96ee298623240d8163766aa
+dist/2024-09-22/rust-std-beta-x86_64-apple-ios-macabi.tar.xz=a36a3ed36c0224edaa5161b1c2cb7acb2736d0c2845d56064bde1c94af4e2db1
+dist/2024-09-22/rust-std-beta-x86_64-fortanix-unknown-sgx.tar.gz=8d217487118140549fdc2223954d38a7932a2e9004a07924f853139395f8d88d
+dist/2024-09-22/rust-std-beta-x86_64-fortanix-unknown-sgx.tar.xz=66d7b8cc0b92af4f0458eab631faee6069c3bdf8e35200fa3d573177b1b354c8
+dist/2024-09-22/rust-std-beta-x86_64-linux-android.tar.gz=7efbe112fdf33d55ada19f3803b2552796d1027281b6c652a19465e4902a22bf
+dist/2024-09-22/rust-std-beta-x86_64-linux-android.tar.xz=cacbf59cc9bad0a212d9fb86c81434350fb0b4842918bf7dc51fe978d21402b6
+dist/2024-09-22/rust-std-beta-x86_64-pc-solaris.tar.gz=073833d7b60d396be6890552f7068e885dc0fd4536e5049e88d97c71df31f126
+dist/2024-09-22/rust-std-beta-x86_64-pc-solaris.tar.xz=c6cbc8c41eb2e071cad032ae7587c5ae2e841f1d074c328229e3b7f271fe9330
+dist/2024-09-22/rust-std-beta-x86_64-pc-windows-gnu.tar.gz=0b5c7c007faa77fb28fe7cf275846f23adf0aa3fa1338dc93f86c05f7c605ded
+dist/2024-09-22/rust-std-beta-x86_64-pc-windows-gnu.tar.xz=c1ec0ad342ec630f2ed909c54b0ca7f9073a85977da3a86eb5ef68d5c13ad4b9
+dist/2024-09-22/rust-std-beta-x86_64-pc-windows-gnullvm.tar.gz=5cf9a1daad4b60f7946adbdc9bde0d0d3ce438902f0a158f5f4f423f10960886
+dist/2024-09-22/rust-std-beta-x86_64-pc-windows-gnullvm.tar.xz=d8cfeec61cbbf6bb1b4234bd53a777ad2157def8dc232ba4b5f16bc81f4f1524
+dist/2024-09-22/rust-std-beta-x86_64-pc-windows-msvc.tar.gz=795ac3edcb9f0f10f36a19be14641918b5b0d647d5cc38e8652040437e409538
+dist/2024-09-22/rust-std-beta-x86_64-pc-windows-msvc.tar.xz=dacb5baf49d2b3dd8727a159f8fd348967f987a95162e587c8e5add57dd6d31e
+dist/2024-09-22/rust-std-beta-x86_64-unknown-freebsd.tar.gz=089f99e1cbeab86b5d7ba9d582c5771c8d229ece1f81ad110716618823692deb
+dist/2024-09-22/rust-std-beta-x86_64-unknown-freebsd.tar.xz=8749c2ae47644c16f62a310500ab91e5403a25c3e023a2c6e25cfa16217c98e9
+dist/2024-09-22/rust-std-beta-x86_64-unknown-fuchsia.tar.gz=becef9619e8ad1d4de66796c5877fd9798e5c943fb93a893aacd7819465f8a15
+dist/2024-09-22/rust-std-beta-x86_64-unknown-fuchsia.tar.xz=3801cc566789ae0313a5d10159cd0c94cbbcd8636409ba69ace73fae972ce2eb
+dist/2024-09-22/rust-std-beta-x86_64-unknown-illumos.tar.gz=ba74cfa20f8c53865d96d26b9aaaa7abebf2269d1c3fe2bcd70e3cd7bd4e78d1
+dist/2024-09-22/rust-std-beta-x86_64-unknown-illumos.tar.xz=8f0a00cb53e21c90d60eb02853412d4cf671a1667bbbf7fe9a64183d966a9e48
+dist/2024-09-22/rust-std-beta-x86_64-unknown-linux-gnu.tar.gz=1188997812bfef02c93a13a7d31a9df560383a875bb6a3cbdbb03eaf5fa0d649
+dist/2024-09-22/rust-std-beta-x86_64-unknown-linux-gnu.tar.xz=12583cfd10835abf0f340fe8e141683cdce3e4df5a00998a04361b59203321e6
+dist/2024-09-22/rust-std-beta-x86_64-unknown-linux-gnux32.tar.gz=854f01a511c01b003facf4beb89a511395f0efcdc2284ad279b92837349eaa95
+dist/2024-09-22/rust-std-beta-x86_64-unknown-linux-gnux32.tar.xz=b016d4584a44064feee64de50963ccfbfaaecb792c88c97a079f279a0c1df955
+dist/2024-09-22/rust-std-beta-x86_64-unknown-linux-musl.tar.gz=912eea9c27b6fd251c5b92ae24d6321d5effe9586dbbd473e16a8dee2b758291
+dist/2024-09-22/rust-std-beta-x86_64-unknown-linux-musl.tar.xz=96bf10ef8fee6f8571b6601ab89e65562a91312502630c139d986b6e1ec9fbac
+dist/2024-09-22/rust-std-beta-x86_64-unknown-linux-ohos.tar.gz=09e42b412f0891d608a9d4030203fe09645fc763ecad4be5ae790122a5d01f4a
+dist/2024-09-22/rust-std-beta-x86_64-unknown-linux-ohos.tar.xz=dd84077f22ac4abea1c143d5d293425a85fad62ac65a4b31f18b9100c4e1076e
+dist/2024-09-22/rust-std-beta-x86_64-unknown-netbsd.tar.gz=9aa5fa7bf57fbb95c3a6f718c0a2b62f32c6d1c9ccf93b392d4e166d311e0833
+dist/2024-09-22/rust-std-beta-x86_64-unknown-netbsd.tar.xz=765cf1a81b03ce210a88e87404a64d5b378f6615e428c385fac7a33b646f1276
+dist/2024-09-22/rust-std-beta-x86_64-unknown-none.tar.gz=e00c50362ffc95a1704912ea35c7b1792ead7906d98937fd73b9fa9fe31a520c
+dist/2024-09-22/rust-std-beta-x86_64-unknown-none.tar.xz=280cf203356db9c32898197a3b5954901897a5b3059547f67c59cf5780c46386
+dist/2024-09-22/rust-std-beta-x86_64-unknown-redox.tar.gz=77069fcc33bc481ac8e18697884c1f3e3004a5fe5b265acb419b5f60c03fd2c9
+dist/2024-09-22/rust-std-beta-x86_64-unknown-redox.tar.xz=254dba227a76cb476fbc2a897169713969bf00f691ef77e03d303473db130523
+dist/2024-09-22/rust-std-beta-x86_64-unknown-uefi.tar.gz=4f1fb25ef423ab3cd5577f3e081771494978998acb8c04dda9de8a7d56cce985
+dist/2024-09-22/rust-std-beta-x86_64-unknown-uefi.tar.xz=fc21de2770ff0d0eb44d0939db5b274b0f408eb1a904c9eaf4db4c9463b5ff8d
+dist/2024-09-22/cargo-beta-aarch64-apple-darwin.tar.gz=489c1b6aef3a7275e2e7a644677dde933a738534966089fe28c52c61dff04f2c
+dist/2024-09-22/cargo-beta-aarch64-apple-darwin.tar.xz=5fe4d6a15e4f51f0575f2aee12eb644a95e548a4f03a80835296c44b1daf18a6
+dist/2024-09-22/cargo-beta-aarch64-pc-windows-msvc.tar.gz=5c5c408b026e0332c4e5d816c7a6a961ae5af0174f02b793edd613e56c672494
+dist/2024-09-22/cargo-beta-aarch64-pc-windows-msvc.tar.xz=4e060bccd78dc8abba7c7006585103b6bfa473a0f1cdd9e2c6b10d4fb8294f8c
+dist/2024-09-22/cargo-beta-aarch64-unknown-linux-gnu.tar.gz=45cee09ecd3655b3a822b9c85e3f61f8e40b3fb510728503a3691f56ce415274
+dist/2024-09-22/cargo-beta-aarch64-unknown-linux-gnu.tar.xz=d8902eb0c3a725ef6345d325907ac10a7eb81e274c59aa589bf05aedea5958cb
+dist/2024-09-22/cargo-beta-aarch64-unknown-linux-musl.tar.gz=67e6658e39c0381554ac025c26564888804eb9d8a3e1178726652fff03bc21b4
+dist/2024-09-22/cargo-beta-aarch64-unknown-linux-musl.tar.xz=427e7a4781dcdd2e316eb0c2751257597b4af58da8a5fd8407a8402814b65148
+dist/2024-09-22/cargo-beta-arm-unknown-linux-gnueabi.tar.gz=735d1b824d3a375a6b9c5a5d22fb5e607d3ad06ff70cebe81b84007967c6a5c7
+dist/2024-09-22/cargo-beta-arm-unknown-linux-gnueabi.tar.xz=749c017f8c25d0df23a160e02a765bb5e967f7657fdf3105d0d7ce64afe83524
+dist/2024-09-22/cargo-beta-arm-unknown-linux-gnueabihf.tar.gz=050ae56d0398150212a75493562e6654cc14b7a1ebd6051bde146b5d408d24c8
+dist/2024-09-22/cargo-beta-arm-unknown-linux-gnueabihf.tar.xz=1088b61e20981dabe406ff52965f48ab1542dd84d9673f7d56b21145d0b604b3
+dist/2024-09-22/cargo-beta-armv7-unknown-linux-gnueabihf.tar.gz=43dfb8491dcb64b91e6786366300a0ee3fd00f1815cd84f3bb4247e6b723a6d6
+dist/2024-09-22/cargo-beta-armv7-unknown-linux-gnueabihf.tar.xz=90266fcba10bd88e1f8f5d8420ee6835fe3e337dad1cc43ab7ef79edbe1a1b98
+dist/2024-09-22/cargo-beta-i686-pc-windows-gnu.tar.gz=6dca2e273600ee0f92a416901a7713ffd6db420b953e62d51d95bc85c1dbe27b
+dist/2024-09-22/cargo-beta-i686-pc-windows-gnu.tar.xz=36fa46c7edcfc881568435f366e76f1989479356d93b8982981658fd44b80f4d
+dist/2024-09-22/cargo-beta-i686-pc-windows-msvc.tar.gz=bd99a9cf662fbe90b79711776f972d2d574fcd6f0053bb672e4cdb35fc67ddf3
+dist/2024-09-22/cargo-beta-i686-pc-windows-msvc.tar.xz=8a995e56a96217cd999e786b16a69de1ec6e9db6412cd2c9c6ce090ed21a84bf
+dist/2024-09-22/cargo-beta-i686-unknown-linux-gnu.tar.gz=ae115caa9516a96f144db9751b185503e1c648ea9b7e8b0a6aa10200315e6458
+dist/2024-09-22/cargo-beta-i686-unknown-linux-gnu.tar.xz=54b125ce0c00afa7bdebf5cb592249c37ac21d78479129a46d0b70d86fe6bf17
+dist/2024-09-22/cargo-beta-loongarch64-unknown-linux-gnu.tar.gz=21d2ca9f6d715e44fae058b7c26abc873930ac2823e72c9f8c983f7d089bd91a
+dist/2024-09-22/cargo-beta-loongarch64-unknown-linux-gnu.tar.xz=b9b395041d328a09643b7e727705aa7705bf67c08edb3d26b78405ce454c6798
+dist/2024-09-22/cargo-beta-loongarch64-unknown-linux-musl.tar.gz=da7853da9096b6ddebc3b3da948b90ac448663dc9a5d2940cad420360d5934a2
+dist/2024-09-22/cargo-beta-loongarch64-unknown-linux-musl.tar.xz=9997e251abe606e390e3d2c280233f435f8ab46a6a3d24ce95d7a700ec049664
+dist/2024-09-22/cargo-beta-powerpc-unknown-linux-gnu.tar.gz=1715eabf3860f2fa7e1e27f2163a5243c8000b6216c0e7ac8dec993061ff479b
+dist/2024-09-22/cargo-beta-powerpc-unknown-linux-gnu.tar.xz=f4e0f364c4ca68dc7b40b40bf13e28284a9bf6e6075b10504b9e6979d4a1a375
+dist/2024-09-22/cargo-beta-powerpc64-unknown-linux-gnu.tar.gz=70cb2337910933f0ce22ef57e8dec4ab5732855d0657e56ed237e3e483aa07d2
+dist/2024-09-22/cargo-beta-powerpc64-unknown-linux-gnu.tar.xz=1e9e383a093b54b8f7bff8dbf2f38590c148d0c9e18399bc128a09a6c67565bd
+dist/2024-09-22/cargo-beta-powerpc64le-unknown-linux-gnu.tar.gz=6e01a5a6cf68b8385d2a2eaa07984ba62ef4df6811be2ade5dd7b22ba7d4bd69
+dist/2024-09-22/cargo-beta-powerpc64le-unknown-linux-gnu.tar.xz=70d0e45fba27db3322c3e4d802cdcd37503d2a848b9c0c2b9b759d48611c19ab
+dist/2024-09-22/cargo-beta-riscv64gc-unknown-linux-gnu.tar.gz=baabb56c3670a0dab62fc7c0e5cb07474de795e81a6be42c57a91c2249e9b960
+dist/2024-09-22/cargo-beta-riscv64gc-unknown-linux-gnu.tar.xz=fd87e580bd0d4b47340b797fb52aeda83854556328869ebd1ce7136bcf8ead78
+dist/2024-09-22/cargo-beta-s390x-unknown-linux-gnu.tar.gz=dbf01fb97c1aa9db57b68fa863dca5df81e1f83c1686bdbc01c702b0148bba7a
+dist/2024-09-22/cargo-beta-s390x-unknown-linux-gnu.tar.xz=f2eaf49ad1a05b5acf3050159aeb7351544c5aa14a46b381b0e2659eb857bce8
+dist/2024-09-22/cargo-beta-x86_64-apple-darwin.tar.gz=cdd90fe77bff57d0acae21499c0188fac2ddf7aa24dba07dcbf900444ceb1295
+dist/2024-09-22/cargo-beta-x86_64-apple-darwin.tar.xz=2c8acbf6eb4076ad876993f09714a2b1664031a41a12ff395c1f9c4bd0283640
+dist/2024-09-22/cargo-beta-x86_64-pc-windows-gnu.tar.gz=f16189ad7a0d311b17b6bb6ced913cde0115ac07e9a950b85d4336c488456c6c
+dist/2024-09-22/cargo-beta-x86_64-pc-windows-gnu.tar.xz=1d4bf171c84def4110ee3f4e4798ab3ee52d0323bc2fc4abd564f229a23846da
+dist/2024-09-22/cargo-beta-x86_64-pc-windows-msvc.tar.gz=c3e27d6a38eb46fca153ef17cea76b11664e8171e0aa76af594e67ed9dffbef5
+dist/2024-09-22/cargo-beta-x86_64-pc-windows-msvc.tar.xz=b64792d6ec70ee083dac929343ab45f4a52039c7fbc6cb223b02663591c8f544
+dist/2024-09-22/cargo-beta-x86_64-unknown-freebsd.tar.gz=40bf96a087dc1d57ba495733975ff34a4e75e51d7ddffc025561f0951adb57ca
+dist/2024-09-22/cargo-beta-x86_64-unknown-freebsd.tar.xz=7912a49f7a181145b71a197014e3de6594b216959cd7c95a003fcd13854cb056
+dist/2024-09-22/cargo-beta-x86_64-unknown-illumos.tar.gz=1c3dfd5dcb8e7c8ba947b67f5bc466bae26ca1518a74798cfe5a21997bfcf71d
+dist/2024-09-22/cargo-beta-x86_64-unknown-illumos.tar.xz=6f620a91c2bc145f894f5736a9818f7b54583a93e7eb2d0ac202f46a38040b99
+dist/2024-09-22/cargo-beta-x86_64-unknown-linux-gnu.tar.gz=c6c20977054f56fc279e666cf02da65acb376c1b08bbbc998cf34d0cc2b5bb7b
+dist/2024-09-22/cargo-beta-x86_64-unknown-linux-gnu.tar.xz=9cca7e46ad35f0f69d8fe628a95e44388ed5cb62c1b77f2bab03dab28a05a650
+dist/2024-09-22/cargo-beta-x86_64-unknown-linux-musl.tar.gz=74005a4511ca2087ebb92db7e19a2e31e3ddcdef93e27da544bbc444df01dc32
+dist/2024-09-22/cargo-beta-x86_64-unknown-linux-musl.tar.xz=94215716623cadc8bf4a119612ad7482661905748d4e43ddff1855d4746f3972
+dist/2024-09-22/cargo-beta-x86_64-unknown-netbsd.tar.gz=fd9b2dd77b76b2ac44dbeb80e46371669223fe8ca57e4d480deeb162168c38d5
+dist/2024-09-22/cargo-beta-x86_64-unknown-netbsd.tar.xz=d419dbb9d1c905eb841c6870ddc8afe946b7618d3a0c6f39f8feeba6ecc74f0d
+dist/2024-09-22/clippy-beta-aarch64-apple-darwin.tar.gz=60aba239287116d7e0f58fc71e510fdb7582003efdb3011765f732b1e494c7e1
+dist/2024-09-22/clippy-beta-aarch64-apple-darwin.tar.xz=00ef2da71c8e3f5be8401128509ff99130eebd5c0b90b5b5c16dc0465c2a18f8
+dist/2024-09-22/clippy-beta-aarch64-pc-windows-msvc.tar.gz=7ff2952e057849ec69a7d1147920c2b6ecb99fe7984afe627c5514c8c6a8811c
+dist/2024-09-22/clippy-beta-aarch64-pc-windows-msvc.tar.xz=cc3e145daaf3674c1436d4380171ce5e26b075975121dac5c1d5c5d6cfa1a6e6
+dist/2024-09-22/clippy-beta-aarch64-unknown-linux-gnu.tar.gz=430c6d5ded52d04bfe93fce17f8fef57ce3ab05715767b85d6c9b59e521671b2
+dist/2024-09-22/clippy-beta-aarch64-unknown-linux-gnu.tar.xz=df4b9444dd435133bcfe386955b1d4b63c13e4acd766dc3bb9742c21431926d4
+dist/2024-09-22/clippy-beta-aarch64-unknown-linux-musl.tar.gz=7064208f59db897b1107072a3cc1a516d53888ea1c549bdf3cfd8479c65ec0c3
+dist/2024-09-22/clippy-beta-aarch64-unknown-linux-musl.tar.xz=1d33c3e2b4daa1ba7f1a6399790d1b76fdfe1ac9d293859983412d5e1e3663a1
+dist/2024-09-22/clippy-beta-arm-unknown-linux-gnueabi.tar.gz=b851cb5bcb31a2105039b55a613d937113fd45f5c1fbd4e3d24eecbed85a0bb0
+dist/2024-09-22/clippy-beta-arm-unknown-linux-gnueabi.tar.xz=a17f46c82fa28bfa9e3c9ff99cd25a888b6ff0c08a887ef4056b8ae29437a67a
+dist/2024-09-22/clippy-beta-arm-unknown-linux-gnueabihf.tar.gz=784a1a0134d54cff72c9bf59ee1e750d0493fef5bde06bf778bc98321d833031
+dist/2024-09-22/clippy-beta-arm-unknown-linux-gnueabihf.tar.xz=c11461066103bf92f21298e5cb3b009cf4ac07bde5d99ce9ab97c1cbdf7c73f5
+dist/2024-09-22/clippy-beta-armv7-unknown-linux-gnueabihf.tar.gz=98c74f6a0692482355045bb4b0977887b419a8aa3c4654b9b59cd0d867f261ac
+dist/2024-09-22/clippy-beta-armv7-unknown-linux-gnueabihf.tar.xz=20c82e6bbefdbaca22911a63a41d0aa05ed0ffad4571090c053cb354b49acd23
+dist/2024-09-22/clippy-beta-i686-pc-windows-gnu.tar.gz=3da558108df227ceb0ff7a2837d1bd2f5a75a0c7167f0b3c380d1aa5b2fa3e77
+dist/2024-09-22/clippy-beta-i686-pc-windows-gnu.tar.xz=f657f1cdc9f91243112834afbe5fe60f8b43e914504c8aed1994a13ac98bc575
+dist/2024-09-22/clippy-beta-i686-pc-windows-msvc.tar.gz=cf27f06843f5e0706aace4be4b9973fd164b57697b44d00852a9545d336c6fd2
+dist/2024-09-22/clippy-beta-i686-pc-windows-msvc.tar.xz=74dd229cdf65ce19ded1ed27cf5fb31c20f6a45879b277ad43aedc818eed514c
+dist/2024-09-22/clippy-beta-i686-unknown-linux-gnu.tar.gz=4d22b439675ec118d021a85dc75540d7a3331364395e21bc1a2d76c26aabe9d3
+dist/2024-09-22/clippy-beta-i686-unknown-linux-gnu.tar.xz=bfc60e9fe1dbed050904efc71e8d0e5c90dae7f949fc7c81312de0c129f4d058
+dist/2024-09-22/clippy-beta-loongarch64-unknown-linux-gnu.tar.gz=25df67e21543e3a3b71500f55da1abe6182a24aabe1f5bb1e57fe99821a22d97
+dist/2024-09-22/clippy-beta-loongarch64-unknown-linux-gnu.tar.xz=7b56b6f7704742821f42396f5c517adda129b68f05da258d371cc8a3bc7356f3
+dist/2024-09-22/clippy-beta-loongarch64-unknown-linux-musl.tar.gz=f7305d23b8b850b4169a2ae6816c9db721a989ffbb642a4645ed95068a6553fe
+dist/2024-09-22/clippy-beta-loongarch64-unknown-linux-musl.tar.xz=9576586590c11c86e8b029c32f17916ebd13d27d8750e30a927a4a986dd47aea
+dist/2024-09-22/clippy-beta-powerpc-unknown-linux-gnu.tar.gz=1eb483594b3ca3ab8e0eac99e7699be151791fcdf0349714b0da923ea33b92bc
+dist/2024-09-22/clippy-beta-powerpc-unknown-linux-gnu.tar.xz=42b9373a18ebf76394513cb75f8072ca094efbdfd8c60cc2249b04fad344f677
+dist/2024-09-22/clippy-beta-powerpc64-unknown-linux-gnu.tar.gz=fa6438d40613bb99062118bfb293f6f252a21c927d222c7cdfe4cee865d30d16
+dist/2024-09-22/clippy-beta-powerpc64-unknown-linux-gnu.tar.xz=7cfba858f149b327cbd9bf292080a2ae20404018228ab556eeefc3776f429785
+dist/2024-09-22/clippy-beta-powerpc64le-unknown-linux-gnu.tar.gz=5f6d94333400f99bbb0762be18fa9390885c13f4fe0ad7ea05b57808b26653e4
+dist/2024-09-22/clippy-beta-powerpc64le-unknown-linux-gnu.tar.xz=38042ee6161d8e8b04faf58a4bca98cf7940ece6ec42eb44ce29bdb9aedb6c89
+dist/2024-09-22/clippy-beta-riscv64gc-unknown-linux-gnu.tar.gz=b5056a3d8a8b3bbd888647117b316404b2701803bff09737cca18e16611ed3cd
+dist/2024-09-22/clippy-beta-riscv64gc-unknown-linux-gnu.tar.xz=9322024609e563bb0d1f342bae2deab1d0c0ae951c2e94fe74ddc22fe2c7d3f2
+dist/2024-09-22/clippy-beta-s390x-unknown-linux-gnu.tar.gz=8b52721fc1df5cd158e12ae80a2936929f64a7b2506c55793b4a7d28522f0e3e
+dist/2024-09-22/clippy-beta-s390x-unknown-linux-gnu.tar.xz=66dedbc154a11588a03616b92823c63502276123e66e9ff110c2e63cc7ed3529
+dist/2024-09-22/clippy-beta-x86_64-apple-darwin.tar.gz=66ba82b5e5097a2e35053fcb5db9ca44a152c1172f75d689688454561c8b3712
+dist/2024-09-22/clippy-beta-x86_64-apple-darwin.tar.xz=cfaa2e71b847103660336ad58025fff26f2928a4d7bcc5907fef91e70b63e1fc
+dist/2024-09-22/clippy-beta-x86_64-pc-windows-gnu.tar.gz=fef4e4f2c68294908e170c78efb657c02166fbfbc45b6ce65fbfb5c76ce6d20c
+dist/2024-09-22/clippy-beta-x86_64-pc-windows-gnu.tar.xz=0eec7155f78dfd0cc2e6ac996053492d7ba8a4fa5203f779a92b04ad42e8f651
+dist/2024-09-22/clippy-beta-x86_64-pc-windows-msvc.tar.gz=4dc7b6c972ed13417fa831ee20b9e4cc0a3895c39d4f059d1a14ebe51f7430e3
+dist/2024-09-22/clippy-beta-x86_64-pc-windows-msvc.tar.xz=c9f3fb89a31cbba2b575cbb7fc74c09c087940b138b34015239c8938ed6d6f14
+dist/2024-09-22/clippy-beta-x86_64-unknown-freebsd.tar.gz=cd7e5a9ee6be58a627b13d2e85c05aebd64414f854229aca917f3334acbe2352
+dist/2024-09-22/clippy-beta-x86_64-unknown-freebsd.tar.xz=7d81d8fd02506935f289e22c6a8f3433bc2c78ea02bbfa4950a31f49eb95344b
+dist/2024-09-22/clippy-beta-x86_64-unknown-illumos.tar.gz=d38eda29de151d13b0fb1f58b090b63e049e095a326e26b76055383ba13285a0
+dist/2024-09-22/clippy-beta-x86_64-unknown-illumos.tar.xz=3100a9e357e6ded30499d4a60a6ff64f26d99e1cbd1eea11ca7fcf92a9c1f293
+dist/2024-09-22/clippy-beta-x86_64-unknown-linux-gnu.tar.gz=c09c9e00e653ffdb51c4edca6aa1e23572092c45a1cb81235f05bc75331d68c3
+dist/2024-09-22/clippy-beta-x86_64-unknown-linux-gnu.tar.xz=1e2fa4de890d7bc6c2828df95a729a55cb2b255a25d96194ccca0c3e06a580ba
+dist/2024-09-22/clippy-beta-x86_64-unknown-linux-musl.tar.gz=ac80d0b1b7f3e451c3bd00fd882b547a9b87e95c3fc0d332050859ff827782a9
+dist/2024-09-22/clippy-beta-x86_64-unknown-linux-musl.tar.xz=1178ff5a580bd131ecb9a7b0ad2894c09f2882bcfc483ca14e1fd780925e97ed
+dist/2024-09-22/clippy-beta-x86_64-unknown-netbsd.tar.gz=b69d92c035e456d4d1dd8a09032a92f8226c9f39579966e86c2e202ac9995d29
+dist/2024-09-22/clippy-beta-x86_64-unknown-netbsd.tar.xz=a0e827a24ffe8d2b38efff5da0972eee15e098f790b49035b21a72ebf1cb17ef
+dist/2024-09-22/rustfmt-nightly-aarch64-apple-darwin.tar.gz=4e632df4953f955b24414d929c352ce1f6e196c50cedde3da4d8663f5f1dd77e
+dist/2024-09-22/rustfmt-nightly-aarch64-apple-darwin.tar.xz=d7f8d8442b25053e767ec85e50aa2a6f9bb01e45a2ec3fdec56ef1c305a91ba2
+dist/2024-09-22/rustfmt-nightly-aarch64-pc-windows-msvc.tar.gz=eaee820d549347d15f1b96e3c85517a65e2a5655b86e27927eb6646a7c1d7b67
+dist/2024-09-22/rustfmt-nightly-aarch64-pc-windows-msvc.tar.xz=5fb16519d2acb68df963800c9a5036f1ee38b6ea02a115c40b6622338cf7052c
+dist/2024-09-22/rustfmt-nightly-aarch64-unknown-linux-gnu.tar.gz=037999e2fed25ae76b70960133a811a29707712d2141fc74a1db312cfe6020e1
+dist/2024-09-22/rustfmt-nightly-aarch64-unknown-linux-gnu.tar.xz=b10d1947baafc6160ce8d5902936c2b3469a1558b71263671e581ac5b1c14f0e
+dist/2024-09-22/rustfmt-nightly-aarch64-unknown-linux-musl.tar.gz=eb33ec39c232a6ddeab1b8038222f96407b9671052f995e0a60ada332a1ccb3f
+dist/2024-09-22/rustfmt-nightly-aarch64-unknown-linux-musl.tar.xz=396775133e37dac5de8e71e5d8fea26c19dbfc7841244a35c3529f5dfec93163
+dist/2024-09-22/rustfmt-nightly-arm-unknown-linux-gnueabi.tar.gz=4885a99dbab8f33288501532b287c20f981bdcd10ea4d9ccffe585d5338c43d3
+dist/2024-09-22/rustfmt-nightly-arm-unknown-linux-gnueabi.tar.xz=af165d8090fd3c32efc7e5f58dd57d4a2c228cc6a9939c40024d896c35119bf6
+dist/2024-09-22/rustfmt-nightly-arm-unknown-linux-gnueabihf.tar.gz=150086cbd94e084b30faaebabc809cff11eca87a4aa4ff2b2b89286e0af6760e
+dist/2024-09-22/rustfmt-nightly-arm-unknown-linux-gnueabihf.tar.xz=49ab34e495e893037431851e65a35ea7e9d0b46ba651f7d73591bd659c031bd7
+dist/2024-09-22/rustfmt-nightly-armv7-unknown-linux-gnueabihf.tar.gz=c61c6bb8a96c19a848155a38560e0a6dac91ec5f1ee2c602a060cd6039324839
+dist/2024-09-22/rustfmt-nightly-armv7-unknown-linux-gnueabihf.tar.xz=81b7ae3c5e27830fa10a17e062c56bcfe66413b994b27951b63f67faabd296d4
+dist/2024-09-22/rustfmt-nightly-i686-pc-windows-gnu.tar.gz=585896ee3c2b1644ebcba6a81b2f2dabc47da151f6100b5660e208c3a2967952
+dist/2024-09-22/rustfmt-nightly-i686-pc-windows-gnu.tar.xz=ca875f395d33249cbfd657cfab1b4c596de1453c4451c7bb4466ebec639ad016
+dist/2024-09-22/rustfmt-nightly-i686-pc-windows-msvc.tar.gz=4dbce4c329cac38785408eb1a8b2ff5358fd18b59276435695324a03a7018fa9
+dist/2024-09-22/rustfmt-nightly-i686-pc-windows-msvc.tar.xz=10aea1e2abaae9d098afff8d080cc9d84bfb3f77e2e72ec0a639d61dc5900fd8
+dist/2024-09-22/rustfmt-nightly-i686-unknown-linux-gnu.tar.gz=140897d538c0f7df473c3f704ec7e9198c9e903b5882688f0494166647dbd91e
+dist/2024-09-22/rustfmt-nightly-i686-unknown-linux-gnu.tar.xz=06e85fa8391eb7d82902ef55af8ee89a16f07b32e4839a848ac09b506f4227e3
+dist/2024-09-22/rustfmt-nightly-loongarch64-unknown-linux-gnu.tar.gz=4103e5daf242f72c0c7875044ea2ee5f2c88bc5c87ba1e685eee526038663e7d
+dist/2024-09-22/rustfmt-nightly-loongarch64-unknown-linux-gnu.tar.xz=fe424f1c13eb8257036db3e843d4c6b7b0e3bbf310f1d42719046f86dd635c95
+dist/2024-09-22/rustfmt-nightly-loongarch64-unknown-linux-musl.tar.gz=86304bb8673decae3d6e8b923765b410948277ea00d0cc5b14bb448da149aa8d
+dist/2024-09-22/rustfmt-nightly-loongarch64-unknown-linux-musl.tar.xz=743abf4d3ea8b3e1e8dbed6d9f75ee84680b0636e8e7c536b13bd69a41c8a0d9
+dist/2024-09-22/rustfmt-nightly-powerpc-unknown-linux-gnu.tar.gz=db68cf7bfaa00b8f6c544b615eabdea998540ae70ec23af6b7370153a6706a64
+dist/2024-09-22/rustfmt-nightly-powerpc-unknown-linux-gnu.tar.xz=fe1abd02ed36a3720c41c46c77136c89c5addc2c8e5e2cbe25331a34082f4b7a
+dist/2024-09-22/rustfmt-nightly-powerpc64-unknown-linux-gnu.tar.gz=c6bb214d68fe7d631398a8684df49f4d1faeb42f9d422c247328e508bdaee830
+dist/2024-09-22/rustfmt-nightly-powerpc64-unknown-linux-gnu.tar.xz=230e19228f80fa4da3036d4eac5b9f9dde02b47d32c43278190da4d322461fd1
+dist/2024-09-22/rustfmt-nightly-powerpc64le-unknown-linux-gnu.tar.gz=b21b569a1831a2ea621c35e19a1820f236fdfc54d38a387789b7750b1af26043
+dist/2024-09-22/rustfmt-nightly-powerpc64le-unknown-linux-gnu.tar.xz=28f8c4aa4cf00561d6c9dfddc13fdf5fba7b936f9f510b9ecc84160385d590d0
+dist/2024-09-22/rustfmt-nightly-riscv64gc-unknown-linux-gnu.tar.gz=5cd81cb8c792abb3c31da225424ef5d1f6006163d3ddee06a95bb4286a29123e
+dist/2024-09-22/rustfmt-nightly-riscv64gc-unknown-linux-gnu.tar.xz=58eedfc8cda153ea5ee92278bf08a0625d129d3e208b3e0244e2b90819c7cc2e
+dist/2024-09-22/rustfmt-nightly-s390x-unknown-linux-gnu.tar.gz=17a0c073de3c6e3769a86d0438b1132762456153f3739c6652f94fca270e3a4b
+dist/2024-09-22/rustfmt-nightly-s390x-unknown-linux-gnu.tar.xz=d7001fc75844be6859a57d2263075ff1b7ac2d88c62452bd42fef97b0afe03d7
+dist/2024-09-22/rustfmt-nightly-x86_64-apple-darwin.tar.gz=7bc303ca8b36c782f2034441cbb6d3dc3ea891114895d2027cce9d8cd25ce348
+dist/2024-09-22/rustfmt-nightly-x86_64-apple-darwin.tar.xz=119dcbdeda0fc6cb80d18e6e908646cbaedd615f5a501922344c795ffd1dc7d8
+dist/2024-09-22/rustfmt-nightly-x86_64-pc-windows-gnu.tar.gz=b14962a790a48b609eda7e1a847c85759cd7dc7f9d0ac9914f126f458b4ae268
+dist/2024-09-22/rustfmt-nightly-x86_64-pc-windows-gnu.tar.xz=3a710fdf3d35c0a42f5c43341aa00390644d82e76c52aa59f4d652a6ab980b3d
+dist/2024-09-22/rustfmt-nightly-x86_64-pc-windows-msvc.tar.gz=946233868c179df3c133fa04bde2c863028a69776c7416aa4a33adb102d63783
+dist/2024-09-22/rustfmt-nightly-x86_64-pc-windows-msvc.tar.xz=1db1094ee7c9cad7a16b227de6763b835bc33c0650ba2eb9b380c430a766b81c
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-freebsd.tar.gz=68bc0322c947af0d98f63fc3e41322c12ce8be2bd185091b14407792d407f59b
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-freebsd.tar.xz=66e380f40e18c8a1ce91a9eaf7f662cacd580fc2b276cc854c03d795a5b9d547
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-illumos.tar.gz=5048bd14d07ed54f5120b0488925f69ff92d2fe00f1e19ae3a8a39a56201c09b
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-illumos.tar.xz=d2f903f996c265b4d70bb88d47e85dd7382b3298f9ff02ad4502f32d6f9919dd
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-linux-gnu.tar.gz=f0c150cb2fcbb7cfc4982426be6760093aa6cf854d84ed3c793f766fba6a0cc8
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-linux-gnu.tar.xz=5d5cc741435c63b162417f425f7cf9445a13c109687cc85f28424fc51192e333
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-linux-musl.tar.gz=a3252a997f60b086ea8c9c32665277f33cf574fdefee859ee448dc0b7eed5be9
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-linux-musl.tar.xz=b888f58dce3689e75ea6c23904481f7fec110f0aea45b75a9390d2160e0d3151
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-netbsd.tar.gz=4663adcc009bd376b0787760854fb694eaa0edff88f72b4cf486f7180f6a1c2b
+dist/2024-09-22/rustfmt-nightly-x86_64-unknown-netbsd.tar.xz=bfc83277d2217b3a908c3f9153db1336b63270c70c6cd83a2628cf18c41db47f
+dist/2024-09-22/rustc-nightly-aarch64-apple-darwin.tar.gz=ade996e00dd338a86cdcb25961d07c936edec1392526d78dd5de156ba012fe55
+dist/2024-09-22/rustc-nightly-aarch64-apple-darwin.tar.xz=147d0cfe57be988564d30fcba7fc0c69979b5fbdd91e4a08ac8e580be8a1cc6f
+dist/2024-09-22/rustc-nightly-aarch64-pc-windows-msvc.tar.gz=e6a59a0303abbabb3b373fda7fb697ad2cfd31011f231fbdfd45c1cbd64e8bd7
+dist/2024-09-22/rustc-nightly-aarch64-pc-windows-msvc.tar.xz=9ee27bc608470ef29a51272656d0ed5e03946dcc3411412ef8b05cc70f97f8b9
+dist/2024-09-22/rustc-nightly-aarch64-unknown-linux-gnu.tar.gz=3ec6f8cee20883195c102bdcffee31d695698bb6eaf45502720edbc16b02f471
+dist/2024-09-22/rustc-nightly-aarch64-unknown-linux-gnu.tar.xz=7f8fabd6433acb752131071c5bee76752fcc88e08ffff4684a7badb9ed4bc50e
+dist/2024-09-22/rustc-nightly-aarch64-unknown-linux-musl.tar.gz=7a8756afcd643b78aa6834497935d7bc0ede1ae74150fa83fff85243deb5e554
+dist/2024-09-22/rustc-nightly-aarch64-unknown-linux-musl.tar.xz=de39081dbeeb0715d433e0cd56e62db45c3bb5bf04d1e7dc3fa097e7b3ca97dc
+dist/2024-09-22/rustc-nightly-arm-unknown-linux-gnueabi.tar.gz=ea6bd6b337d24a7c9995fa95d8884e66755d016fb1d50fea063129a410bec22a
+dist/2024-09-22/rustc-nightly-arm-unknown-linux-gnueabi.tar.xz=fa195b2588675831274ca21c0d2420e5729d1c21c4c245f2fd1d2c044d7ede1c
+dist/2024-09-22/rustc-nightly-arm-unknown-linux-gnueabihf.tar.gz=6f0719613ec54221e978e7136baa00eb25b8b3d627e5de5ee3488c9d9e869b97
+dist/2024-09-22/rustc-nightly-arm-unknown-linux-gnueabihf.tar.xz=9e0bbd283a0377f881f1c048660c54700561762e220ff2713566d3fb6eb56cce
+dist/2024-09-22/rustc-nightly-armv7-unknown-linux-gnueabihf.tar.gz=c8f88bb948119a9ff218571eb3ff0144915b2ce4a404d445db9f8f9c25044aa3
+dist/2024-09-22/rustc-nightly-armv7-unknown-linux-gnueabihf.tar.xz=1c41588099d929a7e9dd56cba22782f5202fac2829b924b1aa7dab3e03c52960
+dist/2024-09-22/rustc-nightly-i686-pc-windows-gnu.tar.gz=af2d30b4925e786ace64d4a11bb05ac6f7df1636989a3656d1aa9fe56cdc330f
+dist/2024-09-22/rustc-nightly-i686-pc-windows-gnu.tar.xz=4bfe618c3702ea805b63beac19cbf0561d262e67d87765a4e10ea9defded53c4
+dist/2024-09-22/rustc-nightly-i686-pc-windows-msvc.tar.gz=c4e57fe6fec40d874c8fb54227b310072dc98f35f99b8cc741e6818a67941f6d
+dist/2024-09-22/rustc-nightly-i686-pc-windows-msvc.tar.xz=ed10535a830e2e1ab22767a24b82b3314b7ef4ac3c318954ee8f2384b287d8e7
+dist/2024-09-22/rustc-nightly-i686-unknown-linux-gnu.tar.gz=da5e36f6bb3d9f00b8e5db5aceefcf8ad38552b85a1a4f60f7b700148cd49152
+dist/2024-09-22/rustc-nightly-i686-unknown-linux-gnu.tar.xz=5831b0209eb64a44b6bfc8aa4b092faaae85101f58f79c4e869bffec22361f1b
+dist/2024-09-22/rustc-nightly-loongarch64-unknown-linux-gnu.tar.gz=f31871890aa6249528b43119d0f050d27c5f404b560d48660cd4c9e7a3a80b76
+dist/2024-09-22/rustc-nightly-loongarch64-unknown-linux-gnu.tar.xz=19dc59393d25edef8a341bb137ad1f4ca20741038b0111dc81d6e61c0a7a1975
+dist/2024-09-22/rustc-nightly-loongarch64-unknown-linux-musl.tar.gz=8ebea352863ef014e4dafbafe5a28ddfff6a26f3e4cf728fb4099ecd3444a3ec
+dist/2024-09-22/rustc-nightly-loongarch64-unknown-linux-musl.tar.xz=97196b586f44022d2c24b7378830f716abceb451244035f74c40b6c1587f6c50
+dist/2024-09-22/rustc-nightly-powerpc-unknown-linux-gnu.tar.gz=6f4d2428ec7a4d5e1540b53e35904b9f9ff5b8fcd05cf3311b005dbfd426d65b
+dist/2024-09-22/rustc-nightly-powerpc-unknown-linux-gnu.tar.xz=c2bc66d7d763c1d4c5752b60ab563fe5b870dd35533712046acd40f258f7a337
+dist/2024-09-22/rustc-nightly-powerpc64-unknown-linux-gnu.tar.gz=d0e6f42aafc8d8b289b55c1ba4a34039c747a7445b347f05017606801a7d81a4
+dist/2024-09-22/rustc-nightly-powerpc64-unknown-linux-gnu.tar.xz=9612777e56955ab5446e3ef20e0d579fbeceedc3bdc4d0053367be2191551fd7
+dist/2024-09-22/rustc-nightly-powerpc64le-unknown-linux-gnu.tar.gz=811099c8b6adc017678c4e43c8f7b02b2bde267eac1bbc023b1f22c184894231
+dist/2024-09-22/rustc-nightly-powerpc64le-unknown-linux-gnu.tar.xz=f766dab0fa46122c26e5a7736da65e8a2df9c2c6578093b6532dbd88a162d1a5
+dist/2024-09-22/rustc-nightly-riscv64gc-unknown-linux-gnu.tar.gz=21e9896e5184d797445a19ce5788d8dabe86302d5f63bf8c07105b52a237c13b
+dist/2024-09-22/rustc-nightly-riscv64gc-unknown-linux-gnu.tar.xz=002da974c9606726cc7e6f68cda012ef305e420cf6f7a0de84bf791c007fecd6
+dist/2024-09-22/rustc-nightly-s390x-unknown-linux-gnu.tar.gz=adfa4248f4ad883a04d67f923325c28b7400853063f2d8017cca8f4100ec1125
+dist/2024-09-22/rustc-nightly-s390x-unknown-linux-gnu.tar.xz=8334aa8a99d2a8034267394d44b0e5036d053c247812dbd5bc90bdb2344e4713
+dist/2024-09-22/rustc-nightly-x86_64-apple-darwin.tar.gz=385aa935fb1762423d1a11c0928597e502adbab9809a86c17d98096c31f65775
+dist/2024-09-22/rustc-nightly-x86_64-apple-darwin.tar.xz=f2bb16e1618dbcc7dda85e0ff4460ee270a99871477380a6412f575bd02f4cf5
+dist/2024-09-22/rustc-nightly-x86_64-pc-windows-gnu.tar.gz=6e3894c7651bfb48c741aba516ee99690616431643db82cd186fe408675d07b4
+dist/2024-09-22/rustc-nightly-x86_64-pc-windows-gnu.tar.xz=5661b5ba3a496106f4b0019d4ce81dbcb4b4a0db68a90bac64a95a0bd9201514
+dist/2024-09-22/rustc-nightly-x86_64-pc-windows-msvc.tar.gz=564f7a0582f3b900201cda4fe502e191b651a845210d21a40a119b94e2e51133
+dist/2024-09-22/rustc-nightly-x86_64-pc-windows-msvc.tar.xz=1804ebc7ade5c49ec4b82cac2261cf159b8c852a7e06f3faafbf990214936d2b
+dist/2024-09-22/rustc-nightly-x86_64-unknown-freebsd.tar.gz=7455de95ddb8e565ddeaf2da7d80d890c60bc653f52afcab5244476d35305e0b
+dist/2024-09-22/rustc-nightly-x86_64-unknown-freebsd.tar.xz=36a7cf6e8245c3879c08d5e3acfb0155ebcdc6c5b06edc51d43376c44d9ed0b4
+dist/2024-09-22/rustc-nightly-x86_64-unknown-illumos.tar.gz=143f5ce723a8f5e54af64a3b31d83243a808355705b1402be5de821759187066
+dist/2024-09-22/rustc-nightly-x86_64-unknown-illumos.tar.xz=c88c8d2ae8f221fe1db978802c98368472381b443bed9501371c03617865785d
+dist/2024-09-22/rustc-nightly-x86_64-unknown-linux-gnu.tar.gz=0ea098f78927d9fdf4ec075a04e989b6ac83bc1f1225aca5960281cd65046a3b
+dist/2024-09-22/rustc-nightly-x86_64-unknown-linux-gnu.tar.xz=33e5e1e0b758de383281ae704d3dd1ee337d8e28515d6b4584dd2691587c7f0e
+dist/2024-09-22/rustc-nightly-x86_64-unknown-linux-musl.tar.gz=723f5eaceef968b05286a17b7868c7e0cf222ac33d23a9ac3f761fc274b87c38
+dist/2024-09-22/rustc-nightly-x86_64-unknown-linux-musl.tar.xz=1b00b14a57b6f3b7edbf9adc05d3ed28ed1e2b8ced921a444d13dd1ef577e715
+dist/2024-09-22/rustc-nightly-x86_64-unknown-netbsd.tar.gz=6cd2651e4e8aedd8aef8d325a72cf18694ee7a14077c7331d96e2e7c03b9c57a
+dist/2024-09-22/rustc-nightly-x86_64-unknown-netbsd.tar.xz=0c6144559f040a209183d6f02f61caf485f0174190e643870d1d6c9744bfede3
\ No newline at end of file
diff --git a/src/tools/build-manifest/src/main.rs b/src/tools/build-manifest/src/main.rs
index eb5faeeaf9afb..62e1695cbe362 100644
--- a/src/tools/build-manifest/src/main.rs
+++ b/src/tools/build-manifest/src/main.rs
@@ -598,14 +598,11 @@ impl Builder {
             })
             .collect();
 
-        dst.insert(
-            pkg.manifest_component_name(),
-            Package {
-                version: version_info.version.unwrap_or_default(),
-                git_commit_hash: version_info.git_commit,
-                target: targets,
-            },
-        );
+        dst.insert(pkg.manifest_component_name(), Package {
+            version: version_info.version.unwrap_or_default(),
+            git_commit_hash: version_info.git_commit,
+            target: targets,
+        });
     }
 
     fn url(&self, path: &Path) -> String {
diff --git a/src/tools/build-manifest/src/manifest.rs b/src/tools/build-manifest/src/manifest.rs
index 695a8f5d4e743..f038deea7025e 100644
--- a/src/tools/build-manifest/src/manifest.rs
+++ b/src/tools/build-manifest/src/manifest.rs
@@ -3,8 +3,8 @@ use std::path::{Path, PathBuf};
 
 use serde::{Serialize, Serializer};
 
-use crate::versions::PkgType;
 use crate::Builder;
+use crate::versions::PkgType;
 
 #[derive(Serialize)]
 #[serde(rename_all = "kebab-case")]
diff --git a/src/tools/bump-stage0/src/main.rs b/src/tools/bump-stage0/src/main.rs
index f8c75ca722609..b2dc044ec66a2 100644
--- a/src/tools/bump-stage0/src/main.rs
+++ b/src/tools/bump-stage0/src/main.rs
@@ -1,7 +1,7 @@
 #![deny(unused_variables)]
 
 use anyhow::{Context, Error};
-use build_helper::stage0_parser::{parse_stage0_file, Stage0Config, VersionMetadata};
+use build_helper::stage0_parser::{Stage0Config, VersionMetadata, parse_stage0_file};
 use curl::easy::Easy;
 use indexmap::IndexMap;
 
diff --git a/src/tools/clippy/clippy_lints/src/derive.rs b/src/tools/clippy/clippy_lints/src/derive.rs
index 636698e96f6d1..649c480fb92a1 100644
--- a/src/tools/clippy/clippy_lints/src/derive.rs
+++ b/src/tools/clippy/clippy_lints/src/derive.rs
@@ -386,7 +386,6 @@ fn check_unsafe_derive_deserialize<'tcx>(
             .tcx
             .inherent_impls(def.did())
             .into_iter()
-            .flatten()
             .map(|imp_did| cx.tcx.hir().expect_item(imp_did.expect_local()))
             .any(|imp| has_unsafe(cx, imp))
     {
diff --git a/src/tools/clippy/clippy_lints/src/inherent_impl.rs b/src/tools/clippy/clippy_lints/src/inherent_impl.rs
index d39f910f9936d..309d2dfb28b87 100644
--- a/src/tools/clippy/clippy_lints/src/inherent_impl.rs
+++ b/src/tools/clippy/clippy_lints/src/inherent_impl.rs
@@ -51,9 +51,7 @@ impl<'tcx> LateLintPass<'tcx> for MultipleInherentImpl {
         // List of spans to lint. (lint_span, first_span)
         let mut lint_spans = Vec::new();
 
-        let Ok(impls) = cx.tcx.crate_inherent_impls(()) else {
-            return;
-        };
+        let (impls, _) = cx.tcx.crate_inherent_impls(());
 
         for (&id, impl_ids) in &impls.inherent_impls {
             if impl_ids.len() < 2
diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs
index 0bc7fc2dd9d1e..16f86b18e2e55 100644
--- a/src/tools/clippy/clippy_lints/src/len_zero.rs
+++ b/src/tools/clippy/clippy_lints/src/len_zero.rs
@@ -448,7 +448,6 @@ fn check_for_is_empty(
         .tcx
         .inherent_impls(impl_ty)
         .into_iter()
-        .flatten()
         .flat_map(|&id| cx.tcx.associated_items(id).filter_by_name_unhygienic(is_empty))
         .find(|item| item.kind == AssocKind::Fn);
 
@@ -616,7 +615,7 @@ fn has_is_empty(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool {
     /// Checks the inherent impl's items for an `is_empty(self)` method.
     fn has_is_empty_impl(cx: &LateContext<'_>, id: DefId) -> bool {
         let is_empty = sym!(is_empty);
-        cx.tcx.inherent_impls(id).into_iter().flatten().any(|imp| {
+        cx.tcx.inherent_impls(id).into_iter().any(|imp| {
             cx.tcx
                 .associated_items(*imp)
                 .filter_by_name_unhygienic(is_empty)
diff --git a/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs b/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs
index e4326cb958e5f..af71799f0a731 100644
--- a/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs
+++ b/src/tools/clippy/clippy_lints/src/methods/or_fun_call.rs
@@ -78,7 +78,6 @@ pub(super) fn check<'tcx>(
             cx.tcx
                 .inherent_impls(adt_def.did())
                 .into_iter()
-                .flatten()
                 .flat_map(|impl_id| cx.tcx.associated_items(impl_id).filter_by_name_unhygienic(sugg))
                 .find_map(|assoc| {
                     if assoc.fn_has_self_parameter
diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs
index 0d0d6219c5e05..aed0bc565d8e9 100644
--- a/src/tools/clippy/clippy_utils/src/lib.rs
+++ b/src/tools/clippy/clippy_utils/src/lib.rs
@@ -589,14 +589,11 @@ fn find_primitive_impls<'tcx>(tcx: TyCtxt<'tcx>, name: &str) -> impl Iterator SimplifiedType::Float(FloatTy::F32),
         "f64" => SimplifiedType::Float(FloatTy::F64),
         _ => {
-            return Result::<&[_], rustc_errors::ErrorGuaranteed>::Ok(&[])
-                .into_iter()
-                .flatten()
-                .copied();
+            return [].iter().copied();
         },
     };
 
-    tcx.incoherent_impls(ty).into_iter().flatten().copied()
+    tcx.incoherent_impls(ty).into_iter().copied()
 }
 
 fn non_local_item_children_by_name(tcx: TyCtxt<'_>, def_id: DefId, name: Symbol) -> Vec {
@@ -721,7 +718,6 @@ pub fn def_path_res(tcx: TyCtxt<'_>, path: &[&str]) -> Vec {
                 let inherent_impl_children = tcx
                     .inherent_impls(def_id)
                     .into_iter()
-                    .flatten()
                     .flat_map(|&impl_def_id| item_children_by_name(tcx, impl_def_id, segment));
 
                 let direct_children = item_children_by_name(tcx, def_id, segment);
diff --git a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs
index d9befb3c157a3..ce1895b7fb19b 100644
--- a/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs
+++ b/src/tools/clippy/clippy_utils/src/qualify_min_const_fn.rs
@@ -123,7 +123,7 @@ fn check_rvalue<'tcx>(
             | CastKind::FloatToFloat
             | CastKind::FnPtrToPtr
             | CastKind::PtrToPtr
-            | CastKind::PointerCoercion(PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer),
+            | CastKind::PointerCoercion(PointerCoercion::MutToConstPointer | PointerCoercion::ArrayToPointer, _),
             operand,
             _,
         ) => check_operand(tcx, operand, span, body, msrv),
@@ -131,12 +131,12 @@ fn check_rvalue<'tcx>(
             CastKind::PointerCoercion(
                 PointerCoercion::UnsafeFnPointer
                 | PointerCoercion::ClosureFnPointer(_)
-                | PointerCoercion::ReifyFnPointer,
+                | PointerCoercion::ReifyFnPointer, _
             ),
             _,
             _,
         ) => Err((span, "function pointer casts are not allowed in const fn".into())),
-        Rvalue::Cast(CastKind::PointerCoercion(PointerCoercion::Unsize), op, cast_ty) => {
+        Rvalue::Cast(CastKind::PointerCoercion(PointerCoercion::Unsize, _), op, cast_ty) => {
             let Some(pointee_ty) = cast_ty.builtin_deref(true) else {
                 // We cannot allow this for now.
                 return Err((span, "unsizing casts are only allowed for references right now".into()));
@@ -154,7 +154,7 @@ fn check_rvalue<'tcx>(
         Rvalue::Cast(CastKind::PointerExposeProvenance, _, _) => {
             Err((span, "casting pointers to ints is unstable in const fn".into()))
         },
-        Rvalue::Cast(CastKind::DynStar, _, _) => {
+        Rvalue::Cast(CastKind::PointerCoercion(PointerCoercion::DynStar, _), _, _) => {
             // FIXME(dyn-star)
             unimplemented!()
         },
diff --git a/src/tools/clippy/clippy_utils/src/ty.rs b/src/tools/clippy/clippy_utils/src/ty.rs
index 585134209ca3a..22aaaa1b73419 100644
--- a/src/tools/clippy/clippy_utils/src/ty.rs
+++ b/src/tools/clippy/clippy_utils/src/ty.rs
@@ -1316,7 +1316,7 @@ pub fn deref_chain<'cx, 'tcx>(cx: &'cx LateContext<'tcx>, ty: Ty<'tcx>) -> impl
 /// If you need this, you should wrap this call in `clippy_utils::ty::deref_chain().any(...)`.
 pub fn get_adt_inherent_method<'a>(cx: &'a LateContext<'_>, ty: Ty<'_>, method_name: Symbol) -> Option<&'a AssocItem> {
     if let Some(ty_did) = ty.ty_adt_def().map(AdtDef::did) {
-        cx.tcx.inherent_impls(ty_did).into_iter().flatten().find_map(|&did| {
+        cx.tcx.inherent_impls(ty_did).into_iter().find_map(|&did| {
             cx.tcx
                 .associated_items(did)
                 .filter_by_name_unhygienic(method_name)
diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs
index 414f9f3a7f13a..2d8c0c3fa5eb6 100644
--- a/src/tools/compiletest/src/common.rs
+++ b/src/tools/compiletest/src/common.rs
@@ -11,7 +11,7 @@ use serde::de::{Deserialize, Deserializer, Error as _};
 use test::{ColorConfig, OutputFormat};
 
 pub use self::Mode::*;
-use crate::util::{add_dylib_path, PathBufExt};
+use crate::util::{PathBufExt, add_dylib_path};
 
 macro_rules! string_enum {
     ($(#[$meta:meta])* $vis:vis enum $name:ident { $($variant:ident => $repr:expr,)* }) => {
diff --git a/src/tools/compiletest/src/errors.rs b/src/tools/compiletest/src/errors.rs
index 4ca9f02ddc7c7..efe758e65cf66 100644
--- a/src/tools/compiletest/src/errors.rs
+++ b/src/tools/compiletest/src/errors.rs
@@ -1,7 +1,7 @@
 use std::fmt;
 use std::fs::File;
-use std::io::prelude::*;
 use std::io::BufReader;
+use std::io::prelude::*;
 use std::path::Path;
 use std::str::FromStr;
 use std::sync::OnceLock;
diff --git a/src/tools/compiletest/src/header.rs b/src/tools/compiletest/src/header.rs
index 93df6aa72550f..a291ff3711239 100644
--- a/src/tools/compiletest/src/header.rs
+++ b/src/tools/compiletest/src/header.rs
@@ -1,8 +1,8 @@
 use std::collections::HashSet;
 use std::env;
 use std::fs::File;
-use std::io::prelude::*;
 use std::io::BufReader;
+use std::io::prelude::*;
 use std::path::{Path, PathBuf};
 use std::process::Command;
 use std::sync::OnceLock;
@@ -11,7 +11,7 @@ use regex::Regex;
 use tracing::*;
 
 use crate::common::{Config, Debugger, FailMode, Mode, PassMode};
-use crate::header::cfg::{parse_cfg_name_directive, MatchOutcome};
+use crate::header::cfg::{MatchOutcome, parse_cfg_name_directive};
 use crate::header::needs::CachedNeedsConditions;
 use crate::util::static_regex;
 use crate::{extract_cdb_version, extract_gdb_version};
diff --git a/src/tools/compiletest/src/header/needs.rs b/src/tools/compiletest/src/header/needs.rs
index e903f60ceb37f..99c0e850f1a24 100644
--- a/src/tools/compiletest/src/header/needs.rs
+++ b/src/tools/compiletest/src/header/needs.rs
@@ -1,5 +1,5 @@
 use crate::common::{Config, Sanitizer};
-use crate::header::{llvm_has_libzstd, IgnoreDecision};
+use crate::header::{IgnoreDecision, llvm_has_libzstd};
 
 pub(super) fn handle_needs(
     cache: &CachedNeedsConditions,
diff --git a/src/tools/compiletest/src/header/tests.rs b/src/tools/compiletest/src/header/tests.rs
index 3a9a7eb911889..ae661200c6cfa 100644
--- a/src/tools/compiletest/src/header/tests.rs
+++ b/src/tools/compiletest/src/header/tests.rs
@@ -4,7 +4,7 @@ use std::str::FromStr;
 
 use super::iter_header;
 use crate::common::{Config, Debugger, Mode};
-use crate::header::{parse_normalize_rule, EarlyProps, HeadersCache};
+use crate::header::{EarlyProps, HeadersCache, parse_normalize_rule};
 
 fn make_test_description(
     config: &Config,
@@ -226,10 +226,9 @@ fn revisions() {
     let config: Config = cfg().build();
 
     assert_eq!(parse_rs(&config, "//@ revisions: a b c").revisions, vec!["a", "b", "c"],);
-    assert_eq!(
-        parse_makefile(&config, "# revisions: hello there").revisions,
-        vec!["hello", "there"],
-    );
+    assert_eq!(parse_makefile(&config, "# revisions: hello there").revisions, vec![
+        "hello", "there"
+    ],);
 }
 
 #[test]
diff --git a/src/tools/compiletest/src/lib.rs b/src/tools/compiletest/src/lib.rs
index 3339116d542bc..cfc619f934208 100644
--- a/src/tools/compiletest/src/lib.rs
+++ b/src/tools/compiletest/src/lib.rs
@@ -34,10 +34,10 @@ use test::ColorConfig;
 use tracing::*;
 use walkdir::WalkDir;
 
-use self::header::{make_test_description, EarlyProps};
+use self::header::{EarlyProps, make_test_description};
 use crate::common::{
-    expected_output_path, output_base_dir, output_relative_path, Config, Debugger, Mode, PassMode,
-    TestPaths, UI_EXTENSIONS,
+    Config, Debugger, Mode, PassMode, TestPaths, UI_EXTENSIONS, expected_output_path,
+    output_base_dir, output_relative_path,
 };
 use crate::header::HeadersCache;
 use crate::util::logv;
diff --git a/src/tools/compiletest/src/read2.rs b/src/tools/compiletest/src/read2.rs
index b2d068e78b48f..2375f391d03d0 100644
--- a/src/tools/compiletest/src/read2.rs
+++ b/src/tools/compiletest/src/read2.rs
@@ -232,9 +232,9 @@ mod imp {
     use std::process::{ChildStderr, ChildStdout};
     use std::{io, slice};
 
+    use miow::Overlapped;
     use miow::iocp::{CompletionPort, CompletionStatus};
     use miow::pipe::NamedPipe;
-    use miow::Overlapped;
     use windows::Win32::Foundation::ERROR_BROKEN_PIPE;
 
     struct Pipe<'a> {
diff --git a/src/tools/compiletest/src/read2/tests.rs b/src/tools/compiletest/src/read2/tests.rs
index 9e052ff069b99..10572725431cc 100644
--- a/src/tools/compiletest/src/read2/tests.rs
+++ b/src/tools/compiletest/src/read2/tests.rs
@@ -1,6 +1,6 @@
 use std::io::Write;
 
-use crate::read2::{ProcOutput, FILTERED_PATHS_PLACEHOLDER_LEN, MAX_OUT_LEN};
+use crate::read2::{FILTERED_PATHS_PLACEHOLDER_LEN, MAX_OUT_LEN, ProcOutput};
 
 #[test]
 fn test_abbreviate_short_string() {
diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs
index 7b23aa3463923..25a135aa32027 100644
--- a/src/tools/compiletest/src/runtest.rs
+++ b/src/tools/compiletest/src/runtest.rs
@@ -3,7 +3,7 @@
 use std::borrow::Cow;
 use std::collections::{HashMap, HashSet};
 use std::ffi::OsString;
-use std::fs::{self, create_dir_all, File};
+use std::fs::{self, File, create_dir_all};
 use std::hash::{DefaultHasher, Hash, Hasher};
 use std::io::prelude::*;
 use std::io::{self, BufReader};
@@ -18,18 +18,18 @@ use regex::{Captures, Regex};
 use tracing::*;
 
 use crate::common::{
-    expected_output_path, incremental_dir, output_base_dir, output_base_name,
-    output_testname_unique, Assembly, Codegen, CodegenUnits, CompareMode, Config, CoverageMap,
-    CoverageRun, Crashes, DebugInfo, Debugger, FailMode, Incremental, JsDocTest, MirOpt, PassMode,
-    Pretty, RunMake, RunPassValgrind, Rustdoc, RustdocJson, TestPaths, Ui, UI_EXTENSIONS, UI_FIXED,
-    UI_RUN_STDERR, UI_RUN_STDOUT, UI_STDERR, UI_STDOUT, UI_SVG, UI_WINDOWS_SVG,
+    Assembly, Codegen, CodegenUnits, CompareMode, Config, CoverageMap, CoverageRun, Crashes,
+    DebugInfo, Debugger, FailMode, Incremental, JsDocTest, MirOpt, PassMode, Pretty, RunMake,
+    RunPassValgrind, Rustdoc, RustdocJson, TestPaths, UI_EXTENSIONS, UI_FIXED, UI_RUN_STDERR,
+    UI_RUN_STDOUT, UI_STDERR, UI_STDOUT, UI_SVG, UI_WINDOWS_SVG, Ui, expected_output_path,
+    incremental_dir, output_base_dir, output_base_name, output_testname_unique,
 };
 use crate::compute_diff::{write_diff, write_filtered_diff};
 use crate::errors::{self, Error, ErrorKind};
 use crate::header::TestProps;
-use crate::read2::{read2_abbreviated, Truncated};
-use crate::util::{add_dylib_path, logv, static_regex, PathBufExt};
-use crate::{json, ColorConfig};
+use crate::read2::{Truncated, read2_abbreviated};
+use crate::util::{PathBufExt, add_dylib_path, logv, static_regex};
+use crate::{ColorConfig, json};
 
 mod debugger;
 
@@ -62,7 +62,7 @@ fn disable_error_reporting R, R>(f: F) -> R {
     use std::sync::Mutex;
 
     use windows::Win32::System::Diagnostics::Debug::{
-        SetErrorMode, SEM_NOGPFAULTERRORBOX, THREAD_ERROR_MODE,
+        SEM_NOGPFAULTERRORBOX, SetErrorMode, THREAD_ERROR_MODE,
     };
 
     static LOCK: Mutex<()> = Mutex::new(());
@@ -1963,7 +1963,7 @@ impl<'test> TestCx<'test> {
 
         #[rustfmt::skip]
         let tidy_args = [
-            "--new-blocklevel-tags", "rustdoc-search",
+            "--new-blocklevel-tags", "rustdoc-search,rustdoc-toolbar",
             "--indent", "yes",
             "--indent-spaces", "2",
             "--wrap", "0",
diff --git a/src/tools/compiletest/src/runtest/crash.rs b/src/tools/compiletest/src/runtest/crash.rs
index 7f2bec4949be7..885ed3b08faca 100644
--- a/src/tools/compiletest/src/runtest/crash.rs
+++ b/src/tools/compiletest/src/runtest/crash.rs
@@ -15,10 +15,11 @@ impl TestCx<'_> {
         // if a test does not crash, consider it an error
         if proc_res.status.success() || matches!(proc_res.status.code(), Some(1 | 0)) {
             self.fatal(&format!(
-                "crashtest no longer crashes/triggers ICE, horray! Please give it a meaningful name, \
-            add a doc-comment to the start of the test explaining why it exists and \
-            move it to tests/ui or wherever you see fit. Adding 'Fixes #' to your PR description \
-            ensures that the corresponding ticket is auto-closed upon merge."
+                "crashtest no longer crashes/triggers ICE, horray! Please give it a meaningful \
+                name, add a doc-comment to the start of the test explaining why it exists and \
+                move it to tests/ui or wherever you see fit. Adding 'Fixes #' to your PR \
+                description ensures that the corresponding ticket is auto-closed upon merge. \
+                If you want to see verbose output, set `COMPILETEST_VERBOSE_CRASHES=1`."
             ));
         }
     }
diff --git a/src/tools/compiletest/src/runtest/mir_opt.rs b/src/tools/compiletest/src/runtest/mir_opt.rs
index 02289a8df1eff..d1ec00357449d 100644
--- a/src/tools/compiletest/src/runtest/mir_opt.rs
+++ b/src/tools/compiletest/src/runtest/mir_opt.rs
@@ -2,7 +2,7 @@ use std::fs;
 use std::path::{Path, PathBuf};
 
 use glob::glob;
-use miropt_test_tools::{files_for_miropt_test, MiroptTest, MiroptTestFile};
+use miropt_test_tools::{MiroptTest, MiroptTestFile, files_for_miropt_test};
 use tracing::debug;
 
 use super::{Emit, TestCx, WillExecute};
diff --git a/src/tools/compiletest/src/runtest/rustdoc.rs b/src/tools/compiletest/src/runtest/rustdoc.rs
index 6a31888527ef0..3f33862d2cfe2 100644
--- a/src/tools/compiletest/src/runtest/rustdoc.rs
+++ b/src/tools/compiletest/src/runtest/rustdoc.rs
@@ -1,6 +1,6 @@
 use std::process::Command;
 
-use super::{remove_and_create_dir_all, TestCx};
+use super::{TestCx, remove_and_create_dir_all};
 
 impl TestCx<'_> {
     pub(super) fn run_rustdoc_test(&self) {
diff --git a/src/tools/compiletest/src/runtest/rustdoc_json.rs b/src/tools/compiletest/src/runtest/rustdoc_json.rs
index a39887ccd026d..31fdb0a5d13bd 100644
--- a/src/tools/compiletest/src/runtest/rustdoc_json.rs
+++ b/src/tools/compiletest/src/runtest/rustdoc_json.rs
@@ -1,6 +1,6 @@
 use std::process::Command;
 
-use super::{remove_and_create_dir_all, TestCx};
+use super::{TestCx, remove_and_create_dir_all};
 
 impl TestCx<'_> {
     pub(super) fn run_rustdoc_json_test(&self) {
diff --git a/src/tools/compiletest/src/runtest/ui.rs b/src/tools/compiletest/src/runtest/ui.rs
index 88a0ec3aa3b2d..bd8ef952a863b 100644
--- a/src/tools/compiletest/src/runtest/ui.rs
+++ b/src/tools/compiletest/src/runtest/ui.rs
@@ -2,12 +2,12 @@ use std::collections::HashSet;
 use std::fs::OpenOptions;
 use std::io::Write;
 
-use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};
+use rustfix::{Filter, apply_suggestions, get_suggestions_from_json};
 use tracing::debug;
 
 use super::{
     AllowUnused, Emit, ErrorKind, FailMode, LinkToAux, PassMode, TargetLocation, TestCx,
-    TestOutput, Truncated, WillExecute, UI_FIXED,
+    TestOutput, Truncated, UI_FIXED, WillExecute,
 };
 use crate::{errors, json};
 
diff --git a/src/tools/coverage-dump/src/covfun.rs b/src/tools/coverage-dump/src/covfun.rs
index 4729b327de594..c779dd0583c4e 100644
--- a/src/tools/coverage-dump/src/covfun.rs
+++ b/src/tools/coverage-dump/src/covfun.rs
@@ -2,10 +2,10 @@ use std::collections::HashMap;
 use std::fmt::{self, Debug, Write as _};
 use std::sync::OnceLock;
 
-use anyhow::{anyhow, Context};
+use anyhow::{Context, anyhow};
 use regex::Regex;
 
-use crate::parser::{unescape_llvm_string_contents, Parser};
+use crate::parser::{Parser, unescape_llvm_string_contents};
 
 pub(crate) fn dump_covfun_mappings(
     llvm_ir: &str,
diff --git a/src/tools/coverage-dump/src/prf_names.rs b/src/tools/coverage-dump/src/prf_names.rs
index c5f9c4ce54cc5..96d097c79a315 100644
--- a/src/tools/coverage-dump/src/prf_names.rs
+++ b/src/tools/coverage-dump/src/prf_names.rs
@@ -4,7 +4,7 @@ use std::sync::OnceLock;
 use anyhow::{anyhow, ensure};
 use regex::Regex;
 
-use crate::parser::{unescape_llvm_string_contents, Parser};
+use crate::parser::{Parser, unescape_llvm_string_contents};
 
 /// Scans through the contents of an LLVM IR assembly file to find `__llvm_prf_names`
 /// entries, decodes them, and creates a table that maps name hash values to
diff --git a/src/tools/error_index_generator/main.rs b/src/tools/error_index_generator/main.rs
index 53a26112911db..58224aed14879 100644
--- a/src/tools/error_index_generator/main.rs
+++ b/src/tools/error_index_generator/main.rs
@@ -12,7 +12,7 @@ use std::io::Write;
 use std::path::{Path, PathBuf};
 use std::str::FromStr;
 
-use mdbook::book::{parse_summary, BookItem, Chapter};
+use mdbook::book::{BookItem, Chapter, parse_summary};
 use mdbook::{Config, MDBook};
 use rustc_errors::codes::DIAGNOSTICS;
 
diff --git a/src/tools/generate-copyright/src/cargo_metadata.rs b/src/tools/generate-copyright/src/cargo_metadata.rs
index c85e4aa371a2a..31b18c3dc1035 100644
--- a/src/tools/generate-copyright/src/cargo_metadata.rs
+++ b/src/tools/generate-copyright/src/cargo_metadata.rs
@@ -99,15 +99,12 @@ pub fn get_metadata(
             }
             // otherwise it's an out-of-tree dependency
             let package_id = Package { name: package.name, version: package.version.to_string() };
-            output.insert(
-                package_id,
-                PackageMetadata {
-                    license: package.license.unwrap_or_else(|| String::from("Unspecified")),
-                    authors: package.authors,
-                    notices: BTreeMap::new(),
-                    is_in_libstd: None,
-                },
-            );
+            output.insert(package_id, PackageMetadata {
+                license: package.license.unwrap_or_else(|| String::from("Unspecified")),
+                authors: package.authors,
+                notices: BTreeMap::new(),
+                is_in_libstd: None,
+            });
         }
     }
 
diff --git a/src/tools/html-checker/main.rs b/src/tools/html-checker/main.rs
index ecfbb1955e779..5cdc4d53ab500 100644
--- a/src/tools/html-checker/main.rs
+++ b/src/tools/html-checker/main.rs
@@ -31,7 +31,7 @@ fn check_html_file(file: &Path) -> usize {
         .arg("--mute-id") // this option is useful in case we want to mute more warnings
         .arg("yes")
         .arg("--new-blocklevel-tags")
-        .arg("rustdoc-search") // custom elements
+        .arg("rustdoc-search,rustdoc-toolbar") // custom elements
         .arg("--mute")
         .arg(&to_mute_s)
         .arg(file);
diff --git a/src/tools/jsondoclint/src/main.rs b/src/tools/jsondoclint/src/main.rs
index aaaba78cb46d1..5cbf346086062 100644
--- a/src/tools/jsondoclint/src/main.rs
+++ b/src/tools/jsondoclint/src/main.rs
@@ -1,10 +1,10 @@
 use std::io::{BufWriter, Write};
 use std::path::{Path, PathBuf};
 
-use anyhow::{bail, Result};
+use anyhow::{Result, bail};
 use clap::Parser;
 use fs_err as fs;
-use rustdoc_json_types::{Crate, Id, FORMAT_VERSION};
+use rustdoc_json_types::{Crate, FORMAT_VERSION, Id};
 use serde::Serialize;
 use serde_json::Value;
 
diff --git a/src/tools/jsondoclint/src/validator.rs b/src/tools/jsondoclint/src/validator.rs
index 10ab62cb24aa8..b04919bdd3edc 100644
--- a/src/tools/jsondoclint/src/validator.rs
+++ b/src/tools/jsondoclint/src/validator.rs
@@ -11,7 +11,7 @@ use rustdoc_json_types::{
 use serde_json::Value;
 
 use crate::item_kind::Kind;
-use crate::{json_find, Error, ErrorKind};
+use crate::{Error, ErrorKind, json_find};
 
 // This is a rustc implementation detail that we rely on here
 const LOCAL_CRATE_ID: u32 = 0;
diff --git a/src/tools/jsondoclint/src/validator/tests.rs b/src/tools/jsondoclint/src/validator/tests.rs
index f28702de06d50..d15aa7db31571 100644
--- a/src/tools/jsondoclint/src/validator/tests.rs
+++ b/src/tools/jsondoclint/src/validator/tests.rs
@@ -1,5 +1,5 @@
 use rustc_hash::FxHashMap;
-use rustdoc_json_types::{Item, ItemKind, Visibility, FORMAT_VERSION};
+use rustdoc_json_types::{FORMAT_VERSION, Item, ItemKind, Visibility};
 
 use super::*;
 use crate::json_find::SelectorPart;
@@ -25,42 +25,32 @@ fn errors_on_missing_links() {
         root: id("0"),
         crate_version: None,
         includes_private: false,
-        index: FxHashMap::from_iter([(
-            id("0"),
-            Item {
-                name: Some("root".to_owned()),
-                id: id(""),
-                crate_id: 0,
-                span: None,
-                visibility: Visibility::Public,
-                docs: None,
-                links: FxHashMap::from_iter([("Not Found".to_owned(), id("1"))]),
-                attrs: vec![],
-                deprecation: None,
-                inner: ItemEnum::Module(Module {
-                    is_crate: true,
-                    items: vec![],
-                    is_stripped: false,
-                }),
-            },
-        )]),
+        index: FxHashMap::from_iter([(id("0"), Item {
+            name: Some("root".to_owned()),
+            id: id(""),
+            crate_id: 0,
+            span: None,
+            visibility: Visibility::Public,
+            docs: None,
+            links: FxHashMap::from_iter([("Not Found".to_owned(), id("1"))]),
+            attrs: vec![],
+            deprecation: None,
+            inner: ItemEnum::Module(Module { is_crate: true, items: vec![], is_stripped: false }),
+        })]),
         paths: FxHashMap::default(),
         external_crates: FxHashMap::default(),
         format_version: rustdoc_json_types::FORMAT_VERSION,
     };
 
-    check(
-        &k,
-        &[Error {
-            kind: ErrorKind::NotFound(vec![vec![
-                SelectorPart::Field("index".to_owned()),
-                SelectorPart::Field("0".to_owned()),
-                SelectorPart::Field("links".to_owned()),
-                SelectorPart::Field("Not Found".to_owned()),
-            ]]),
-            id: id("1"),
-        }],
-    );
+    check(&k, &[Error {
+        kind: ErrorKind::NotFound(vec![vec![
+            SelectorPart::Field("index".to_owned()),
+            SelectorPart::Field("0".to_owned()),
+            SelectorPart::Field("links".to_owned()),
+            SelectorPart::Field("Not Found".to_owned()),
+        ]]),
+        id: id("1"),
+    }]);
 }
 
 // Test we would catch
@@ -72,60 +62,48 @@ fn errors_on_local_in_paths_and_not_index() {
         crate_version: None,
         includes_private: false,
         index: FxHashMap::from_iter([
-            (
-                id("0:0:1572"),
-                Item {
-                    id: id("0:0:1572"),
-                    crate_id: 0,
-                    name: Some("microcore".to_owned()),
-                    span: None,
-                    visibility: Visibility::Public,
-                    docs: None,
-                    links: FxHashMap::from_iter([(("prim@i32".to_owned(), id("0:1:1571")))]),
-                    attrs: Vec::new(),
-                    deprecation: None,
-                    inner: ItemEnum::Module(Module {
-                        is_crate: true,
-                        items: vec![id("0:1:717")],
-                        is_stripped: false,
-                    }),
-                },
-            ),
-            (
-                id("0:1:717"),
-                Item {
-                    id: id("0:1:717"),
-                    crate_id: 0,
-                    name: Some("i32".to_owned()),
-                    span: None,
-                    visibility: Visibility::Public,
-                    docs: None,
-                    links: FxHashMap::default(),
-                    attrs: Vec::new(),
-                    deprecation: None,
-                    inner: ItemEnum::Primitive(Primitive { name: "i32".to_owned(), impls: vec![] }),
-                },
-            ),
-        ]),
-        paths: FxHashMap::from_iter([(
-            id("0:1:1571"),
-            ItemSummary {
+            (id("0:0:1572"), Item {
+                id: id("0:0:1572"),
                 crate_id: 0,
-                path: vec!["microcore".to_owned(), "i32".to_owned()],
-                kind: ItemKind::Primitive,
-            },
-        )]),
+                name: Some("microcore".to_owned()),
+                span: None,
+                visibility: Visibility::Public,
+                docs: None,
+                links: FxHashMap::from_iter([(("prim@i32".to_owned(), id("0:1:1571")))]),
+                attrs: Vec::new(),
+                deprecation: None,
+                inner: ItemEnum::Module(Module {
+                    is_crate: true,
+                    items: vec![id("0:1:717")],
+                    is_stripped: false,
+                }),
+            }),
+            (id("0:1:717"), Item {
+                id: id("0:1:717"),
+                crate_id: 0,
+                name: Some("i32".to_owned()),
+                span: None,
+                visibility: Visibility::Public,
+                docs: None,
+                links: FxHashMap::default(),
+                attrs: Vec::new(),
+                deprecation: None,
+                inner: ItemEnum::Primitive(Primitive { name: "i32".to_owned(), impls: vec![] }),
+            }),
+        ]),
+        paths: FxHashMap::from_iter([(id("0:1:1571"), ItemSummary {
+            crate_id: 0,
+            path: vec!["microcore".to_owned(), "i32".to_owned()],
+            kind: ItemKind::Primitive,
+        })]),
         external_crates: FxHashMap::default(),
         format_version: rustdoc_json_types::FORMAT_VERSION,
     };
 
-    check(
-        &krate,
-        &[Error {
-            id: id("0:1:1571"),
-            kind: ErrorKind::Custom("Id for local item in `paths` but not in `index`".to_owned()),
-        }],
-    );
+    check(&krate, &[Error {
+        id: id("0:1:1571"),
+        kind: ErrorKind::Custom("Id for local item in `paths` but not in `index`".to_owned()),
+    }]);
 }
 
 #[test]
@@ -135,25 +113,18 @@ fn checks_local_crate_id_is_correct() {
         root: id("root"),
         crate_version: None,
         includes_private: false,
-        index: FxHashMap::from_iter([(
-            id("root"),
-            Item {
-                id: id("root"),
-                crate_id: LOCAL_CRATE_ID.wrapping_add(1),
-                name: Some("irrelavent".to_owned()),
-                span: None,
-                visibility: Visibility::Public,
-                docs: None,
-                links: FxHashMap::default(),
-                attrs: Vec::new(),
-                deprecation: None,
-                inner: ItemEnum::Module(Module {
-                    is_crate: true,
-                    items: vec![],
-                    is_stripped: false,
-                }),
-            },
-        )]),
+        index: FxHashMap::from_iter([(id("root"), Item {
+            id: id("root"),
+            crate_id: LOCAL_CRATE_ID.wrapping_add(1),
+            name: Some("irrelavent".to_owned()),
+            span: None,
+            visibility: Visibility::Public,
+            docs: None,
+            links: FxHashMap::default(),
+            attrs: Vec::new(),
+            deprecation: None,
+            inner: ItemEnum::Module(Module { is_crate: true, items: vec![], is_stripped: false }),
+        })]),
         paths: FxHashMap::default(),
         external_crates: FxHashMap::default(),
         format_version: FORMAT_VERSION,
diff --git a/src/tools/lint-docs/src/lib.rs b/src/tools/lint-docs/src/lib.rs
index 532a27b22aa6f..8c7ff08ccd72c 100644
--- a/src/tools/lint-docs/src/lib.rs
+++ b/src/tools/lint-docs/src/lib.rs
@@ -19,30 +19,24 @@ mod groups;
 /// level of the lint, which will be more difficult to support, since rustc
 /// currently does not track that historical information.
 static RENAMES: &[(Level, &[(&str, &str)])] = &[
-    (
-        Level::Allow,
-        &[
-            ("single-use-lifetime", "single-use-lifetimes"),
-            ("elided-lifetime-in-path", "elided-lifetimes-in-paths"),
-            ("async-idents", "keyword-idents"),
-            ("disjoint-capture-migration", "rust-2021-incompatible-closure-captures"),
-            ("keyword-idents", "keyword-idents-2018"),
-            ("or-patterns-back-compat", "rust-2021-incompatible-or-patterns"),
-        ],
-    ),
-    (
-        Level::Warn,
-        &[
-            ("bare-trait-object", "bare-trait-objects"),
-            ("unstable-name-collision", "unstable-name-collisions"),
-            ("unused-doc-comment", "unused-doc-comments"),
-            ("redundant-semicolon", "redundant-semicolons"),
-            ("overlapping-patterns", "overlapping-range-endpoints"),
-            ("non-fmt-panic", "non-fmt-panics"),
-            ("unused-tuple-struct-fields", "dead-code"),
-            ("static-mut-ref", "static-mut-refs"),
-        ],
-    ),
+    (Level::Allow, &[
+        ("single-use-lifetime", "single-use-lifetimes"),
+        ("elided-lifetime-in-path", "elided-lifetimes-in-paths"),
+        ("async-idents", "keyword-idents"),
+        ("disjoint-capture-migration", "rust-2021-incompatible-closure-captures"),
+        ("keyword-idents", "keyword-idents-2018"),
+        ("or-patterns-back-compat", "rust-2021-incompatible-or-patterns"),
+    ]),
+    (Level::Warn, &[
+        ("bare-trait-object", "bare-trait-objects"),
+        ("unstable-name-collision", "unstable-name-collisions"),
+        ("unused-doc-comment", "unused-doc-comments"),
+        ("redundant-semicolon", "redundant-semicolons"),
+        ("overlapping-patterns", "overlapping-range-endpoints"),
+        ("non-fmt-panic", "non-fmt-panics"),
+        ("unused-tuple-struct-fields", "dead-code"),
+        ("static-mut-ref", "static-mut-refs"),
+    ]),
     (Level::Deny, &[("exceeding-bitshifts", "arithmetic-overflow")]),
 ];
 
diff --git a/src/tools/miri/README.md b/src/tools/miri/README.md
index d8636915ea80e..f6349f45f43d0 100644
--- a/src/tools/miri/README.md
+++ b/src/tools/miri/README.md
@@ -219,7 +219,7 @@ degree documented below):
   - `solaris` / `illumos`: maintained by @devnexen. Supports `std::{env, thread, sync}`, but not `std::fs`.
   - `freebsd`: **maintainer wanted**. Supports `std::env` and parts of `std::{thread, fs}`, but not `std::sync`.
   - `android`: **maintainer wanted**. Support very incomplete, but a basic "hello world" works.
-  - `wasm`: **maintainer wanted**. Support very incomplete, not even standard output works, but an empty `main` function works.
+  - `wasi`: **maintainer wanted**. Support very incomplete, not even standard output works, but an empty `main` function works.
 - For targets on other operating systems, Miri might fail before even reaching the `main` function.
 
 However, even for targets that we do support, the degree of support for accessing platform APIs
diff --git a/src/tools/miri/ci/ci.sh b/src/tools/miri/ci/ci.sh
index c7be71662bd5f..2d4cf696d8cb7 100755
--- a/src/tools/miri/ci/ci.sh
+++ b/src/tools/miri/ci/ci.sh
@@ -148,18 +148,19 @@ case $HOST_TARGET in
     TEST_TARGET=arm-unknown-linux-gnueabi run_tests
     TEST_TARGET=s390x-unknown-linux-gnu run_tests # big-endian architecture of choice
     # Partially supported targets (tier 2)
-    BASIC="empty_main integer vec string btreemap hello hashmap heap_alloc align" # ensures we have the basics: stdout/stderr, system allocator, randomness (for HashMap initialization)
-    UNIX="panic/panic panic/unwind concurrency/simple atomic libc-mem libc-misc libc-random env num_cpus" # the things that are very similar across all Unixes, and hence easily supported there
+    BASIC="empty_main integer heap_alloc libc-mem vec string btreemap" # ensures we have the basics: pre-main code, system allocator
+    UNIX="hello panic/panic panic/unwind concurrency/simple atomic libc-mem libc-misc libc-random env num_cpus" # the things that are very similar across all Unixes, and hence easily supported there
     TEST_TARGET=x86_64-unknown-freebsd run_tests_minimal $BASIC $UNIX threadname pthread time fs
     TEST_TARGET=i686-unknown-freebsd   run_tests_minimal $BASIC $UNIX threadname pthread time fs
     TEST_TARGET=x86_64-unknown-illumos run_tests_minimal $BASIC $UNIX thread sync available-parallelism time tls
     TEST_TARGET=x86_64-pc-solaris      run_tests_minimal $BASIC $UNIX thread sync available-parallelism time tls
-    TEST_TARGET=aarch64-linux-android  run_tests_minimal $BASIC $UNIX pthread --skip threadname --skip pthread_cond_timedwait
-    TEST_TARGET=wasm32-wasip2          run_tests_minimal empty_main wasm heap_alloc libc-mem
-    TEST_TARGET=wasm32-unknown-unknown run_tests_minimal empty_main wasm
+    TEST_TARGET=aarch64-linux-android  run_tests_minimal $BASIC $UNIX hashmap pthread --skip threadname --skip pthread_cond_timedwait
+    TEST_TARGET=wasm32-wasip2          run_tests_minimal $BASIC wasm
+    TEST_TARGET=wasm32-unknown-unknown run_tests_minimal no_std empty_main wasm # this target doesn't really have std
     TEST_TARGET=thumbv7em-none-eabihf  run_tests_minimal no_std
     # Custom target JSON file
-    TEST_TARGET=tests/avr.json MIRI_NO_STD=1 run_tests_minimal no_std
+    # FIXME: disabled due to .
+    #TEST_TARGET=tests/avr.json MIRI_NO_STD=1 run_tests_minimal no_std
     ;;
   i686-pc-windows-msvc)
     # Host
diff --git a/src/tools/miri/rust-version b/src/tools/miri/rust-version
index 76fe17316ac65..79ed6cc7d74b8 100644
--- a/src/tools/miri/rust-version
+++ b/src/tools/miri/rust-version
@@ -1 +1 @@
-6ce376774c0bc46ac8be247bca93ff5a1287a8fc
+1b5aa96d6016bafe50e071b45d4d2e3c90fd766f
diff --git a/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs b/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs
index e7d7cc28eeee6..f792e75ad0855 100644
--- a/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs
+++ b/src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs
@@ -22,9 +22,9 @@ use crate::borrow_tracker::{
 use crate::concurrency::data_race::{NaReadType, NaWriteType};
 use crate::*;
 
-use diagnostics::{RetagCause, RetagInfo};
-pub use item::{Item, Permission};
-pub use stack::Stack;
+use self::diagnostics::{RetagCause, RetagInfo};
+pub use self::item::{Item, Permission};
+pub use self::stack::Stack;
 
 pub type AllocState = Stacks;
 
diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs
index 89b8ff1af8bdb..2afe02dc2c7f8 100644
--- a/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs
+++ b/src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs
@@ -19,8 +19,8 @@ mod unimap;
 #[cfg(test)]
 mod exhaustive;
 
-use perms::Permission;
-pub use tree::Tree;
+use self::perms::Permission;
+pub use self::tree::Tree;
 
 pub type AllocState = Tree;
 
diff --git a/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs b/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs
index dfb9b8637fde5..28f9dec7bb98a 100644
--- a/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs
+++ b/src/tools/miri/src/borrow_tracker/tree_borrows/perms.rs
@@ -47,7 +47,7 @@ enum PermissionPriv {
     /// rejects: all child accesses (UB).
     Disabled,
 }
-use PermissionPriv::*;
+use self::PermissionPriv::*;
 
 impl PartialOrd for PermissionPriv {
     /// PermissionPriv is ordered by the reflexive transitive closure of
diff --git a/src/tools/miri/src/concurrency/mod.rs b/src/tools/miri/src/concurrency/mod.rs
index 17789fe9f87fa..c5082b4e40b4c 100644
--- a/src/tools/miri/src/concurrency/mod.rs
+++ b/src/tools/miri/src/concurrency/mod.rs
@@ -7,4 +7,4 @@ pub mod thread;
 mod vector_clock;
 pub mod weak_memory;
 
-pub use vector_clock::VClock;
+pub use self::vector_clock::VClock;
diff --git a/src/tools/miri/src/intrinsics/atomic.rs b/src/tools/miri/src/intrinsics/atomic.rs
index d76f622e84baf..f38c3b821742a 100644
--- a/src/tools/miri/src/intrinsics/atomic.rs
+++ b/src/tools/miri/src/intrinsics/atomic.rs
@@ -1,7 +1,7 @@
 use rustc_middle::{mir, mir::BinOp, ty};
 
+use self::helpers::check_arg_count;
 use crate::*;
-use helpers::check_arg_count;
 
 pub enum AtomicOp {
     /// The `bool` indicates whether the result of the operation should be negated (`UnOp::Not`,
diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs
index 3eeb11dbbb4a0..d8d267f5ba693 100644
--- a/src/tools/miri/src/intrinsics/mod.rs
+++ b/src/tools/miri/src/intrinsics/mod.rs
@@ -12,10 +12,10 @@ use rustc_middle::{
 use rustc_span::{Symbol, sym};
 use rustc_target::abi::Size;
 
+use self::atomic::EvalContextExt as _;
+use self::helpers::{ToHost, ToSoft, check_arg_count};
+use self::simd::EvalContextExt as _;
 use crate::*;
-use atomic::EvalContextExt as _;
-use helpers::{ToHost, ToSoft, check_arg_count};
-use simd::EvalContextExt as _;
 
 impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
 pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
diff --git a/src/tools/miri/src/lib.rs b/src/tools/miri/src/lib.rs
index b39f88dd1c9dc..6e015813e77a7 100644
--- a/src/tools/miri/src/lib.rs
+++ b/src/tools/miri/src/lib.rs
@@ -51,6 +51,8 @@
     clippy::cast_lossless,
     clippy::cast_possible_truncation,
 )]
+#![cfg_attr(not(bootstrap), feature(unqualified_local_imports))]
+#![cfg_attr(not(bootstrap), warn(unqualified_local_imports))]
 // Needed for rustdoc from bootstrap (with `-Znormalize-docs`).
 #![recursion_limit = "256"]
 
diff --git a/src/tools/miri/src/shims/env.rs b/src/tools/miri/src/shims/env.rs
index 6586ea8e48cff..d12a0581b4137 100644
--- a/src/tools/miri/src/shims/env.rs
+++ b/src/tools/miri/src/shims/env.rs
@@ -2,8 +2,8 @@ use std::ffi::{OsStr, OsString};
 
 use rustc_data_structures::fx::FxHashMap;
 
+use self::shims::{unix::UnixEnvVars, windows::WindowsEnvVars};
 use crate::*;
-use shims::{unix::UnixEnvVars, windows::WindowsEnvVars};
 
 #[derive(Default)]
 pub enum EnvVars<'tcx> {
diff --git a/src/tools/miri/src/shims/foreign_items.rs b/src/tools/miri/src/shims/foreign_items.rs
index 67dc1476175d8..c0484dde59b5b 100644
--- a/src/tools/miri/src/shims/foreign_items.rs
+++ b/src/tools/miri/src/shims/foreign_items.rs
@@ -12,10 +12,10 @@ use rustc_target::{
     spec::abi::Abi,
 };
 
+use self::helpers::{ToHost, ToSoft};
 use super::alloc::EvalContextExt as _;
 use super::backtrace::EvalContextExt as _;
 use crate::*;
-use helpers::{ToHost, ToSoft};
 
 /// Type of dynamic symbols (for `dlsym` et al)
 #[derive(Debug, Copy, Clone)]
diff --git a/src/tools/miri/src/shims/mod.rs b/src/tools/miri/src/shims/mod.rs
index 618cf8cf200c1..a689ac2b3784e 100644
--- a/src/tools/miri/src/shims/mod.rs
+++ b/src/tools/miri/src/shims/mod.rs
@@ -17,7 +17,7 @@ pub mod panic;
 pub mod time;
 pub mod tls;
 
-pub use unix::{DirTable, EpollInterestTable, FdTable};
+pub use self::unix::{DirTable, EpollInterestTable, FdTable};
 
 /// What needs to be done after emulating an item (a shim or an intrinsic) is done.
 pub enum EmulateItemResult {
diff --git a/src/tools/miri/src/shims/panic.rs b/src/tools/miri/src/shims/panic.rs
index 44f942cb4c58c..55b814a09fa01 100644
--- a/src/tools/miri/src/shims/panic.rs
+++ b/src/tools/miri/src/shims/panic.rs
@@ -16,8 +16,8 @@ use rustc_middle::{mir, ty};
 use rustc_target::spec::PanicStrategy;
 use rustc_target::spec::abi::Abi;
 
+use self::helpers::check_arg_count;
 use crate::*;
-use helpers::check_arg_count;
 
 /// Holds all of the relevant data for when unwinding hits a `try` frame.
 #[derive(Debug)]
diff --git a/src/tools/miri/src/shims/unix/foreign_items.rs b/src/tools/miri/src/shims/unix/foreign_items.rs
index 57dae05025002..c06ce57e610a0 100644
--- a/src/tools/miri/src/shims/unix/foreign_items.rs
+++ b/src/tools/miri/src/shims/unix/foreign_items.rs
@@ -11,11 +11,11 @@ use crate::shims::alloc::EvalContextExt as _;
 use crate::shims::unix::*;
 use crate::*;
 
-use shims::unix::android::foreign_items as android;
-use shims::unix::freebsd::foreign_items as freebsd;
-use shims::unix::linux::foreign_items as linux;
-use shims::unix::macos::foreign_items as macos;
-use shims::unix::solarish::foreign_items as solarish;
+use self::shims::unix::android::foreign_items as android;
+use self::shims::unix::freebsd::foreign_items as freebsd;
+use self::shims::unix::linux::foreign_items as linux;
+use self::shims::unix::macos::foreign_items as macos;
+use self::shims::unix::solarish::foreign_items as solarish;
 
 pub fn is_dyn_sym(name: &str, target_os: &str) -> bool {
     match name {
diff --git a/src/tools/miri/src/shims/unix/fs.rs b/src/tools/miri/src/shims/unix/fs.rs
index 1f7e1b3bd7c07..1b657db5cccc0 100644
--- a/src/tools/miri/src/shims/unix/fs.rs
+++ b/src/tools/miri/src/shims/unix/fs.rs
@@ -11,11 +11,11 @@ use std::time::SystemTime;
 use rustc_data_structures::fx::FxHashMap;
 use rustc_target::abi::Size;
 
+use self::shims::time::system_time_to_duration;
 use crate::shims::os_str::bytes_to_os_str;
 use crate::shims::unix::fd::FileDescriptionRef;
 use crate::shims::unix::*;
 use crate::*;
-use shims::time::system_time_to_duration;
 
 use self::fd::FlockOp;
 
diff --git a/src/tools/miri/src/shims/unix/linux/foreign_items.rs b/src/tools/miri/src/shims/unix/linux/foreign_items.rs
index d64f13f63d91f..07527a9d6e332 100644
--- a/src/tools/miri/src/shims/unix/linux/foreign_items.rs
+++ b/src/tools/miri/src/shims/unix/linux/foreign_items.rs
@@ -1,14 +1,14 @@
 use rustc_span::Symbol;
 use rustc_target::spec::abi::Abi;
 
+use self::shims::unix::linux::epoll::EvalContextExt as _;
+use self::shims::unix::linux::eventfd::EvalContextExt as _;
+use self::shims::unix::linux::mem::EvalContextExt as _;
+use self::shims::unix::linux::sync::futex;
 use crate::machine::SIGRTMAX;
 use crate::machine::SIGRTMIN;
 use crate::shims::unix::*;
 use crate::*;
-use shims::unix::linux::epoll::EvalContextExt as _;
-use shims::unix::linux::eventfd::EvalContextExt as _;
-use shims::unix::linux::mem::EvalContextExt as _;
-use shims::unix::linux::sync::futex;
 
 pub fn is_dyn_sym(name: &str) -> bool {
     matches!(name, "statx")
diff --git a/src/tools/miri/src/shims/unix/macos/foreign_items.rs b/src/tools/miri/src/shims/unix/macos/foreign_items.rs
index 47b887dec9473..ce4ea0816f016 100644
--- a/src/tools/miri/src/shims/unix/macos/foreign_items.rs
+++ b/src/tools/miri/src/shims/unix/macos/foreign_items.rs
@@ -78,6 +78,17 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
                 this.write_pointer(environ, dest)?;
             }
 
+            // Random data generation
+            "CCRandomGenerateBytes" => {
+                let [bytes, count] =
+                    this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
+                let bytes = this.read_pointer(bytes)?;
+                let count = this.read_target_usize(count)?;
+                let success = this.eval_libc_i32("kCCSuccess");
+                this.gen_random(bytes, count)?;
+                this.write_int(success, dest)?;
+            }
+
             // Time related shims
             "mach_absolute_time" => {
                 let [] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;
diff --git a/src/tools/miri/src/shims/unix/mod.rs b/src/tools/miri/src/shims/unix/mod.rs
index 7da6d7b02a2a0..a95b4d3d30793 100644
--- a/src/tools/miri/src/shims/unix/mod.rs
+++ b/src/tools/miri/src/shims/unix/mod.rs
@@ -14,18 +14,18 @@ mod linux;
 mod macos;
 mod solarish;
 
-pub use env::UnixEnvVars;
-pub use fd::{FdTable, FileDescription};
-pub use fs::DirTable;
-pub use linux::epoll::EpollInterestTable;
+pub use self::env::UnixEnvVars;
+pub use self::fd::{FdTable, FileDescription};
+pub use self::fs::DirTable;
+pub use self::linux::epoll::EpollInterestTable;
 // All the Unix-specific extension traits
-pub use env::EvalContextExt as _;
-pub use fd::EvalContextExt as _;
-pub use fs::EvalContextExt as _;
-pub use mem::EvalContextExt as _;
-pub use sync::EvalContextExt as _;
-pub use thread::EvalContextExt as _;
-pub use unnamed_socket::EvalContextExt as _;
+pub use self::env::EvalContextExt as _;
+pub use self::fd::EvalContextExt as _;
+pub use self::fs::EvalContextExt as _;
+pub use self::mem::EvalContextExt as _;
+pub use self::sync::EvalContextExt as _;
+pub use self::thread::EvalContextExt as _;
+pub use self::unnamed_socket::EvalContextExt as _;
 
 // Make up some constants.
 const UID: u32 = 1000;
diff --git a/src/tools/miri/src/shims/windows/env.rs b/src/tools/miri/src/shims/windows/env.rs
index 495df18a6eaa2..9707482b1e2c2 100644
--- a/src/tools/miri/src/shims/windows/env.rs
+++ b/src/tools/miri/src/shims/windows/env.rs
@@ -4,8 +4,8 @@ use std::io::ErrorKind;
 
 use rustc_data_structures::fx::FxHashMap;
 
+use self::helpers::windows_check_buffer_size;
 use crate::*;
-use helpers::windows_check_buffer_size;
 
 #[derive(Default)]
 pub struct WindowsEnvVars {
diff --git a/src/tools/miri/src/shims/windows/foreign_items.rs b/src/tools/miri/src/shims/windows/foreign_items.rs
index f840ba161650e..998daddf5208f 100644
--- a/src/tools/miri/src/shims/windows/foreign_items.rs
+++ b/src/tools/miri/src/shims/windows/foreign_items.rs
@@ -8,10 +8,10 @@ use rustc_span::Symbol;
 use rustc_target::abi::{Align, Size};
 use rustc_target::spec::abi::Abi;
 
+use self::shims::windows::handle::{Handle, PseudoHandle};
 use crate::shims::os_str::bytes_to_os_str;
 use crate::shims::windows::*;
 use crate::*;
-use shims::windows::handle::{Handle, PseudoHandle};
 
 pub fn is_dyn_sym(name: &str) -> bool {
     // std does dynamic detection for these symbols
diff --git a/src/tools/miri/src/shims/windows/mod.rs b/src/tools/miri/src/shims/windows/mod.rs
index 65f682b9dad9a..537c724e52665 100644
--- a/src/tools/miri/src/shims/windows/mod.rs
+++ b/src/tools/miri/src/shims/windows/mod.rs
@@ -5,9 +5,9 @@ mod handle;
 mod sync;
 mod thread;
 
-pub use env::WindowsEnvVars;
+pub use self::env::WindowsEnvVars;
 // All the Windows-specific extension traits
-pub use env::EvalContextExt as _;
-pub use handle::EvalContextExt as _;
-pub use sync::EvalContextExt as _;
-pub use thread::EvalContextExt as _;
+pub use self::env::EvalContextExt as _;
+pub use self::handle::EvalContextExt as _;
+pub use self::sync::EvalContextExt as _;
+pub use self::thread::EvalContextExt as _;
diff --git a/src/tools/miri/src/shims/windows/thread.rs b/src/tools/miri/src/shims/windows/thread.rs
index f3ddf6072af1f..a4c177311d46d 100644
--- a/src/tools/miri/src/shims/windows/thread.rs
+++ b/src/tools/miri/src/shims/windows/thread.rs
@@ -1,8 +1,8 @@
 use rustc_middle::ty::layout::LayoutOf;
 use rustc_target::spec::abi::Abi;
 
+use self::shims::windows::handle::{EvalContextExt as _, Handle, PseudoHandle};
 use crate::*;
-use shims::windows::handle::{EvalContextExt as _, Handle, PseudoHandle};
 
 impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
 
diff --git a/src/tools/miri/src/shims/x86/mod.rs b/src/tools/miri/src/shims/x86/mod.rs
index 7c7a0935c47ab..211bd168af28b 100644
--- a/src/tools/miri/src/shims/x86/mod.rs
+++ b/src/tools/miri/src/shims/x86/mod.rs
@@ -8,8 +8,8 @@ use rustc_span::Symbol;
 use rustc_target::abi::Size;
 use rustc_target::spec::abi::Abi;
 
+use self::helpers::bool_to_simd_element;
 use crate::*;
-use helpers::bool_to_simd_element;
 
 mod aesni;
 mod avx;
diff --git a/src/tools/miri/tests/fail/dyn-call-trait-mismatch.rs b/src/tools/miri/tests/fail/dyn-call-trait-mismatch.rs
index 982d57b737202..7ac619e09abf6 100644
--- a/src/tools/miri/tests/fail/dyn-call-trait-mismatch.rs
+++ b/src/tools/miri/tests/fail/dyn-call-trait-mismatch.rs
@@ -16,5 +16,5 @@ impl T1 for i32 {
 fn main() {
     let r = Box::new(0) as Box;
     let r2: Box = unsafe { std::mem::transmute(r) };
-    r2.method2(); //~ERROR: using vtable for trait `T1` but trait `T2` was expected
+    r2.method2(); //~ERROR: using vtable for `T1` but `T2` was expected
 }
diff --git a/src/tools/miri/tests/fail/dyn-call-trait-mismatch.stderr b/src/tools/miri/tests/fail/dyn-call-trait-mismatch.stderr
index 3680a84fac271..37d102c87134d 100644
--- a/src/tools/miri/tests/fail/dyn-call-trait-mismatch.stderr
+++ b/src/tools/miri/tests/fail/dyn-call-trait-mismatch.stderr
@@ -1,8 +1,8 @@
-error: Undefined Behavior: using vtable for trait `T1` but trait `T2` was expected
+error: Undefined Behavior: using vtable for `T1` but `T2` was expected
   --> tests/fail/dyn-call-trait-mismatch.rs:LL:CC
    |
 LL |     r2.method2();
-   |     ^^^^^^^^^^^^ using vtable for trait `T1` but trait `T2` was expected
+   |     ^^^^^^^^^^^^ using vtable for `T1` but `T2` was expected
    |
    = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
    = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
diff --git a/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.rs b/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.rs
index 85d7582d112ae..f450e7e652c51 100644
--- a/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.rs
+++ b/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.rs
@@ -63,6 +63,6 @@ fn main() {
         let baz: &dyn Baz = &1;
         let baz_fake: *const dyn Bar = std::mem::transmute(baz);
         let _err = baz_fake as *const dyn Foo;
-        //~^ERROR: using vtable for trait `Baz` but trait `Bar` was expected
+        //~^ERROR: using vtable for `Baz` but `Bar` was expected
     }
 }
diff --git a/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.stderr b/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.stderr
index 2129fe66e9c02..d0fd0e6fcc144 100644
--- a/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.stderr
+++ b/src/tools/miri/tests/fail/dyn-upcast-trait-mismatch.stderr
@@ -1,8 +1,8 @@
-error: Undefined Behavior: using vtable for trait `Baz` but trait `Bar` was expected
+error: Undefined Behavior: using vtable for `Baz` but `Bar` was expected
   --> tests/fail/dyn-upcast-trait-mismatch.rs:LL:CC
    |
 LL |         let _err = baz_fake as *const dyn Foo;
-   |                    ^^^^^^^^ using vtable for trait `Baz` but trait `Bar` was expected
+   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^ using vtable for `Baz` but `Bar` was expected
    |
    = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
    = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
diff --git a/src/tools/miri/tests/fail/validity/wrong-dyn-trait-assoc-type.rs b/src/tools/miri/tests/fail/validity/wrong-dyn-trait-assoc-type.rs
new file mode 100644
index 0000000000000..566ddac2cc71a
--- /dev/null
+++ b/src/tools/miri/tests/fail/validity/wrong-dyn-trait-assoc-type.rs
@@ -0,0 +1,20 @@
+trait Trait {
+    type Assoc;
+    fn foo(&self) -> Self::Assoc;
+}
+
+impl Trait for T {
+    type Assoc = T;
+    fn foo(&self) -> T {
+        *self
+    }
+}
+
+fn main() {
+    let v: Box> = Box::new(2);
+    let v: Box> = unsafe { std::mem::transmute(v) }; //~ERROR: wrong trait
+
+    if v.foo() {
+        println!("huh");
+    }
+}
diff --git a/src/tools/miri/tests/fail/validity/wrong-dyn-trait-assoc-type.stderr b/src/tools/miri/tests/fail/validity/wrong-dyn-trait-assoc-type.stderr
new file mode 100644
index 0000000000000..44939a5a838cc
--- /dev/null
+++ b/src/tools/miri/tests/fail/validity/wrong-dyn-trait-assoc-type.stderr
@@ -0,0 +1,15 @@
+error: Undefined Behavior: constructing invalid value: wrong trait in wide pointer vtable: expected `Trait`, but encountered `Trait`
+  --> tests/fail/validity/wrong-dyn-trait-assoc-type.rs:LL:CC
+   |
+LL |     let v: Box> = unsafe { std::mem::transmute(v) };
+   |                                                    ^^^^^^^^^^^^^^^^^^^^^^ constructing invalid value: wrong trait in wide pointer vtable: expected `Trait`, but encountered `Trait`
+   |
+   = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
+   = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
+   = note: BACKTRACE:
+   = note: inside `main` at tests/fail/validity/wrong-dyn-trait-assoc-type.rs:LL:CC
+
+note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
+
+error: aborting due to 1 previous error
+
diff --git a/src/tools/miri/tests/fail/validity/wrong-dyn-trait.stderr b/src/tools/miri/tests/fail/validity/wrong-dyn-trait.stderr
index 4be3fb52bdb7f..45c882bebdfc6 100644
--- a/src/tools/miri/tests/fail/validity/wrong-dyn-trait.stderr
+++ b/src/tools/miri/tests/fail/validity/wrong-dyn-trait.stderr
@@ -1,8 +1,8 @@
-error: Undefined Behavior: constructing invalid value: wrong trait in wide pointer vtable: expected `std::fmt::Debug`, but encountered ``
+error: Undefined Behavior: constructing invalid value: wrong trait in wide pointer vtable: expected `std::fmt::Debug`, but encountered `std::marker::Send`
   --> tests/fail/validity/wrong-dyn-trait.rs:LL:CC
    |
 LL |     let _y: *const dyn fmt::Debug = unsafe { mem::transmute(x) };
-   |                                              ^^^^^^^^^^^^^^^^^ constructing invalid value: wrong trait in wide pointer vtable: expected `std::fmt::Debug`, but encountered ``
+   |                                              ^^^^^^^^^^^^^^^^^ constructing invalid value: wrong trait in wide pointer vtable: expected `std::fmt::Debug`, but encountered `std::marker::Send`
    |
    = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
    = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
diff --git a/src/tools/miri/tests/pass-dep/libc/ccrandomgeneratebytes_apple.rs b/src/tools/miri/tests/pass-dep/libc/ccrandomgeneratebytes_apple.rs
new file mode 100644
index 0000000000000..afcc02bc83971
--- /dev/null
+++ b/src/tools/miri/tests/pass-dep/libc/ccrandomgeneratebytes_apple.rs
@@ -0,0 +1,7 @@
+//@only-target: apple # This directly tests apple-only functions
+
+fn main() {
+    let mut bytes = [0u8; 24];
+    let ret = unsafe { libc::CCRandomGenerateBytes(bytes.as_mut_ptr().cast(), bytes.len()) };
+    assert_eq!(ret, libc::kCCSuccess);
+}
diff --git a/src/tools/miri/tests/pass/shims/fs.rs b/src/tools/miri/tests/pass/shims/fs.rs
index 62424ca26b1c7..81151f4ac4730 100644
--- a/src/tools/miri/tests/pass/shims/fs.rs
+++ b/src/tools/miri/tests/pass/shims/fs.rs
@@ -4,7 +4,7 @@
 #![feature(io_error_more)]
 #![feature(io_error_uncategorized)]
 
-use std::collections::HashMap;
+use std::collections::BTreeMap;
 use std::ffi::OsString;
 use std::fs::{
     File, OpenOptions, canonicalize, create_dir, read_dir, remove_dir, remove_dir_all, remove_file,
@@ -262,7 +262,7 @@ fn test_directory() {
     create_dir(&dir_1).unwrap();
     // Test that read_dir metadata calls succeed
     assert_eq!(
-        HashMap::from([
+        BTreeMap::from([
             (OsString::from("test_file_1"), true),
             (OsString::from("test_file_2"), true),
             (OsString::from("test_dir_1"), false)
@@ -273,7 +273,7 @@ fn test_directory() {
                 let e = e.unwrap();
                 (e.file_name(), e.metadata().unwrap().is_file())
             })
-            .collect::>()
+            .collect::>()
     );
     // Deleting the directory should fail, since it is not empty.
     assert_eq!(ErrorKind::DirectoryNotEmpty, remove_dir(&dir_path).unwrap_err().kind());
diff --git a/src/tools/miri/tests/pass/shims/random.rs b/src/tools/miri/tests/pass/shims/random.rs
new file mode 100644
index 0000000000000..ae75ebdcd3f32
--- /dev/null
+++ b/src/tools/miri/tests/pass/shims/random.rs
@@ -0,0 +1,5 @@
+#![feature(random)]
+
+fn main() {
+    let _x: i32 = std::random::random();
+}
diff --git a/src/tools/opt-dist/src/main.rs b/src/tools/opt-dist/src/main.rs
index 73389f930bda3..6211b5670aa69 100644
--- a/src/tools/opt-dist/src/main.rs
+++ b/src/tools/opt-dist/src/main.rs
@@ -6,7 +6,7 @@ use utils::io;
 
 use crate::bolt::{bolt_optimize, with_bolt_instrumented};
 use crate::environment::{Environment, EnvironmentBuilder};
-use crate::exec::{cmd, Bootstrap};
+use crate::exec::{Bootstrap, cmd};
 use crate::tests::run_tests;
 use crate::timer::Timer;
 use crate::training::{
diff --git a/src/tools/opt-dist/src/tests.rs b/src/tools/opt-dist/src/tests.rs
index e7a3ed787ed7c..82c393d34a679 100644
--- a/src/tools/opt-dist/src/tests.rs
+++ b/src/tools/opt-dist/src/tests.rs
@@ -1,7 +1,7 @@
 use anyhow::Context;
 use camino::{Utf8Path, Utf8PathBuf};
 
-use crate::environment::{executable_extension, Environment};
+use crate::environment::{Environment, executable_extension};
 use crate::exec::cmd;
 use crate::utils::io::{copy_directory, find_file_in_dir, unpack_archive};
 
diff --git a/src/tools/opt-dist/src/training.rs b/src/tools/opt-dist/src/training.rs
index 97e8ec5c6edfb..30c79f9594744 100644
--- a/src/tools/opt-dist/src/training.rs
+++ b/src/tools/opt-dist/src/training.rs
@@ -3,8 +3,8 @@ use build_helper::{LLVM_PGO_CRATES, RUSTC_PGO_CRATES};
 use camino::{Utf8Path, Utf8PathBuf};
 use humansize::BINARY;
 
-use crate::environment::{executable_extension, Environment};
-use crate::exec::{cmd, CmdBuilder};
+use crate::environment::{Environment, executable_extension};
+use crate::exec::{CmdBuilder, cmd};
 use crate::utils::io::{count_files, delete_directory};
 use crate::utils::with_log_group;
 
diff --git a/src/tools/opt-dist/src/utils/artifact_size.rs b/src/tools/opt-dist/src/utils/artifact_size.rs
index e51b5f06dfb38..74f7f75b9c014 100644
--- a/src/tools/opt-dist/src/utils/artifact_size.rs
+++ b/src/tools/opt-dist/src/utils/artifact_size.rs
@@ -11,7 +11,7 @@ use crate::utils::io::get_files_from_dir;
 pub fn print_binary_sizes(env: &Environment) -> anyhow::Result<()> {
     use std::fmt::Write;
 
-    use humansize::{format_size, BINARY};
+    use humansize::{BINARY, format_size};
 
     let root = env.build_artifacts().join("stage2");
 
diff --git a/src/tools/run-make-support/src/external_deps/cargo.rs b/src/tools/run-make-support/src/external_deps/cargo.rs
index b0e045dc80bf8..e91d101cb995b 100644
--- a/src/tools/run-make-support/src/external_deps/cargo.rs
+++ b/src/tools/run-make-support/src/external_deps/cargo.rs
@@ -1,7 +1,8 @@
 use crate::command::Command;
 use crate::env_var;
 
-/// Returns a command that can be used to invoke Cargo.
+/// Returns a command that can be used to invoke cargo. The cargo is provided by compiletest
+/// through the `CARGO` env var.
 pub fn cargo() -> Command {
-    Command::new(env_var("BOOTSTRAP_CARGO"))
+    Command::new(env_var("CARGO"))
 }
diff --git a/src/tools/rust-installer/src/combiner.rs b/src/tools/rust-installer/src/combiner.rs
index 66b3d324568cb..487b7cae84436 100644
--- a/src/tools/rust-installer/src/combiner.rs
+++ b/src/tools/rust-installer/src/combiner.rs
@@ -1,7 +1,7 @@
 use std::io::{Read, Write};
 use std::path::Path;
 
-use anyhow::{bail, Context, Result};
+use anyhow::{Context, Result, bail};
 use tar::Archive;
 
 use super::{Scripter, Tarballer};
diff --git a/src/tools/rust-installer/src/compression.rs b/src/tools/rust-installer/src/compression.rs
index df3a98ae789b0..96c48657c4691 100644
--- a/src/tools/rust-installer/src/compression.rs
+++ b/src/tools/rust-installer/src/compression.rs
@@ -81,17 +81,14 @@ impl CompressionFormat {
         let file = crate::util::create_new_file(path)?;
 
         Ok(match self {
-            CompressionFormat::Gz => Box::new(GzEncoder::new(
-                file,
-                match profile {
-                    CompressionProfile::Fast => flate2::Compression::fast(),
-                    CompressionProfile::Balanced => flate2::Compression::new(6),
-                    CompressionProfile::Best => flate2::Compression::best(),
-                    CompressionProfile::NoOp => panic!(
-                        "compression profile 'no-op' should not call `CompressionFormat::encode`."
-                    ),
-                },
-            )),
+            CompressionFormat::Gz => Box::new(GzEncoder::new(file, match profile {
+                CompressionProfile::Fast => flate2::Compression::fast(),
+                CompressionProfile::Balanced => flate2::Compression::new(6),
+                CompressionProfile::Best => flate2::Compression::best(),
+                CompressionProfile::NoOp => panic!(
+                    "compression profile 'no-op' should not call `CompressionFormat::encode`."
+                ),
+            })),
             CompressionFormat::Xz => {
                 let encoder = match profile {
                     CompressionProfile::NoOp => panic!(
diff --git a/src/tools/rust-installer/src/generator.rs b/src/tools/rust-installer/src/generator.rs
index e122869334401..d8a8a11332bba 100644
--- a/src/tools/rust-installer/src/generator.rs
+++ b/src/tools/rust-installer/src/generator.rs
@@ -2,7 +2,7 @@ use std::collections::BTreeSet;
 use std::io::Write;
 use std::path::Path;
 
-use anyhow::{bail, format_err, Context, Result};
+use anyhow::{Context, Result, bail, format_err};
 
 use super::{Scripter, Tarballer};
 use crate::compression::{CompressionFormats, CompressionProfile};
diff --git a/src/tools/rust-installer/src/tarballer.rs b/src/tools/rust-installer/src/tarballer.rs
index a101be8f5ff1f..854bb85f2c526 100644
--- a/src/tools/rust-installer/src/tarballer.rs
+++ b/src/tools/rust-installer/src/tarballer.rs
@@ -2,7 +2,7 @@ use std::fs::{read_link, symlink_metadata};
 use std::io::{BufWriter, Write};
 use std::path::Path;
 
-use anyhow::{bail, Context, Result};
+use anyhow::{Context, Result, bail};
 use tar::{Builder, Header, HeaderMode};
 use walkdir::WalkDir;
 
diff --git a/src/tools/rust-installer/src/util.rs b/src/tools/rust-installer/src/util.rs
index 51b8c9c9d1b63..bbded1df31028 100644
--- a/src/tools/rust-installer/src/util.rs
+++ b/src/tools/rust-installer/src/util.rs
@@ -1,15 +1,15 @@
 use std::fs;
-// FIXME: what about Windows? Are default ACLs executable?
-#[cfg(unix)]
-use std::os::unix::fs::symlink as symlink_file;
 // Needed to set the script mode to executable.
 #[cfg(unix)]
 use std::os::unix::fs::OpenOptionsExt;
+// FIXME: what about Windows? Are default ACLs executable?
+#[cfg(unix)]
+use std::os::unix::fs::symlink as symlink_file;
 #[cfg(windows)]
 use std::os::windows::fs::symlink_file;
 use std::path::Path;
 
-use anyhow::{format_err, Context, Result};
+use anyhow::{Context, Result, format_err};
 use walkdir::WalkDir;
 
 /// Converts a `&Path` to a UTF-8 `&str`.
diff --git a/src/tools/rustbook/src/main.rs b/src/tools/rustbook/src/main.rs
index a4faac0760f4f..2118af6139690 100644
--- a/src/tools/rustbook/src/main.rs
+++ b/src/tools/rustbook/src/main.rs
@@ -1,9 +1,9 @@
 use std::env;
 use std::path::{Path, PathBuf};
 
-use clap::{arg, crate_version, ArgMatches, Command};
-use mdbook::errors::Result as Result3;
+use clap::{ArgMatches, Command, arg, crate_version};
 use mdbook::MDBook;
+use mdbook::errors::Result as Result3;
 use mdbook_i18n_helpers::preprocessors::Gettext;
 use mdbook_spec::Spec;
 use mdbook_trpl_listing::TrplListing;
diff --git a/src/tools/rustdoc-themes/main.rs b/src/tools/rustdoc-themes/main.rs
index 1eba83a80572f..9f0663bd8ee01 100644
--- a/src/tools/rustdoc-themes/main.rs
+++ b/src/tools/rustdoc-themes/main.rs
@@ -1,8 +1,8 @@
 use std::env::args;
-use std::fs::{create_dir_all, File};
+use std::fs::{File, create_dir_all};
 use std::io::{BufRead, BufReader, BufWriter, Write};
 use std::path::Path;
-use std::process::{exit, Command};
+use std::process::{Command, exit};
 
 fn get_themes>(style_path: P) -> Vec {
     let mut ret = Vec::with_capacity(10);
diff --git a/src/tools/suggest-tests/src/main.rs b/src/tools/suggest-tests/src/main.rs
index 6f09bddcf60b8..ee8cc40404d49 100644
--- a/src/tools/suggest-tests/src/main.rs
+++ b/src/tools/suggest-tests/src/main.rs
@@ -1,6 +1,6 @@
 use std::process::ExitCode;
 
-use build_helper::git::{get_git_modified_files, GitConfig};
+use build_helper::git::{GitConfig, get_git_modified_files};
 use suggest_tests::get_suggestions;
 
 fn main() -> ExitCode {
diff --git a/src/tools/suggest-tests/src/static_suggestions.rs b/src/tools/suggest-tests/src/static_suggestions.rs
index a282facd9df92..b216138cf9a58 100644
--- a/src/tools/suggest-tests/src/static_suggestions.rs
+++ b/src/tools/suggest-tests/src/static_suggestions.rs
@@ -1,6 +1,6 @@
 use std::sync::OnceLock;
 
-use crate::{sug, Suggestion};
+use crate::{Suggestion, sug};
 
 // FIXME: perhaps this could use `std::lazy` when it is stablizied
 macro_rules! static_suggestions {
diff --git a/src/tools/tidy/src/ext_tool_checks.rs b/src/tools/tidy/src/ext_tool_checks.rs
index ea9ab01aaf837..8f21338c7dbc8 100644
--- a/src/tools/tidy/src/ext_tool_checks.rs
+++ b/src/tools/tidy/src/ext_tool_checks.rs
@@ -172,11 +172,10 @@ fn check_impl(
         let files;
         if file_args_clang_format.is_empty() {
             let llvm_wrapper = root_path.join("compiler/rustc_llvm/llvm-wrapper");
-            files = find_with_extension(
-                root_path,
-                Some(llvm_wrapper.as_path()),
-                &[OsStr::new("h"), OsStr::new("cpp")],
-            )?;
+            files = find_with_extension(root_path, Some(llvm_wrapper.as_path()), &[
+                OsStr::new("h"),
+                OsStr::new("cpp"),
+            ])?;
             file_args_clang_format.extend(files.iter().map(|p| p.as_os_str()));
         }
         let args = merge_args(&cfg_args_clang_format, &file_args_clang_format);
diff --git a/src/tools/tidy/src/main.rs b/src/tools/tidy/src/main.rs
index 38b3f3f6417a9..40608952c0b70 100644
--- a/src/tools/tidy/src/main.rs
+++ b/src/tools/tidy/src/main.rs
@@ -9,7 +9,7 @@ use std::num::NonZeroUsize;
 use std::path::PathBuf;
 use std::str::FromStr;
 use std::sync::atomic::{AtomicBool, Ordering};
-use std::thread::{self, scope, ScopedJoinHandle};
+use std::thread::{self, ScopedJoinHandle, scope};
 use std::{env, process};
 
 use tidy::*;
diff --git a/src/tools/tidy/src/target_specific_tests.rs b/src/tools/tidy/src/target_specific_tests.rs
index c1032b19f9709..751d678e581cf 100644
--- a/src/tools/tidy/src/target_specific_tests.rs
+++ b/src/tools/tidy/src/target_specific_tests.rs
@@ -4,7 +4,7 @@
 use std::collections::BTreeMap;
 use std::path::Path;
 
-use crate::iter_header::{iter_header, HeaderLine};
+use crate::iter_header::{HeaderLine, iter_header};
 use crate::walk::filter_not_rust;
 
 const LLVM_COMPONENTS_HEADER: &str = "needs-llvm-components:";
diff --git a/src/tools/tidy/src/unknown_revision.rs b/src/tools/tidy/src/unknown_revision.rs
index abfff1d632ad8..0ba05c80a791b 100644
--- a/src/tools/tidy/src/unknown_revision.rs
+++ b/src/tools/tidy/src/unknown_revision.rs
@@ -12,7 +12,7 @@ use std::sync::OnceLock;
 use ignore::DirEntry;
 use regex::Regex;
 
-use crate::iter_header::{iter_header, HeaderLine};
+use crate::iter_header::{HeaderLine, iter_header};
 use crate::walk::{filter_dirs, filter_not_rust, walk};
 
 pub fn check(tests_path: impl AsRef, bad: &mut bool) {
diff --git a/src/tools/unicode-table-generator/src/case_mapping.rs b/src/tools/unicode-table-generator/src/case_mapping.rs
index f28161c782971..00241b7ee0eb5 100644
--- a/src/tools/unicode-table-generator/src/case_mapping.rs
+++ b/src/tools/unicode-table-generator/src/case_mapping.rs
@@ -2,7 +2,7 @@ use std::char;
 use std::collections::BTreeMap;
 use std::fmt::{self, Write};
 
-use crate::{fmt_list, UnicodeData};
+use crate::{UnicodeData, fmt_list};
 
 const INDEX_MASK: u32 = 1 << 22;
 
diff --git a/src/tools/unicode-table-generator/src/main.rs b/src/tools/unicode-table-generator/src/main.rs
index 9f89e7c33f747..e1832091d7029 100644
--- a/src/tools/unicode-table-generator/src/main.rs
+++ b/src/tools/unicode-table-generator/src/main.rs
@@ -82,7 +82,7 @@ mod raw_emitter;
 mod skiplist;
 mod unicode_download;
 
-use raw_emitter::{emit_codepoints, emit_whitespace, RawEmitter};
+use raw_emitter::{RawEmitter, emit_codepoints, emit_whitespace};
 
 static PROPERTIES: &[&str] = &[
     "Alphabetic",
diff --git a/src/tools/unicode-table-generator/src/raw_emitter.rs b/src/tools/unicode-table-generator/src/raw_emitter.rs
index 47120e4f1690a..bfffa1eee600d 100644
--- a/src/tools/unicode-table-generator/src/raw_emitter.rs
+++ b/src/tools/unicode-table-generator/src/raw_emitter.rs
@@ -360,15 +360,12 @@ impl Canonicalized {
         let unique_mapping = unique_mapping
             .into_iter()
             .map(|(key, value)| {
-                (
-                    key,
-                    match value {
-                        UniqueMapping::Canonicalized(idx) => {
-                            u8::try_from(canonical_words.len() + idx).unwrap()
-                        }
-                        UniqueMapping::Canonical(idx) => u8::try_from(idx).unwrap(),
-                    },
-                )
+                (key, match value {
+                    UniqueMapping::Canonicalized(idx) => {
+                        u8::try_from(canonical_words.len() + idx).unwrap()
+                    }
+                    UniqueMapping::Canonical(idx) => u8::try_from(idx).unwrap(),
+                })
             })
             .collect::>();
 
@@ -383,24 +380,21 @@ impl Canonicalized {
         let canonicalized_words = canonicalized_words
             .into_iter()
             .map(|v| {
-                (
-                    u8::try_from(v.0).unwrap(),
-                    match v.1 {
-                        Mapping::RotateAndInvert(amount) => {
-                            assert_eq!(amount, amount & LOWER_6);
-                            1 << 6 | (amount as u8)
-                        }
-                        Mapping::Rotate(amount) => {
-                            assert_eq!(amount, amount & LOWER_6);
-                            amount as u8
-                        }
-                        Mapping::Invert => 1 << 6,
-                        Mapping::ShiftRight(shift_by) => {
-                            assert_eq!(shift_by, shift_by & LOWER_6);
-                            1 << 7 | (shift_by as u8)
-                        }
-                    },
-                )
+                (u8::try_from(v.0).unwrap(), match v.1 {
+                    Mapping::RotateAndInvert(amount) => {
+                        assert_eq!(amount, amount & LOWER_6);
+                        1 << 6 | (amount as u8)
+                    }
+                    Mapping::Rotate(amount) => {
+                        assert_eq!(amount, amount & LOWER_6);
+                        amount as u8
+                    }
+                    Mapping::Invert => 1 << 6,
+                    Mapping::ShiftRight(shift_by) => {
+                        assert_eq!(shift_by, shift_by & LOWER_6);
+                        1 << 7 | (shift_by as u8)
+                    }
+                })
             })
             .collect::>();
         Canonicalized { unique_mapping, canonical_words, canonicalized_words }
diff --git a/src/tools/unstable-book-gen/src/main.rs b/src/tools/unstable-book-gen/src/main.rs
index 9af8802b012c0..6cbdc83d5b5ff 100644
--- a/src/tools/unstable-book-gen/src/main.rs
+++ b/src/tools/unstable-book-gen/src/main.rs
@@ -5,11 +5,11 @@ use std::env;
 use std::fs::{self, write};
 use std::path::Path;
 
-use tidy::features::{collect_lang_features, collect_lib_features, Features};
+use tidy::features::{Features, collect_lang_features, collect_lib_features};
 use tidy::t;
 use tidy::unstable_book::{
-    collect_unstable_book_section_file_names, collect_unstable_feature_names, LANG_FEATURES_DIR,
-    LIB_FEATURES_DIR, PATH_STR,
+    LANG_FEATURES_DIR, LIB_FEATURES_DIR, PATH_STR, collect_unstable_book_section_file_names,
+    collect_unstable_feature_names,
 };
 
 fn generate_stub_issue(path: &Path, name: &str, issue: u32) {
diff --git a/tests/assembly/cmse.rs b/tests/assembly/cmse.rs
index acad77b251357..e0ada8dc2f15c 100644
--- a/tests/assembly/cmse.rs
+++ b/tests/assembly/cmse.rs
@@ -1,6 +1,9 @@
+//@ revisions: hard soft
 //@ assembly-output: emit-asm
-//@ compile-flags: --target thumbv8m.main-none-eabi --crate-type lib -Copt-level=1
-//@ needs-llvm-components: arm
+//@ [hard] compile-flags: --target thumbv8m.main-none-eabihf --crate-type lib -Copt-level=1
+//@ [soft] compile-flags: --target thumbv8m.main-none-eabi --crate-type lib -Copt-level=1
+//@ [hard] needs-llvm-components: arm
+//@ [soft] needs-llvm-components: arm
 #![crate_type = "lib"]
 #![feature(abi_c_cmse_nonsecure_call, cmse_nonsecure_entry, no_core, lang_items)]
 #![no_core]
@@ -9,15 +12,88 @@ pub trait Sized {}
 #[lang = "copy"]
 pub trait Copy {}
 
-// CHECK-LABEL: __acle_se_entry_point
-// CHECK: bxns
+// CHECK-LABEL: __acle_se_entry_point:
+// CHECK-NEXT: entry_point:
+//
+// Write return argument (two registers since 64bit integer)
+// CHECK: movs r0, #0
+// CHECK: movs r1, #0
+//
+// If we are using hard-float:
+// * Check if the float registers were touched (bit 3 in CONTROL)
+// hard: mrs     [[REG:r[0-9]+]], control
+// hard: tst.w   [[REG]], #8
+// hard: beq     [[LABEL:[\.a-zA-Z0-9_]+]]
+//
+// * If touched clear all float registers (d0..=d7)
+// hard: vmov    d0,
+// hard: vmov    d1,
+// hard: vmov    d2,
+// hard: vmov    d3,
+// hard: vmov    d4,
+// hard: vmov    d5,
+// hard: vmov    d6,
+// hard: vmov    d7,
+//
+// * If touched clear FPU status register
+// hard: vmrs    [[REG:r[0-9]+]], fpscr
+// hard: bic     [[REG]], [[REG]], #159
+// hard: bic     [[REG]], [[REG]], #4026531840
+// hard: vmsr    fpscr, [[REG]]
+// hard: [[LABEL]]:
+//
+// Clear all other registers that might have been used
+// CHECK: mov r2,
+// CHECK: mov r3,
+// CHECK: mov r12,
+//
+// Clear the flags
+// CHECK: msr apsr_nzcvq,
+//
+// Branch back to non-secure side
+// CHECK: bxns lr
 #[no_mangle]
 pub extern "C-cmse-nonsecure-entry" fn entry_point() -> i64 {
     0
 }
 
+// NOTE for future codegen changes:
+// The specific register assignment is not important, however:
+// * all registers must be cleared before `blxns` is executed
+//     (either by writing arguments or any other value)
+// * the lowest bit on the address of the callee must be cleared
+// * the flags need to be overwritten
+// * `blxns` needs to be called with the callee address
+//     (with the lowest bit cleared)
+//
 // CHECK-LABEL: call_nonsecure
-// CHECK: blxns
+// Save callee pointer
+// CHECK: mov r12, r0
+//
+// All arguments are written to (writes r0..=r3)
+// CHECK: movs r0, #0
+// CHECK: movs r1, #1
+// CHECK: movs r2, #2
+// CHECK: movs r3, #3
+//
+// Lowest bit gets cleared on callee address
+// CHECK: bic r12, r12, #1
+//
+// Ununsed registers get cleared (r4..=r11)
+// CHECK: mov r4,
+// CHECK: mov r5,
+// CHECK: mov r6,
+// CHECK: mov r7,
+// CHECK: mov r8,
+// CHECK: mov r9,
+// CHECK: mov r10,
+// CHECK: mov r11,
+//
+// Flags get cleared
+// CHECK: msr apsr_nzcvq,
+//
+// Call to non-secure
+// CHECK: blxns r12
 #[no_mangle]
 pub fn call_nonsecure(
     f: unsafe extern "C-cmse-nonsecure-call" fn(u32, u32, u32, u32) -> u64,
diff --git a/tests/assembly/targets/targets-elf.rs b/tests/assembly/targets/targets-elf.rs
index 4e1c5e6806e80..e0f8e9cab7968 100644
--- a/tests/assembly/targets/targets-elf.rs
+++ b/tests/assembly/targets/targets-elf.rs
@@ -9,9 +9,6 @@
 //@ revisions: aarch64_be_unknown_netbsd
 //@ [aarch64_be_unknown_netbsd] compile-flags: --target aarch64_be-unknown-netbsd
 //@ [aarch64_be_unknown_netbsd] needs-llvm-components: aarch64
-//@ revisions: aarch64_fuchsia
-//@ [aarch64_fuchsia] compile-flags: --target aarch64-fuchsia
-//@ [aarch64_fuchsia] needs-llvm-components: aarch64
 //@ revisions: aarch64_kmc_solid_asp3
 //@ [aarch64_kmc_solid_asp3] compile-flags: --target aarch64-kmc-solid_asp3
 //@ [aarch64_kmc_solid_asp3] needs-llvm-components: aarch64
@@ -252,6 +249,9 @@
 //@ revisions: loongarch64_unknown_linux_musl
 //@ [loongarch64_unknown_linux_musl] compile-flags: --target loongarch64-unknown-linux-musl
 //@ [loongarch64_unknown_linux_musl] needs-llvm-components: loongarch
+//@ revisions: loongarch64_unknown_linux_ohos
+//@ [loongarch64_unknown_linux_ohos] compile-flags: --target loongarch64-unknown-linux-ohos
+//@ [loongarch64_unknown_linux_ohos] needs-llvm-components: loongarch
 //@ revisions: loongarch64_unknown_none
 //@ [loongarch64_unknown_none] compile-flags: --target loongarch64-unknown-none
 //@ [loongarch64_unknown_none] needs-llvm-components: loongarch
@@ -525,9 +525,6 @@
 //@ revisions: x86_64_fortanix_unknown_sgx
 //@ [x86_64_fortanix_unknown_sgx] compile-flags: --target x86_64-fortanix-unknown-sgx
 //@ [x86_64_fortanix_unknown_sgx] needs-llvm-components: x86
-//@ revisions: x86_64_fuchsia
-//@ [x86_64_fuchsia] compile-flags: --target x86_64-fuchsia
-//@ [x86_64_fuchsia] needs-llvm-components: x86
 //@ revisions: x86_64_linux_android
 //@ [x86_64_linux_android] compile-flags: --target x86_64-linux-android
 //@ [x86_64_linux_android] needs-llvm-components: x86
diff --git a/tests/codegen/issues/issue-111508-vec-tryinto-array.rs b/tests/codegen/issues/issue-111508-vec-tryinto-array.rs
deleted file mode 100644
index 6415724b40ad5..0000000000000
--- a/tests/codegen/issues/issue-111508-vec-tryinto-array.rs
+++ /dev/null
@@ -1,22 +0,0 @@
-//@ compile-flags: -O
-// This regress since Rust version 1.72.
-//@ min-llvm-version: 18.1.4
-
-#![crate_type = "lib"]
-
-use std::convert::TryInto;
-
-const N: usize = 24;
-
-// CHECK-LABEL: @example
-// CHECK-NOT: unwrap_failed
-#[no_mangle]
-pub fn example(a: Vec) -> u8 {
-    if a.len() != 32 {
-        return 0;
-    }
-
-    let a: [u8; 32] = a.try_into().unwrap();
-
-    a[15] + a[N]
-}
diff --git a/tests/crashes/130310.rs b/tests/crashes/130310.rs
new file mode 100644
index 0000000000000..d59dd39983c78
--- /dev/null
+++ b/tests/crashes/130310.rs
@@ -0,0 +1,15 @@
+//@ known-bug: rust-lang/rust#130310
+
+use std::marker::PhantomData;
+
+#[repr(C)]
+struct A {
+    a: *const A>,
+    p: PhantomData,
+}
+
+extern "C" {
+    fn f(a: *const A<()>);
+}
+
+fn main() {}
diff --git a/tests/mir-opt/address_of.address_of_reborrow.SimplifyCfg-initial.after.mir b/tests/mir-opt/address_of.address_of_reborrow.SimplifyCfg-initial.after.mir
index be636da4517ca..ae445ad9b915b 100644
--- a/tests/mir-opt/address_of.address_of_reborrow.SimplifyCfg-initial.after.mir
+++ b/tests/mir-opt/address_of.address_of_reborrow.SimplifyCfg-initial.after.mir
@@ -1,8 +1,8 @@
 // MIR for `address_of_reborrow` after SimplifyCfg-initial
 
 | User Type Annotations
-| 0: user_ty: Canonical { value: Ty(*const ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:8:5: 8:18, inferred_ty: *const [i32; 10]
-| 1: user_ty: Canonical { value: Ty(*const dyn std::marker::Send), max_universe: U0, variables: [CanonicalVarInfo { kind: Region(U0) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:10:5: 10:25, inferred_ty: *const dyn std::marker::Send
+| 0: user_ty: Canonical { value: Ty(*const ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:8:10: 8:18, inferred_ty: *const [i32; 10]
+| 1: user_ty: Canonical { value: Ty(*const dyn std::marker::Send), max_universe: U0, variables: [CanonicalVarInfo { kind: Region(U0) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:10:10: 10:25, inferred_ty: *const dyn std::marker::Send
 | 2: user_ty: Canonical { value: Ty(*const ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:14:12: 14:20, inferred_ty: *const [i32; 10]
 | 3: user_ty: Canonical { value: Ty(*const ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:14:12: 14:20, inferred_ty: *const [i32; 10]
 | 4: user_ty: Canonical { value: Ty(*const [i32; 10]), max_universe: U0, variables: [], defining_opaque_types: [] }, span: $DIR/address_of.rs:15:12: 15:28, inferred_ty: *const [i32; 10]
@@ -11,8 +11,8 @@
 | 7: user_ty: Canonical { value: Ty(*const dyn std::marker::Send), max_universe: U0, variables: [CanonicalVarInfo { kind: Region(U0) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:16:12: 16:27, inferred_ty: *const dyn std::marker::Send
 | 8: user_ty: Canonical { value: Ty(*const [i32]), max_universe: U0, variables: [], defining_opaque_types: [] }, span: $DIR/address_of.rs:17:12: 17:24, inferred_ty: *const [i32]
 | 9: user_ty: Canonical { value: Ty(*const [i32]), max_universe: U0, variables: [], defining_opaque_types: [] }, span: $DIR/address_of.rs:17:12: 17:24, inferred_ty: *const [i32]
-| 10: user_ty: Canonical { value: Ty(*const ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:19:5: 19:18, inferred_ty: *const [i32; 10]
-| 11: user_ty: Canonical { value: Ty(*const dyn std::marker::Send), max_universe: U0, variables: [CanonicalVarInfo { kind: Region(U0) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:21:5: 21:25, inferred_ty: *const dyn std::marker::Send
+| 10: user_ty: Canonical { value: Ty(*const ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:19:10: 19:18, inferred_ty: *const [i32; 10]
+| 11: user_ty: Canonical { value: Ty(*const dyn std::marker::Send), max_universe: U0, variables: [CanonicalVarInfo { kind: Region(U0) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:21:10: 21:25, inferred_ty: *const dyn std::marker::Send
 | 12: user_ty: Canonical { value: Ty(*const ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:24:12: 24:20, inferred_ty: *const [i32; 10]
 | 13: user_ty: Canonical { value: Ty(*const ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:24:12: 24:20, inferred_ty: *const [i32; 10]
 | 14: user_ty: Canonical { value: Ty(*const [i32; 10]), max_universe: U0, variables: [], defining_opaque_types: [] }, span: $DIR/address_of.rs:25:12: 25:28, inferred_ty: *const [i32; 10]
@@ -21,8 +21,8 @@
 | 17: user_ty: Canonical { value: Ty(*const dyn std::marker::Send), max_universe: U0, variables: [CanonicalVarInfo { kind: Region(U0) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:26:12: 26:27, inferred_ty: *const dyn std::marker::Send
 | 18: user_ty: Canonical { value: Ty(*const [i32]), max_universe: U0, variables: [], defining_opaque_types: [] }, span: $DIR/address_of.rs:27:12: 27:24, inferred_ty: *const [i32]
 | 19: user_ty: Canonical { value: Ty(*const [i32]), max_universe: U0, variables: [], defining_opaque_types: [] }, span: $DIR/address_of.rs:27:12: 27:24, inferred_ty: *const [i32]
-| 20: user_ty: Canonical { value: Ty(*mut ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:29:5: 29:16, inferred_ty: *mut [i32; 10]
-| 21: user_ty: Canonical { value: Ty(*mut dyn std::marker::Send), max_universe: U0, variables: [CanonicalVarInfo { kind: Region(U0) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:31:5: 31:23, inferred_ty: *mut dyn std::marker::Send
+| 20: user_ty: Canonical { value: Ty(*mut ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:29:10: 29:16, inferred_ty: *mut [i32; 10]
+| 21: user_ty: Canonical { value: Ty(*mut dyn std::marker::Send), max_universe: U0, variables: [CanonicalVarInfo { kind: Region(U0) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:31:10: 31:23, inferred_ty: *mut dyn std::marker::Send
 | 22: user_ty: Canonical { value: Ty(*mut ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:34:12: 34:18, inferred_ty: *mut [i32; 10]
 | 23: user_ty: Canonical { value: Ty(*mut ^0), max_universe: U0, variables: [CanonicalVarInfo { kind: Ty(General(U0)) }], defining_opaque_types: [] }, span: $DIR/address_of.rs:34:12: 34:18, inferred_ty: *mut [i32; 10]
 | 24: user_ty: Canonical { value: Ty(*mut [i32; 10]), max_universe: U0, variables: [], defining_opaque_types: [] }, span: $DIR/address_of.rs:35:12: 35:26, inferred_ty: *mut [i32; 10]
@@ -150,7 +150,7 @@ fn address_of_reborrow() -> () {
         StorageLive(_9);
         StorageLive(_10);
         _10 = &raw const (*_1);
-        _9 = move _10 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+        _9 = move _10 as *const dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
         StorageDead(_10);
         AscribeUserType(_9, o, UserTypeProjection { base: UserType(1), projs: [] });
         _8 = copy _9;
@@ -159,13 +159,13 @@ fn address_of_reborrow() -> () {
         StorageLive(_11);
         StorageLive(_12);
         _12 = &raw const (*_1);
-        _11 = move _12 as *const [i32] (PointerCoercion(Unsize));
+        _11 = move _12 as *const [i32] (PointerCoercion(Unsize, AsCast));
         StorageDead(_12);
         StorageDead(_11);
         StorageLive(_13);
         StorageLive(_14);
         _14 = &raw const (*_1);
-        _13 = move _14 as *const i32 (PointerCoercion(ArrayToPointer));
+        _13 = move _14 as *const i32 (PointerCoercion(ArrayToPointer, AsCast));
         StorageDead(_14);
         StorageDead(_13);
         StorageLive(_15);
@@ -179,14 +179,14 @@ fn address_of_reborrow() -> () {
         StorageLive(_17);
         StorageLive(_18);
         _18 = &raw const (*_1);
-        _17 = move _18 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+        _17 = move _18 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
         StorageDead(_18);
         FakeRead(ForLet(None), _17);
         AscribeUserType(_17, o, UserTypeProjection { base: UserType(7), projs: [] });
         StorageLive(_19);
         StorageLive(_20);
         _20 = &raw const (*_1);
-        _19 = move _20 as *const [i32] (PointerCoercion(Unsize));
+        _19 = move _20 as *const [i32] (PointerCoercion(Unsize, Implicit));
         StorageDead(_20);
         FakeRead(ForLet(None), _19);
         AscribeUserType(_19, o, UserTypeProjection { base: UserType(9), projs: [] });
@@ -204,7 +204,7 @@ fn address_of_reborrow() -> () {
         StorageLive(_25);
         StorageLive(_26);
         _26 = &raw const (*_3);
-        _25 = move _26 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+        _25 = move _26 as *const dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
         StorageDead(_26);
         AscribeUserType(_25, o, UserTypeProjection { base: UserType(11), projs: [] });
         _24 = copy _25;
@@ -213,7 +213,7 @@ fn address_of_reborrow() -> () {
         StorageLive(_27);
         StorageLive(_28);
         _28 = &raw const (*_3);
-        _27 = move _28 as *const [i32] (PointerCoercion(Unsize));
+        _27 = move _28 as *const [i32] (PointerCoercion(Unsize, AsCast));
         StorageDead(_28);
         StorageDead(_27);
         StorageLive(_29);
@@ -227,14 +227,14 @@ fn address_of_reborrow() -> () {
         StorageLive(_31);
         StorageLive(_32);
         _32 = &raw const (*_3);
-        _31 = move _32 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+        _31 = move _32 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
         StorageDead(_32);
         FakeRead(ForLet(None), _31);
         AscribeUserType(_31, o, UserTypeProjection { base: UserType(17), projs: [] });
         StorageLive(_33);
         StorageLive(_34);
         _34 = &raw const (*_3);
-        _33 = move _34 as *const [i32] (PointerCoercion(Unsize));
+        _33 = move _34 as *const [i32] (PointerCoercion(Unsize, Implicit));
         StorageDead(_34);
         FakeRead(ForLet(None), _33);
         AscribeUserType(_33, o, UserTypeProjection { base: UserType(19), projs: [] });
@@ -252,7 +252,7 @@ fn address_of_reborrow() -> () {
         StorageLive(_39);
         StorageLive(_40);
         _40 = &raw mut (*_3);
-        _39 = move _40 as *mut dyn std::marker::Send (PointerCoercion(Unsize));
+        _39 = move _40 as *mut dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
         StorageDead(_40);
         AscribeUserType(_39, o, UserTypeProjection { base: UserType(21), projs: [] });
         _38 = copy _39;
@@ -261,7 +261,7 @@ fn address_of_reborrow() -> () {
         StorageLive(_41);
         StorageLive(_42);
         _42 = &raw mut (*_3);
-        _41 = move _42 as *mut [i32] (PointerCoercion(Unsize));
+        _41 = move _42 as *mut [i32] (PointerCoercion(Unsize, AsCast));
         StorageDead(_42);
         StorageDead(_41);
         StorageLive(_43);
@@ -275,14 +275,14 @@ fn address_of_reborrow() -> () {
         StorageLive(_45);
         StorageLive(_46);
         _46 = &raw mut (*_3);
-        _45 = move _46 as *mut dyn std::marker::Send (PointerCoercion(Unsize));
+        _45 = move _46 as *mut dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
         StorageDead(_46);
         FakeRead(ForLet(None), _45);
         AscribeUserType(_45, o, UserTypeProjection { base: UserType(27), projs: [] });
         StorageLive(_47);
         StorageLive(_48);
         _48 = &raw mut (*_3);
-        _47 = move _48 as *mut [i32] (PointerCoercion(Unsize));
+        _47 = move _48 as *mut [i32] (PointerCoercion(Unsize, Implicit));
         StorageDead(_48);
         FakeRead(ForLet(None), _47);
         AscribeUserType(_47, o, UserTypeProjection { base: UserType(29), projs: [] });
diff --git a/tests/mir-opt/build_correct_coerce.main.built.after.mir b/tests/mir-opt/build_correct_coerce.main.built.after.mir
index 061174d69bb05..583a5ecd22702 100644
--- a/tests/mir-opt/build_correct_coerce.main.built.after.mir
+++ b/tests/mir-opt/build_correct_coerce.main.built.after.mir
@@ -9,7 +9,7 @@ fn main() -> () {
 
     bb0: {
         StorageLive(_1);
-        _1 = foo as for<'a> fn(&'a (), &'a ()) (PointerCoercion(ReifyFnPointer));
+        _1 = foo as for<'a> fn(&'a (), &'a ()) (PointerCoercion(ReifyFnPointer, AsCast));
         FakeRead(ForLet(None), _1);
         _0 = const ();
         StorageDead(_1);
diff --git a/tests/mir-opt/building/receiver_ptr_mutability.main.built.after.mir b/tests/mir-opt/building/receiver_ptr_mutability.main.built.after.mir
index 296d71a319d1b..be972b62cbd31 100644
--- a/tests/mir-opt/building/receiver_ptr_mutability.main.built.after.mir
+++ b/tests/mir-opt/building/receiver_ptr_mutability.main.built.after.mir
@@ -39,7 +39,7 @@ fn main() -> () {
         StorageLive(_3);
         StorageLive(_4);
         _4 = copy _1;
-        _3 = move _4 as *const Test (PointerCoercion(MutToConstPointer));
+        _3 = move _4 as *const Test (PointerCoercion(MutToConstPointer, Implicit));
         StorageDead(_4);
         _2 = Test::x(move _3) -> [return: bb2, unwind: bb4];
     }
@@ -64,7 +64,7 @@ fn main() -> () {
         StorageLive(_11);
         StorageLive(_12);
         _12 = copy (*(*(*(*_5))));
-        _11 = move _12 as *const Test (PointerCoercion(MutToConstPointer));
+        _11 = move _12 as *const Test (PointerCoercion(MutToConstPointer, Implicit));
         StorageDead(_12);
         _10 = Test::x(move _11) -> [return: bb3, unwind: bb4];
     }
diff --git a/tests/mir-opt/building/storage_live_dead_in_statics.XXX.built.after.mir b/tests/mir-opt/building/storage_live_dead_in_statics.XXX.built.after.mir
index 683f63065f76b..73ead005f8c62 100644
--- a/tests/mir-opt/building/storage_live_dead_in_statics.XXX.built.after.mir
+++ b/tests/mir-opt/building/storage_live_dead_in_statics.XXX.built.after.mir
@@ -187,7 +187,7 @@ static XXX: &Foo = {
         StorageDead(_7);
         _5 = &_6;
         _4 = &(*_5);
-        _3 = move _4 as &[(u32, u32)] (PointerCoercion(Unsize));
+        _3 = move _4 as &[(u32, u32)] (PointerCoercion(Unsize, Implicit));
         StorageDead(_4);
         _2 = Foo { tup: const "hi", data: move _3 };
         StorageDead(_3);
diff --git a/tests/mir-opt/const_promotion_extern_static.BAR.PromoteTemps.diff b/tests/mir-opt/const_promotion_extern_static.BAR.PromoteTemps.diff
index f412048b6ec7e..487f68a8d4dfe 100644
--- a/tests/mir-opt/const_promotion_extern_static.BAR.PromoteTemps.diff
+++ b/tests/mir-opt/const_promotion_extern_static.BAR.PromoteTemps.diff
@@ -22,7 +22,7 @@
 -         _2 = &_3;
 +         _6 = const BAR::promoted[0];
 +         _2 = &(*_6);
-          _1 = move _2 as &[&i32] (PointerCoercion(Unsize));
+          _1 = move _2 as &[&i32] (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_4);
           StorageDead(_2);
           _0 = core::slice::::as_ptr(move _1) -> [return: bb1, unwind: bb2];
diff --git a/tests/mir-opt/const_promotion_extern_static.FOO.PromoteTemps.diff b/tests/mir-opt/const_promotion_extern_static.FOO.PromoteTemps.diff
index bfefd2b8c95c6..0e4eed2c028d0 100644
--- a/tests/mir-opt/const_promotion_extern_static.FOO.PromoteTemps.diff
+++ b/tests/mir-opt/const_promotion_extern_static.FOO.PromoteTemps.diff
@@ -22,7 +22,7 @@
 -         _2 = &_3;
 +         _6 = const FOO::promoted[0];
 +         _2 = &(*_6);
-          _1 = move _2 as &[&i32] (PointerCoercion(Unsize));
+          _1 = move _2 as &[&i32] (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_4);
           StorageDead(_2);
           _0 = core::slice::::as_ptr(move _1) -> [return: bb1, unwind: bb2];
diff --git a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.32bit.panic-abort.diff b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.32bit.panic-abort.diff
index 52aa4da49efaf..15d3014036713 100644
--- a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.32bit.panic-abort.diff
+++ b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.32bit.panic-abort.diff
@@ -26,7 +26,7 @@
           _9 = const main::promoted[0];
           _3 = &(*_9);
           _2 = &raw const (*_3);
-          _1 = move _2 as *const [i32] (PointerCoercion(Unsize));
+          _1 = move _2 as *const [i32] (PointerCoercion(Unsize, Implicit));
           StorageDead(_2);
           StorageDead(_3);
           StorageLive(_5);
diff --git a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.32bit.panic-unwind.diff b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.32bit.panic-unwind.diff
index 242ff0e664f1d..dd411d84f9fbe 100644
--- a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.32bit.panic-unwind.diff
+++ b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.32bit.panic-unwind.diff
@@ -26,7 +26,7 @@
           _9 = const main::promoted[0];
           _3 = &(*_9);
           _2 = &raw const (*_3);
-          _1 = move _2 as *const [i32] (PointerCoercion(Unsize));
+          _1 = move _2 as *const [i32] (PointerCoercion(Unsize, Implicit));
           StorageDead(_2);
           StorageDead(_3);
           StorageLive(_5);
diff --git a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.64bit.panic-abort.diff b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.64bit.panic-abort.diff
index 52aa4da49efaf..15d3014036713 100644
--- a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.64bit.panic-abort.diff
+++ b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.64bit.panic-abort.diff
@@ -26,7 +26,7 @@
           _9 = const main::promoted[0];
           _3 = &(*_9);
           _2 = &raw const (*_3);
-          _1 = move _2 as *const [i32] (PointerCoercion(Unsize));
+          _1 = move _2 as *const [i32] (PointerCoercion(Unsize, Implicit));
           StorageDead(_2);
           StorageDead(_3);
           StorageLive(_5);
diff --git a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.64bit.panic-unwind.diff b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.64bit.panic-unwind.diff
index 242ff0e664f1d..dd411d84f9fbe 100644
--- a/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.64bit.panic-unwind.diff
+++ b/tests/mir-opt/const_prop/bad_op_unsafe_oob_for_slices.main.GVN.64bit.panic-unwind.diff
@@ -26,7 +26,7 @@
           _9 = const main::promoted[0];
           _3 = &(*_9);
           _2 = &raw const (*_3);
-          _1 = move _2 as *const [i32] (PointerCoercion(Unsize));
+          _1 = move _2 as *const [i32] (PointerCoercion(Unsize, Implicit));
           StorageDead(_2);
           StorageDead(_3);
           StorageLive(_5);
diff --git a/tests/mir-opt/const_prop/reify_fn_ptr.main.GVN.diff b/tests/mir-opt/const_prop/reify_fn_ptr.main.GVN.diff
index e5786bcf701ef..50a17326c2aae 100644
--- a/tests/mir-opt/const_prop/reify_fn_ptr.main.GVN.diff
+++ b/tests/mir-opt/const_prop/reify_fn_ptr.main.GVN.diff
@@ -13,7 +13,7 @@
           StorageLive(_1);
           StorageLive(_2);
           StorageLive(_3);
-          _3 = main as fn() (PointerCoercion(ReifyFnPointer));
+          _3 = main as fn() (PointerCoercion(ReifyFnPointer, AsCast));
           _2 = move _3 as usize (PointerExposeProvenance);
           StorageDead(_3);
           _1 = move _2 as *const fn() (PointerWithExposedProvenance);
diff --git a/tests/mir-opt/const_prop/reify_fn_ptr.rs b/tests/mir-opt/const_prop/reify_fn_ptr.rs
index ffce4e97f5de1..d56f21e586aa8 100644
--- a/tests/mir-opt/const_prop/reify_fn_ptr.rs
+++ b/tests/mir-opt/const_prop/reify_fn_ptr.rs
@@ -3,7 +3,7 @@
 
 fn main() {
     // CHECK-LABEL: fn main(
-    // CHECK: [[ptr:_.*]] = main as fn() (PointerCoercion(ReifyFnPointer));
+    // CHECK: [[ptr:_.*]] = main as fn() (PointerCoercion(ReifyFnPointer, AsCast));
     // CHECK: [[addr:_.*]] = move [[ptr]] as usize (PointerExposeProvenance);
     // CHECK: [[back:_.*]] = move [[addr]] as *const fn() (PointerWithExposedProvenance);
     let _ = main as usize as *const fn();
diff --git a/tests/mir-opt/const_prop/slice_len.main.GVN.32bit.panic-abort.diff b/tests/mir-opt/const_prop/slice_len.main.GVN.32bit.panic-abort.diff
index e834a5802c33f..41ce94eda7517 100644
--- a/tests/mir-opt/const_prop/slice_len.main.GVN.32bit.panic-abort.diff
+++ b/tests/mir-opt/const_prop/slice_len.main.GVN.32bit.panic-abort.diff
@@ -24,9 +24,9 @@
           _9 = const main::promoted[0];
           _4 = copy _9;
 -         _3 = copy _4;
--         _2 = move _3 as &[u32] (PointerCoercion(Unsize));
+-         _2 = move _3 as &[u32] (PointerCoercion(Unsize, AsCast));
 +         _3 = copy _9;
-+         _2 = copy _9 as &[u32] (PointerCoercion(Unsize));
++         _2 = copy _9 as &[u32] (PointerCoercion(Unsize, AsCast));
           StorageDead(_3);
           StorageLive(_6);
           _6 = const 1_usize;
diff --git a/tests/mir-opt/const_prop/slice_len.main.GVN.32bit.panic-unwind.diff b/tests/mir-opt/const_prop/slice_len.main.GVN.32bit.panic-unwind.diff
index 55ffc50180569..8cced96cd4331 100644
--- a/tests/mir-opt/const_prop/slice_len.main.GVN.32bit.panic-unwind.diff
+++ b/tests/mir-opt/const_prop/slice_len.main.GVN.32bit.panic-unwind.diff
@@ -24,9 +24,9 @@
           _9 = const main::promoted[0];
           _4 = copy _9;
 -         _3 = copy _4;
--         _2 = move _3 as &[u32] (PointerCoercion(Unsize));
+-         _2 = move _3 as &[u32] (PointerCoercion(Unsize, AsCast));
 +         _3 = copy _9;
-+         _2 = copy _9 as &[u32] (PointerCoercion(Unsize));
++         _2 = copy _9 as &[u32] (PointerCoercion(Unsize, AsCast));
           StorageDead(_3);
           StorageLive(_6);
           _6 = const 1_usize;
diff --git a/tests/mir-opt/const_prop/slice_len.main.GVN.64bit.panic-abort.diff b/tests/mir-opt/const_prop/slice_len.main.GVN.64bit.panic-abort.diff
index e834a5802c33f..41ce94eda7517 100644
--- a/tests/mir-opt/const_prop/slice_len.main.GVN.64bit.panic-abort.diff
+++ b/tests/mir-opt/const_prop/slice_len.main.GVN.64bit.panic-abort.diff
@@ -24,9 +24,9 @@
           _9 = const main::promoted[0];
           _4 = copy _9;
 -         _3 = copy _4;
--         _2 = move _3 as &[u32] (PointerCoercion(Unsize));
+-         _2 = move _3 as &[u32] (PointerCoercion(Unsize, AsCast));
 +         _3 = copy _9;
-+         _2 = copy _9 as &[u32] (PointerCoercion(Unsize));
++         _2 = copy _9 as &[u32] (PointerCoercion(Unsize, AsCast));
           StorageDead(_3);
           StorageLive(_6);
           _6 = const 1_usize;
diff --git a/tests/mir-opt/const_prop/slice_len.main.GVN.64bit.panic-unwind.diff b/tests/mir-opt/const_prop/slice_len.main.GVN.64bit.panic-unwind.diff
index 55ffc50180569..8cced96cd4331 100644
--- a/tests/mir-opt/const_prop/slice_len.main.GVN.64bit.panic-unwind.diff
+++ b/tests/mir-opt/const_prop/slice_len.main.GVN.64bit.panic-unwind.diff
@@ -24,9 +24,9 @@
           _9 = const main::promoted[0];
           _4 = copy _9;
 -         _3 = copy _4;
--         _2 = move _3 as &[u32] (PointerCoercion(Unsize));
+-         _2 = move _3 as &[u32] (PointerCoercion(Unsize, AsCast));
 +         _3 = copy _9;
-+         _2 = copy _9 as &[u32] (PointerCoercion(Unsize));
++         _2 = copy _9 as &[u32] (PointerCoercion(Unsize, AsCast));
           StorageDead(_3);
           StorageLive(_6);
           _6 = const 1_usize;
diff --git a/tests/mir-opt/const_prop/slice_len.rs b/tests/mir-opt/const_prop/slice_len.rs
index 46604cfe1e091..ebd3c9e792dca 100644
--- a/tests/mir-opt/const_prop/slice_len.rs
+++ b/tests/mir-opt/const_prop/slice_len.rs
@@ -7,7 +7,7 @@
 fn main() {
     // CHECK-LABEL: fn main(
     // CHECK: debug a => [[a:_.*]];
-    // CHECK: [[slice:_.*]] = copy {{.*}} as &[u32] (PointerCoercion(Unsize));
+    // CHECK: [[slice:_.*]] = copy {{.*}} as &[u32] (PointerCoercion(Unsize, AsCast));
     // CHECK: assert(const true,
     // CHECK: [[a]] = const 2_u32;
     let a = (&[1u32, 2, 3] as &[u32])[1];
diff --git a/tests/mir-opt/copy-prop/issue_107511.main.CopyProp.panic-abort.diff b/tests/mir-opt/copy-prop/issue_107511.main.CopyProp.panic-abort.diff
index f4411886f9a7a..6d967257df1f5 100644
--- a/tests/mir-opt/copy-prop/issue_107511.main.CopyProp.panic-abort.diff
+++ b/tests/mir-opt/copy-prop/issue_107511.main.CopyProp.panic-abort.diff
@@ -47,7 +47,7 @@
           StorageLive(_6);
           StorageLive(_7);
           _7 = &_2;
-          _6 = move _7 as &[i32] (PointerCoercion(Unsize));
+          _6 = move _7 as &[i32] (PointerCoercion(Unsize, Implicit));
           StorageDead(_7);
           _5 = core::slice::::len(move _6) -> [return: bb1, unwind unreachable];
       }
diff --git a/tests/mir-opt/copy-prop/issue_107511.main.CopyProp.panic-unwind.diff b/tests/mir-opt/copy-prop/issue_107511.main.CopyProp.panic-unwind.diff
index 833588aa4e920..3580c87c46995 100644
--- a/tests/mir-opt/copy-prop/issue_107511.main.CopyProp.panic-unwind.diff
+++ b/tests/mir-opt/copy-prop/issue_107511.main.CopyProp.panic-unwind.diff
@@ -47,7 +47,7 @@
           StorageLive(_6);
           StorageLive(_7);
           _7 = &_2;
-          _6 = move _7 as &[i32] (PointerCoercion(Unsize));
+          _6 = move _7 as &[i32] (PointerCoercion(Unsize, Implicit));
           StorageDead(_7);
           _5 = core::slice::::len(move _6) -> [return: bb1, unwind continue];
       }
diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-abort.diff
index c7870a7902b98..e62fcb66e3a6d 100644
--- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-abort.diff
+++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-abort.diff
@@ -89,7 +89,7 @@
 -         _4 = Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> };
 +         _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }};
           StorageDead(_5);
--         _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize));
+-         _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize, Implicit));
 +         _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }};
           StorageDead(_4);
 -         _2 = Box::<[bool]>(copy _3, const std::alloc::Global);
diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-unwind.diff
index f5de7a361bc10..8183abd315ae5 100644
--- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-unwind.diff
+++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.32bit.panic-unwind.diff
@@ -93,7 +93,7 @@
 -         _4 = Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> };
 +         _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }};
           StorageDead(_5);
--         _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize));
+-         _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize, Implicit));
 +         _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }};
           StorageDead(_4);
 -         _2 = Box::<[bool]>(copy _3, const std::alloc::Global);
diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-abort.diff
index 3b0bc6377da62..4fa6ef29e0697 100644
--- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-abort.diff
+++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-abort.diff
@@ -89,7 +89,7 @@
 -         _4 = Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> };
 +         _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }};
           StorageDead(_5);
--         _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize));
+-         _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize, Implicit));
 +         _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }};
           StorageDead(_4);
 -         _2 = Box::<[bool]>(copy _3, const std::alloc::Global);
diff --git a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-unwind.diff
index 5dd7ad9a11773..753292045632f 100644
--- a/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-unwind.diff
+++ b/tests/mir-opt/dataflow-const-prop/default_boxed_slice.main.GVN.64bit.panic-unwind.diff
@@ -93,7 +93,7 @@
 -         _4 = Unique::<[bool; 0]> { pointer: move _5, _marker: const PhantomData::<[bool; 0]> };
 +         _4 = const Unique::<[bool; 0]> {{ pointer: NonNull::<[bool; 0]> {{ pointer: {0x1 as *const [bool; 0]} }}, _marker: PhantomData::<[bool; 0]> }};
           StorageDead(_5);
--         _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize));
+-         _3 = move _4 as std::ptr::Unique<[bool]> (PointerCoercion(Unsize, Implicit));
 +         _3 = const Unique::<[bool]> {{ pointer: NonNull::<[bool]> {{ pointer: Indirect { alloc_id: ALLOC0, offset: Size(0 bytes) }: *const [bool] }}, _marker: PhantomData::<[bool]> }};
           StorageDead(_4);
 -         _2 = Box::<[bool]>(copy _3, const std::alloc::Global);
diff --git a/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.32bit.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.32bit.panic-abort.diff
index 40632db667a8d..e71992316dcf4 100644
--- a/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.32bit.panic-abort.diff
+++ b/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.32bit.panic-abort.diff
@@ -32,7 +32,7 @@
           _14 = const main::promoted[0];
           _4 = copy _14;
           _3 = copy _4;
-          _2 = move _3 as &[u32] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u32] (PointerCoercion(Unsize, AsCast));
           StorageDead(_3);
           StorageLive(_6);
           _6 = const 1_usize;
diff --git a/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.32bit.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.32bit.panic-unwind.diff
index 596b4ac9b1e5b..26de859576896 100644
--- a/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.32bit.panic-unwind.diff
+++ b/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.32bit.panic-unwind.diff
@@ -32,7 +32,7 @@
           _14 = const main::promoted[0];
           _4 = copy _14;
           _3 = copy _4;
-          _2 = move _3 as &[u32] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u32] (PointerCoercion(Unsize, AsCast));
           StorageDead(_3);
           StorageLive(_6);
           _6 = const 1_usize;
diff --git a/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.64bit.panic-abort.diff b/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.64bit.panic-abort.diff
index 40632db667a8d..e71992316dcf4 100644
--- a/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.64bit.panic-abort.diff
+++ b/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.64bit.panic-abort.diff
@@ -32,7 +32,7 @@
           _14 = const main::promoted[0];
           _4 = copy _14;
           _3 = copy _4;
-          _2 = move _3 as &[u32] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u32] (PointerCoercion(Unsize, AsCast));
           StorageDead(_3);
           StorageLive(_6);
           _6 = const 1_usize;
diff --git a/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.64bit.panic-unwind.diff b/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.64bit.panic-unwind.diff
index 596b4ac9b1e5b..26de859576896 100644
--- a/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.64bit.panic-unwind.diff
+++ b/tests/mir-opt/dataflow-const-prop/slice_len.main.DataflowConstProp.64bit.panic-unwind.diff
@@ -32,7 +32,7 @@
           _14 = const main::promoted[0];
           _4 = copy _14;
           _3 = copy _4;
-          _2 = move _3 as &[u32] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u32] (PointerCoercion(Unsize, AsCast));
           StorageDead(_3);
           StorageLive(_6);
           _6 = const 1_usize;
diff --git a/tests/mir-opt/gvn.array_len.GVN.panic-abort.diff b/tests/mir-opt/gvn.array_len.GVN.panic-abort.diff
index 90654e0566284..0d0477fe7729f 100644
--- a/tests/mir-opt/gvn.array_len.GVN.panic-abort.diff
+++ b/tests/mir-opt/gvn.array_len.GVN.panic-abort.diff
@@ -16,7 +16,7 @@
 +         nop;
           StorageLive(_3);
           _3 = &(*_1);
-          _2 = move _3 as &[i32] (PointerCoercion(Unsize));
+          _2 = move _3 as &[i32] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
           StorageLive(_4);
           _4 = &raw const (*_2);
diff --git a/tests/mir-opt/gvn.array_len.GVN.panic-unwind.diff b/tests/mir-opt/gvn.array_len.GVN.panic-unwind.diff
index 90654e0566284..0d0477fe7729f 100644
--- a/tests/mir-opt/gvn.array_len.GVN.panic-unwind.diff
+++ b/tests/mir-opt/gvn.array_len.GVN.panic-unwind.diff
@@ -16,7 +16,7 @@
 +         nop;
           StorageLive(_3);
           _3 = &(*_1);
-          _2 = move _3 as &[i32] (PointerCoercion(Unsize));
+          _2 = move _3 as &[i32] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
           StorageLive(_4);
           _4 = &raw const (*_2);
diff --git a/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff b/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff
index 292b812b50c85..130b011630cc2 100644
--- a/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff
+++ b/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff
@@ -37,7 +37,7 @@
       bb0: {
 -         StorageLive(_1);
 +         nop;
-          _1 = identity:: as fn(u8) -> u8 (PointerCoercion(ReifyFnPointer));
+          _1 = identity:: as fn(u8) -> u8 (PointerCoercion(ReifyFnPointer, AsCast));
           StorageLive(_2);
           StorageLive(_3);
           _3 = copy _1;
@@ -50,7 +50,7 @@
           StorageDead(_2);
 -         StorageLive(_4);
 +         nop;
-          _4 = identity:: as fn(u8) -> u8 (PointerCoercion(ReifyFnPointer));
+          _4 = identity:: as fn(u8) -> u8 (PointerCoercion(ReifyFnPointer, AsCast));
           StorageLive(_5);
           StorageLive(_6);
           _6 = copy _4;
@@ -69,9 +69,9 @@
 +         nop;
           StorageLive(_9);
 -         _9 = copy _7;
--         _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Safe)));
+-         _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast));
 +         _9 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21};
-+         _8 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21} as fn() (PointerCoercion(ClosureFnPointer(Safe)));
++         _8 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast));
           StorageDead(_9);
           StorageLive(_10);
           StorageLive(_11);
@@ -87,9 +87,9 @@
 +         nop;
           StorageLive(_13);
 -         _13 = copy _7;
--         _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Safe)));
+-         _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast));
 +         _13 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21};
-+         _12 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21} as fn() (PointerCoercion(ClosureFnPointer(Safe)));
++         _12 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast));
           StorageDead(_13);
           StorageLive(_14);
           StorageLive(_15);
diff --git a/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff b/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff
index a60d986132e56..372a08d547306 100644
--- a/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff
+++ b/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff
@@ -37,7 +37,7 @@
       bb0: {
 -         StorageLive(_1);
 +         nop;
-          _1 = identity:: as fn(u8) -> u8 (PointerCoercion(ReifyFnPointer));
+          _1 = identity:: as fn(u8) -> u8 (PointerCoercion(ReifyFnPointer, AsCast));
           StorageLive(_2);
           StorageLive(_3);
           _3 = copy _1;
@@ -50,7 +50,7 @@
           StorageDead(_2);
 -         StorageLive(_4);
 +         nop;
-          _4 = identity:: as fn(u8) -> u8 (PointerCoercion(ReifyFnPointer));
+          _4 = identity:: as fn(u8) -> u8 (PointerCoercion(ReifyFnPointer, AsCast));
           StorageLive(_5);
           StorageLive(_6);
           _6 = copy _4;
@@ -69,9 +69,9 @@
 +         nop;
           StorageLive(_9);
 -         _9 = copy _7;
--         _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Safe)));
+-         _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast));
 +         _9 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21};
-+         _8 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21} as fn() (PointerCoercion(ClosureFnPointer(Safe)));
++         _8 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast));
           StorageDead(_9);
           StorageLive(_10);
           StorageLive(_11);
@@ -87,9 +87,9 @@
 +         nop;
           StorageLive(_13);
 -         _13 = copy _7;
--         _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Safe)));
+-         _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast));
 +         _13 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21};
-+         _12 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21} as fn() (PointerCoercion(ClosureFnPointer(Safe)));
++         _12 = const ZeroSized: {closure@$DIR/gvn.rs:614:19: 614:21} as fn() (PointerCoercion(ClosureFnPointer(Safe), AsCast));
           StorageDead(_13);
           StorageLive(_14);
           StorageLive(_15);
diff --git a/tests/mir-opt/gvn.wide_ptr_provenance.GVN.panic-abort.diff b/tests/mir-opt/gvn.wide_ptr_provenance.GVN.panic-abort.diff
index c58362e391c43..43cd8ba7809a2 100644
--- a/tests/mir-opt/gvn.wide_ptr_provenance.GVN.panic-abort.diff
+++ b/tests/mir-opt/gvn.wide_ptr_provenance.GVN.panic-abort.diff
@@ -64,10 +64,10 @@
           _44 = const wide_ptr_provenance::promoted[1];
           _5 = &(*_44);
           _4 = &(*_5);
-          _3 = move _4 as &dyn std::marker::Send (PointerCoercion(Unsize));
+          _3 = move _4 as &dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
           StorageDead(_4);
           _2 = &raw const (*_3);
--         _1 = move _2 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _1 = move _2 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_2);
 +         _1 = copy _2;
 +         nop;
@@ -82,10 +82,10 @@
           _43 = const wide_ptr_provenance::promoted[0];
           _11 = &(*_43);
           _10 = &(*_11);
-          _9 = move _10 as &dyn std::marker::Send (PointerCoercion(Unsize));
+          _9 = move _10 as &dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
           StorageDead(_10);
           _8 = &raw const (*_9);
--         _7 = move _8 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _7 = move _8 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_8);
 +         _7 = copy _8;
 +         nop;
@@ -99,7 +99,7 @@
           StorageLive(_16);
           StorageLive(_17);
 -         _17 = copy _7;
--         _16 = move _17 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _16 = move _17 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _17 = copy _8;
 +         _16 = copy _8;
           StorageDead(_17);
@@ -121,7 +121,7 @@
           StorageLive(_21);
           StorageLive(_22);
 -         _22 = copy _7;
--         _21 = move _22 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _21 = move _22 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _22 = copy _8;
 +         _21 = copy _8;
           StorageDead(_22);
@@ -143,7 +143,7 @@
           StorageLive(_26);
           StorageLive(_27);
 -         _27 = copy _7;
--         _26 = move _27 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _26 = move _27 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _27 = copy _8;
 +         _26 = copy _8;
           StorageDead(_27);
@@ -165,7 +165,7 @@
           StorageLive(_31);
           StorageLive(_32);
 -         _32 = copy _7;
--         _31 = move _32 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _31 = move _32 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _32 = copy _8;
 +         _31 = copy _8;
           StorageDead(_32);
@@ -187,7 +187,7 @@
           StorageLive(_36);
           StorageLive(_37);
 -         _37 = copy _7;
--         _36 = move _37 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _36 = move _37 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _37 = copy _8;
 +         _36 = copy _8;
           StorageDead(_37);
@@ -209,7 +209,7 @@
           StorageLive(_41);
           StorageLive(_42);
 -         _42 = copy _7;
--         _41 = move _42 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _41 = move _42 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _42 = copy _8;
 +         _41 = copy _8;
           StorageDead(_42);
diff --git a/tests/mir-opt/gvn.wide_ptr_provenance.GVN.panic-unwind.diff b/tests/mir-opt/gvn.wide_ptr_provenance.GVN.panic-unwind.diff
index b29ee862c81a3..49cca20153bd4 100644
--- a/tests/mir-opt/gvn.wide_ptr_provenance.GVN.panic-unwind.diff
+++ b/tests/mir-opt/gvn.wide_ptr_provenance.GVN.panic-unwind.diff
@@ -64,10 +64,10 @@
           _44 = const wide_ptr_provenance::promoted[1];
           _5 = &(*_44);
           _4 = &(*_5);
-          _3 = move _4 as &dyn std::marker::Send (PointerCoercion(Unsize));
+          _3 = move _4 as &dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
           StorageDead(_4);
           _2 = &raw const (*_3);
--         _1 = move _2 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _1 = move _2 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_2);
 +         _1 = copy _2;
 +         nop;
@@ -82,10 +82,10 @@
           _43 = const wide_ptr_provenance::promoted[0];
           _11 = &(*_43);
           _10 = &(*_11);
-          _9 = move _10 as &dyn std::marker::Send (PointerCoercion(Unsize));
+          _9 = move _10 as &dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
           StorageDead(_10);
           _8 = &raw const (*_9);
--         _7 = move _8 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _7 = move _8 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_8);
 +         _7 = copy _8;
 +         nop;
@@ -99,7 +99,7 @@
           StorageLive(_16);
           StorageLive(_17);
 -         _17 = copy _7;
--         _16 = move _17 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _16 = move _17 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _17 = copy _8;
 +         _16 = copy _8;
           StorageDead(_17);
@@ -121,7 +121,7 @@
           StorageLive(_21);
           StorageLive(_22);
 -         _22 = copy _7;
--         _21 = move _22 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _21 = move _22 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _22 = copy _8;
 +         _21 = copy _8;
           StorageDead(_22);
@@ -143,7 +143,7 @@
           StorageLive(_26);
           StorageLive(_27);
 -         _27 = copy _7;
--         _26 = move _27 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _26 = move _27 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _27 = copy _8;
 +         _26 = copy _8;
           StorageDead(_27);
@@ -165,7 +165,7 @@
           StorageLive(_31);
           StorageLive(_32);
 -         _32 = copy _7;
--         _31 = move _32 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _31 = move _32 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _32 = copy _8;
 +         _31 = copy _8;
           StorageDead(_32);
@@ -187,7 +187,7 @@
           StorageLive(_36);
           StorageLive(_37);
 -         _37 = copy _7;
--         _36 = move _37 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _36 = move _37 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _37 = copy _8;
 +         _36 = copy _8;
           StorageDead(_37);
@@ -209,7 +209,7 @@
           StorageLive(_41);
           StorageLive(_42);
 -         _42 = copy _7;
--         _41 = move _42 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _41 = move _42 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _42 = copy _8;
 +         _41 = copy _8;
           StorageDead(_42);
diff --git a/tests/mir-opt/gvn.wide_ptr_same_provenance.GVN.panic-abort.diff b/tests/mir-opt/gvn.wide_ptr_same_provenance.GVN.panic-abort.diff
index f4c38b7ab071e..6b6152c1117e3 100644
--- a/tests/mir-opt/gvn.wide_ptr_same_provenance.GVN.panic-abort.diff
+++ b/tests/mir-opt/gvn.wide_ptr_same_provenance.GVN.panic-abort.diff
@@ -86,10 +86,10 @@
 -         _7 = &(*_1)[_8];
 +         _7 = &(*_1)[0 of 1];
           _6 = &(*_7);
-          _5 = move _6 as &dyn std::marker::Send (PointerCoercion(Unsize));
+          _5 = move _6 as &dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
           StorageDead(_6);
           _4 = &raw const (*_5);
--         _3 = move _4 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _3 = move _4 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_4);
 +         _3 = copy _4;
 +         nop;
@@ -115,10 +115,10 @@
 -         _15 = &(*_1)[_16];
 +         _15 = &(*_1)[1 of 2];
           _14 = &(*_15);
-          _13 = move _14 as &dyn std::marker::Send (PointerCoercion(Unsize));
+          _13 = move _14 as &dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
           StorageDead(_14);
           _12 = &raw const (*_13);
--         _11 = move _12 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _11 = move _12 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_12);
 +         _11 = copy _12;
 +         nop;
@@ -132,7 +132,7 @@
           StorageLive(_22);
           StorageLive(_23);
 -         _23 = copy _11;
--         _22 = move _23 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _22 = move _23 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _23 = copy _12;
 +         _22 = copy _12;
           StorageDead(_23);
@@ -154,7 +154,7 @@
           StorageLive(_27);
           StorageLive(_28);
 -         _28 = copy _11;
--         _27 = move _28 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _27 = move _28 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _28 = copy _12;
 +         _27 = copy _12;
           StorageDead(_28);
@@ -176,7 +176,7 @@
           StorageLive(_32);
           StorageLive(_33);
 -         _33 = copy _11;
--         _32 = move _33 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _32 = move _33 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _33 = copy _12;
 +         _32 = copy _12;
           StorageDead(_33);
@@ -198,7 +198,7 @@
           StorageLive(_37);
           StorageLive(_38);
 -         _38 = copy _11;
--         _37 = move _38 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _37 = move _38 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _38 = copy _12;
 +         _37 = copy _12;
           StorageDead(_38);
@@ -220,7 +220,7 @@
           StorageLive(_42);
           StorageLive(_43);
 -         _43 = copy _11;
--         _42 = move _43 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _42 = move _43 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _43 = copy _12;
 +         _42 = copy _12;
           StorageDead(_43);
@@ -242,7 +242,7 @@
           StorageLive(_47);
           StorageLive(_48);
 -         _48 = copy _11;
--         _47 = move _48 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _47 = move _48 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _48 = copy _12;
 +         _47 = copy _12;
           StorageDead(_48);
diff --git a/tests/mir-opt/gvn.wide_ptr_same_provenance.GVN.panic-unwind.diff b/tests/mir-opt/gvn.wide_ptr_same_provenance.GVN.panic-unwind.diff
index 03f2d129a9b6f..093c1ec6ce379 100644
--- a/tests/mir-opt/gvn.wide_ptr_same_provenance.GVN.panic-unwind.diff
+++ b/tests/mir-opt/gvn.wide_ptr_same_provenance.GVN.panic-unwind.diff
@@ -86,10 +86,10 @@
 -         _7 = &(*_1)[_8];
 +         _7 = &(*_1)[0 of 1];
           _6 = &(*_7);
-          _5 = move _6 as &dyn std::marker::Send (PointerCoercion(Unsize));
+          _5 = move _6 as &dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
           StorageDead(_6);
           _4 = &raw const (*_5);
--         _3 = move _4 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _3 = move _4 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_4);
 +         _3 = copy _4;
 +         nop;
@@ -115,10 +115,10 @@
 -         _15 = &(*_1)[_16];
 +         _15 = &(*_1)[1 of 2];
           _14 = &(*_15);
-          _13 = move _14 as &dyn std::marker::Send (PointerCoercion(Unsize));
+          _13 = move _14 as &dyn std::marker::Send (PointerCoercion(Unsize, AsCast));
           StorageDead(_14);
           _12 = &raw const (*_13);
--         _11 = move _12 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _11 = move _12 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_12);
 +         _11 = copy _12;
 +         nop;
@@ -132,7 +132,7 @@
           StorageLive(_22);
           StorageLive(_23);
 -         _23 = copy _11;
--         _22 = move _23 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _22 = move _23 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _23 = copy _12;
 +         _22 = copy _12;
           StorageDead(_23);
@@ -154,7 +154,7 @@
           StorageLive(_27);
           StorageLive(_28);
 -         _28 = copy _11;
--         _27 = move _28 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _27 = move _28 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _28 = copy _12;
 +         _27 = copy _12;
           StorageDead(_28);
@@ -176,7 +176,7 @@
           StorageLive(_32);
           StorageLive(_33);
 -         _33 = copy _11;
--         _32 = move _33 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _32 = move _33 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _33 = copy _12;
 +         _32 = copy _12;
           StorageDead(_33);
@@ -198,7 +198,7 @@
           StorageLive(_37);
           StorageLive(_38);
 -         _38 = copy _11;
--         _37 = move _38 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _37 = move _38 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _38 = copy _12;
 +         _37 = copy _12;
           StorageDead(_38);
@@ -220,7 +220,7 @@
           StorageLive(_42);
           StorageLive(_43);
 -         _43 = copy _11;
--         _42 = move _43 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _42 = move _43 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _43 = copy _12;
 +         _42 = copy _12;
           StorageDead(_43);
@@ -242,7 +242,7 @@
           StorageLive(_47);
           StorageLive(_48);
 -         _48 = copy _11;
--         _47 = move _48 as *const dyn std::marker::Send (PointerCoercion(Unsize));
+-         _47 = move _48 as *const dyn std::marker::Send (PointerCoercion(Unsize, Implicit));
 +         _48 = copy _12;
 +         _47 = copy _12;
           StorageDead(_48);
diff --git a/tests/mir-opt/inline/dyn_trait.get_query.Inline.panic-abort.diff b/tests/mir-opt/inline/dyn_trait.get_query.Inline.panic-abort.diff
index 2d64d49ce5c13..df79001ce75b6 100644
--- a/tests/mir-opt/inline/dyn_trait.get_query.Inline.panic-abort.diff
+++ b/tests/mir-opt/inline/dyn_trait.get_query.Inline.panic-abort.diff
@@ -31,7 +31,7 @@
           _4 = copy _2;
 -         _0 = try_execute_query::<::C>(move _4) -> [return: bb2, unwind unreachable];
 +         StorageLive(_5);
-+         _5 = copy _4 as &dyn Cache::V> (PointerCoercion(Unsize));
++         _5 = copy _4 as &dyn Cache::V> (PointerCoercion(Unsize, Implicit));
 +         _0 = ::V> as Cache>::store_nocache(move _5) -> [return: bb2, unwind unreachable];
       }
   
diff --git a/tests/mir-opt/inline/dyn_trait.get_query.Inline.panic-unwind.diff b/tests/mir-opt/inline/dyn_trait.get_query.Inline.panic-unwind.diff
index c5e9654e19cfd..014f950940c5f 100644
--- a/tests/mir-opt/inline/dyn_trait.get_query.Inline.panic-unwind.diff
+++ b/tests/mir-opt/inline/dyn_trait.get_query.Inline.panic-unwind.diff
@@ -31,7 +31,7 @@
           _4 = copy _2;
 -         _0 = try_execute_query::<::C>(move _4) -> [return: bb2, unwind continue];
 +         StorageLive(_5);
-+         _5 = copy _4 as &dyn Cache::V> (PointerCoercion(Unsize));
++         _5 = copy _4 as &dyn Cache::V> (PointerCoercion(Unsize, Implicit));
 +         _0 = ::V> as Cache>::store_nocache(move _5) -> [return: bb2, unwind continue];
       }
   
diff --git a/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.panic-abort.diff b/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.panic-abort.diff
index f02ca6233173f..64d12461e8de1 100644
--- a/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.panic-abort.diff
+++ b/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.panic-abort.diff
@@ -14,7 +14,7 @@
           StorageLive(_2);
           StorageLive(_3);
           _3 = copy _1;
-          _2 = move _3 as &dyn Cache::V> (PointerCoercion(Unsize));
+          _2 = move _3 as &dyn Cache::V> (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
 -         _0 = mk_cycle::<::V>(move _2) -> [return: bb1, unwind unreachable];
 +         _0 = ::V> as Cache>::store_nocache(move _2) -> [return: bb1, unwind unreachable];
diff --git a/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.panic-unwind.diff b/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.panic-unwind.diff
index 31080dff4ded7..21791cb0d2a59 100644
--- a/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.panic-unwind.diff
+++ b/tests/mir-opt/inline/dyn_trait.try_execute_query.Inline.panic-unwind.diff
@@ -14,7 +14,7 @@
           StorageLive(_2);
           StorageLive(_3);
           _3 = copy _1;
-          _2 = move _3 as &dyn Cache::V> (PointerCoercion(Unsize));
+          _2 = move _3 as &dyn Cache::V> (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
 -         _0 = mk_cycle::<::V>(move _2) -> [return: bb1, unwind continue];
 +         _0 = ::V> as Cache>::store_nocache(move _2) -> [return: bb1, unwind continue];
diff --git a/tests/mir-opt/instsimplify/combine_transmutes.rs b/tests/mir-opt/instsimplify/combine_transmutes.rs
index 23f10b71f3c1b..8a670301825be 100644
--- a/tests/mir-opt/instsimplify/combine_transmutes.rs
+++ b/tests/mir-opt/instsimplify/combine_transmutes.rs
@@ -5,7 +5,7 @@
 #![feature(custom_mir)]
 
 use std::intrinsics::mir::*;
-use std::mem::{transmute, ManuallyDrop, MaybeUninit};
+use std::mem::{ManuallyDrop, MaybeUninit, transmute};
 
 // EMIT_MIR combine_transmutes.identity_transmutes.InstSimplify-after-simplifycfg.diff
 pub unsafe fn identity_transmutes() {
diff --git a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff
index f03691ad67316..c02bab3524bca 100644
--- a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff
+++ b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-abort.diff
@@ -26,7 +26,7 @@
           StorageLive(_4);
           _4 = [copy _1, copy _1, copy _1];
           _3 = &_4;
-          _2 = copy _3 as &[T] (PointerCoercion(Unsize));
+          _2 = copy _3 as &[T] (PointerCoercion(Unsize, Implicit));
           nop;
           nop;
           goto -> bb2;
diff --git a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff
index 633e5c740a1a8..49be042588cb3 100644
--- a/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff
+++ b/tests/mir-opt/issue_76432.test.SimplifyComparisonIntegral.panic-unwind.diff
@@ -26,7 +26,7 @@
           StorageLive(_4);
           _4 = [copy _1, copy _1, copy _1];
           _3 = &_4;
-          _2 = copy _3 as &[T] (PointerCoercion(Unsize));
+          _2 = copy _3 as &[T] (PointerCoercion(Unsize, Implicit));
           nop;
           nop;
           goto -> bb2;
diff --git a/tests/mir-opt/lower_array_len.array_bound.GVN.panic-abort.diff b/tests/mir-opt/lower_array_len.array_bound.GVN.panic-abort.diff
index 8223cbbb41216..f052c8f63dcaa 100644
--- a/tests/mir-opt/lower_array_len.array_bound.GVN.panic-abort.diff
+++ b/tests/mir-opt/lower_array_len.array_bound.GVN.panic-abort.diff
@@ -24,7 +24,7 @@
           StorageLive(_6);
           StorageLive(_7);
           _7 = &(*_2);
-          _6 = move _7 as &[u8] (PointerCoercion(Unsize));
+          _6 = move _7 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_7);
 -         _5 = PtrMetadata(move _6);
 +         _5 = const N;
diff --git a/tests/mir-opt/lower_array_len.array_bound.GVN.panic-unwind.diff b/tests/mir-opt/lower_array_len.array_bound.GVN.panic-unwind.diff
index d8f33accbc005..3299e3004317d 100644
--- a/tests/mir-opt/lower_array_len.array_bound.GVN.panic-unwind.diff
+++ b/tests/mir-opt/lower_array_len.array_bound.GVN.panic-unwind.diff
@@ -24,7 +24,7 @@
           StorageLive(_6);
           StorageLive(_7);
           _7 = &(*_2);
-          _6 = move _7 as &[u8] (PointerCoercion(Unsize));
+          _6 = move _7 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_7);
 -         _5 = PtrMetadata(move _6);
 +         _5 = const N;
diff --git a/tests/mir-opt/lower_array_len.array_bound_mut.GVN.panic-abort.diff b/tests/mir-opt/lower_array_len.array_bound_mut.GVN.panic-abort.diff
index 1cb9963c00e94..329eb80b3c4f5 100644
--- a/tests/mir-opt/lower_array_len.array_bound_mut.GVN.panic-abort.diff
+++ b/tests/mir-opt/lower_array_len.array_bound_mut.GVN.panic-abort.diff
@@ -27,7 +27,7 @@
           StorageLive(_6);
           StorageLive(_7);
           _7 = &(*_2);
-          _6 = move _7 as &[u8] (PointerCoercion(Unsize));
+          _6 = move _7 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_7);
 -         _5 = PtrMetadata(move _6);
 +         _5 = const N;
diff --git a/tests/mir-opt/lower_array_len.array_bound_mut.GVN.panic-unwind.diff b/tests/mir-opt/lower_array_len.array_bound_mut.GVN.panic-unwind.diff
index fa4e11ed20192..ab007e133ecc1 100644
--- a/tests/mir-opt/lower_array_len.array_bound_mut.GVN.panic-unwind.diff
+++ b/tests/mir-opt/lower_array_len.array_bound_mut.GVN.panic-unwind.diff
@@ -27,7 +27,7 @@
           StorageLive(_6);
           StorageLive(_7);
           _7 = &(*_2);
-          _6 = move _7 as &[u8] (PointerCoercion(Unsize));
+          _6 = move _7 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_7);
 -         _5 = PtrMetadata(move _6);
 +         _5 = const N;
diff --git a/tests/mir-opt/lower_array_len.array_len.GVN.panic-abort.diff b/tests/mir-opt/lower_array_len.array_len.GVN.panic-abort.diff
index 9c1b9a708c59a..369bd2f473297 100644
--- a/tests/mir-opt/lower_array_len.array_len.GVN.panic-abort.diff
+++ b/tests/mir-opt/lower_array_len.array_len.GVN.panic-abort.diff
@@ -11,7 +11,7 @@
           StorageLive(_2);
           StorageLive(_3);
           _3 = &(*_1);
-          _2 = move _3 as &[u8] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
 -         _0 = PtrMetadata(move _2);
 +         _0 = const N;
diff --git a/tests/mir-opt/lower_array_len.array_len.GVN.panic-unwind.diff b/tests/mir-opt/lower_array_len.array_len.GVN.panic-unwind.diff
index 9c1b9a708c59a..369bd2f473297 100644
--- a/tests/mir-opt/lower_array_len.array_len.GVN.panic-unwind.diff
+++ b/tests/mir-opt/lower_array_len.array_len.GVN.panic-unwind.diff
@@ -11,7 +11,7 @@
           StorageLive(_2);
           StorageLive(_3);
           _3 = &(*_1);
-          _2 = move _3 as &[u8] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
 -         _0 = PtrMetadata(move _2);
 +         _0 = const N;
diff --git a/tests/mir-opt/lower_array_len.array_len_by_value.GVN.panic-abort.diff b/tests/mir-opt/lower_array_len.array_len_by_value.GVN.panic-abort.diff
index 97fa503ac2e46..d9c289bf58aee 100644
--- a/tests/mir-opt/lower_array_len.array_len_by_value.GVN.panic-abort.diff
+++ b/tests/mir-opt/lower_array_len.array_len_by_value.GVN.panic-abort.diff
@@ -11,7 +11,7 @@
           StorageLive(_2);
           StorageLive(_3);
           _3 = &_1;
-          _2 = move _3 as &[u8] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
 -         _0 = PtrMetadata(move _2);
 +         _0 = const N;
diff --git a/tests/mir-opt/lower_array_len.array_len_by_value.GVN.panic-unwind.diff b/tests/mir-opt/lower_array_len.array_len_by_value.GVN.panic-unwind.diff
index 97fa503ac2e46..d9c289bf58aee 100644
--- a/tests/mir-opt/lower_array_len.array_len_by_value.GVN.panic-unwind.diff
+++ b/tests/mir-opt/lower_array_len.array_len_by_value.GVN.panic-unwind.diff
@@ -11,7 +11,7 @@
           StorageLive(_2);
           StorageLive(_3);
           _3 = &_1;
-          _2 = move _3 as &[u8] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
 -         _0 = PtrMetadata(move _2);
 +         _0 = const N;
diff --git a/tests/mir-opt/lower_array_len.array_len_raw.GVN.panic-abort.diff b/tests/mir-opt/lower_array_len.array_len_raw.GVN.panic-abort.diff
index b5e8b66813ae3..180a7db029794 100644
--- a/tests/mir-opt/lower_array_len.array_len_raw.GVN.panic-abort.diff
+++ b/tests/mir-opt/lower_array_len.array_len_raw.GVN.panic-abort.diff
@@ -24,7 +24,7 @@
           StorageLive(_4);
           _4 = &_1;
           _3 = &(*_4);
-          _2 = move _3 as &[u8] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
           StorageDead(_4);
           StorageLive(_5);
diff --git a/tests/mir-opt/lower_array_len.array_len_raw.GVN.panic-unwind.diff b/tests/mir-opt/lower_array_len.array_len_raw.GVN.panic-unwind.diff
index b5e8b66813ae3..180a7db029794 100644
--- a/tests/mir-opt/lower_array_len.array_len_raw.GVN.panic-unwind.diff
+++ b/tests/mir-opt/lower_array_len.array_len_raw.GVN.panic-unwind.diff
@@ -24,7 +24,7 @@
           StorageLive(_4);
           _4 = &_1;
           _3 = &(*_4);
-          _2 = move _3 as &[u8] (PointerCoercion(Unsize));
+          _2 = move _3 as &[u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
           StorageDead(_4);
           StorageLive(_5);
diff --git a/tests/mir-opt/lower_array_len.array_len_reborrow.GVN.panic-abort.diff b/tests/mir-opt/lower_array_len.array_len_reborrow.GVN.panic-abort.diff
index 0299c6acd804a..49964f8b49e26 100644
--- a/tests/mir-opt/lower_array_len.array_len_reborrow.GVN.panic-abort.diff
+++ b/tests/mir-opt/lower_array_len.array_len_reborrow.GVN.panic-abort.diff
@@ -23,7 +23,7 @@
           StorageLive(_4);
           _4 = &mut _1;
           _3 = &mut (*_4);
-          _2 = move _3 as &mut [u8] (PointerCoercion(Unsize));
+          _2 = move _3 as &mut [u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
           StorageDead(_4);
           StorageLive(_5);
diff --git a/tests/mir-opt/lower_array_len.array_len_reborrow.GVN.panic-unwind.diff b/tests/mir-opt/lower_array_len.array_len_reborrow.GVN.panic-unwind.diff
index 0299c6acd804a..49964f8b49e26 100644
--- a/tests/mir-opt/lower_array_len.array_len_reborrow.GVN.panic-unwind.diff
+++ b/tests/mir-opt/lower_array_len.array_len_reborrow.GVN.panic-unwind.diff
@@ -23,7 +23,7 @@
           StorageLive(_4);
           _4 = &mut _1;
           _3 = &mut (*_4);
-          _2 = move _3 as &mut [u8] (PointerCoercion(Unsize));
+          _2 = move _3 as &mut [u8] (PointerCoercion(Unsize, Implicit));
           StorageDead(_3);
           StorageDead(_4);
           StorageLive(_5);
diff --git a/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff b/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff
index 6cac8b109eea6..87fbcca917736 100644
--- a/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff
+++ b/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.32bit.panic-abort.diff
@@ -93,7 +93,7 @@
       bb5: {
           StorageLive(_15);
           _16 = &_13;
-          _15 = copy _16 as &dyn std::fmt::Debug (PointerCoercion(Unsize));
+          _15 = copy _16 as &dyn std::fmt::Debug (PointerCoercion(Unsize, Implicit));
           _14 = result::unwrap_failed(const "called `Result::unwrap()` on an `Err` value", move _15) -> unwind unreachable;
       }
   
diff --git a/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.64bit.panic-abort.diff b/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.64bit.panic-abort.diff
index 10fde25e3178b..13258c171605c 100644
--- a/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.64bit.panic-abort.diff
+++ b/tests/mir-opt/pre-codegen/issue_117368_print_invalid_constant.main.GVN.64bit.panic-abort.diff
@@ -93,7 +93,7 @@
       bb5: {
           StorageLive(_15);
           _16 = &_13;
-          _15 = copy _16 as &dyn std::fmt::Debug (PointerCoercion(Unsize));
+          _15 = copy _16 as &dyn std::fmt::Debug (PointerCoercion(Unsize, Implicit));
           _14 = result::unwrap_failed(const "called `Result::unwrap()` on an `Err` value", move _15) -> unwind unreachable;
       }
   
diff --git a/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-abort.mir b/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-abort.mir
index d0f454e456934..cca2b3ae188c3 100644
--- a/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-abort.mir
+++ b/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-abort.mir
@@ -105,7 +105,7 @@ fn main() -> () {
         StorageLive(_14);
         _14 = {closure@main::{closure#0}};
         Retag(_14);
-        _13 = move _14 as for<'a> fn(&'a i32) -> &'a i32 (PointerCoercion(ClosureFnPointer(Safe)));
+        _13 = move _14 as for<'a> fn(&'a i32) -> &'a i32 (PointerCoercion(ClosureFnPointer(Safe), Implicit));
         StorageDead(_14);
         StorageLive(_15);
         StorageLive(_16);
diff --git a/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-unwind.mir b/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-unwind.mir
index 685277d7a5328..bcd3a47ac04fb 100644
--- a/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-unwind.mir
+++ b/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-unwind.mir
@@ -105,7 +105,7 @@ fn main() -> () {
         StorageLive(_14);
         _14 = {closure@main::{closure#0}};
         Retag(_14);
-        _13 = move _14 as for<'a> fn(&'a i32) -> &'a i32 (PointerCoercion(ClosureFnPointer(Safe)));
+        _13 = move _14 as for<'a> fn(&'a i32) -> &'a i32 (PointerCoercion(ClosureFnPointer(Safe), Implicit));
         StorageDead(_14);
         StorageLive(_15);
         StorageLive(_16);
diff --git a/tests/mir-opt/simplify_locals.c.SimplifyLocals-before-const-prop.diff b/tests/mir-opt/simplify_locals.c.SimplifyLocals-before-const-prop.diff
index 7cc5e335cb00a..37a669d72b85e 100644
--- a/tests/mir-opt/simplify_locals.c.SimplifyLocals-before-const-prop.diff
+++ b/tests/mir-opt/simplify_locals.c.SimplifyLocals-before-const-prop.diff
@@ -21,7 +21,7 @@
 -         StorageLive(_4);
 -         _4 = &_1;
 -         _3 = &(*_4);
--         _2 = move _3 as &[u8] (PointerCoercion(Unsize));
+-         _2 = move _3 as &[u8] (PointerCoercion(Unsize, Implicit));
 -         StorageDead(_3);
 -         StorageDead(_4);
 -         StorageDead(_2);
diff --git a/tests/mir-opt/sroa/lifetimes.foo.ScalarReplacementOfAggregates.diff b/tests/mir-opt/sroa/lifetimes.foo.ScalarReplacementOfAggregates.diff
index 478dacc327668..a1df868cde051 100644
--- a/tests/mir-opt/sroa/lifetimes.foo.ScalarReplacementOfAggregates.diff
+++ b/tests/mir-opt/sroa/lifetimes.foo.ScalarReplacementOfAggregates.diff
@@ -61,7 +61,7 @@
       }
   
       bb1: {
-          _3 = move _4 as std::boxed::Box (PointerCoercion(Unsize));
+          _3 = move _4 as std::boxed::Box (PointerCoercion(Unsize, Implicit));
           StorageDead(_4);
           _2 = Result::, ::Err>::Ok(move _3);
           StorageDead(_3);
diff --git a/tests/run-make/c-link-to-rust-va-list-fn/checkrust.rs b/tests/run-make/c-link-to-rust-va-list-fn/checkrust.rs
index 0a959c3bd881d..bcaef33344e51 100644
--- a/tests/run-make/c-link-to-rust-va-list-fn/checkrust.rs
+++ b/tests/run-make/c-link-to-rust-va-list-fn/checkrust.rs
@@ -1,7 +1,7 @@
 #![crate_type = "staticlib"]
 #![feature(c_variadic)]
 
-use std::ffi::{c_char, c_double, c_int, c_long, c_longlong, CStr, CString, VaList};
+use std::ffi::{CStr, CString, VaList, c_char, c_double, c_int, c_long, c_longlong};
 
 macro_rules! continue_if {
     ($cond:expr) => {
diff --git a/tests/run-make/c-unwind-abi-catch-lib-panic/main.rs b/tests/run-make/c-unwind-abi-catch-lib-panic/main.rs
index 42d3efa82d618..07d89251aa668 100644
--- a/tests/run-make/c-unwind-abi-catch-lib-panic/main.rs
+++ b/tests/run-make/c-unwind-abi-catch-lib-panic/main.rs
@@ -3,7 +3,7 @@
 //! This test triggers a panic in a Rust library that our foreign function invokes. This shows
 //! that we can unwind through the C code in that library, and catch the underlying panic.
 
-use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::panic::{AssertUnwindSafe, catch_unwind};
 
 fn main() {
     // Call `add_small_numbers`, passing arguments that will NOT trigger a panic.
diff --git a/tests/run-make/c-unwind-abi-catch-panic/main.rs b/tests/run-make/c-unwind-abi-catch-panic/main.rs
index 1903be9561c57..3c523b6cc6982 100644
--- a/tests/run-make/c-unwind-abi-catch-panic/main.rs
+++ b/tests/run-make/c-unwind-abi-catch-panic/main.rs
@@ -2,7 +2,7 @@
 //!
 //! This test triggers a panic when calling a foreign function that calls *back* into Rust.
 
-use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::panic::{AssertUnwindSafe, catch_unwind};
 
 fn main() {
     // Call `add_small_numbers`, passing arguments that will NOT trigger a panic.
diff --git a/tests/run-make/compiler-builtins/rmake.rs b/tests/run-make/compiler-builtins/rmake.rs
index 3b05fe2055c34..10093db2258df 100644
--- a/tests/run-make/compiler-builtins/rmake.rs
+++ b/tests/run-make/compiler-builtins/rmake.rs
@@ -15,46 +15,36 @@
 #![deny(warnings)]
 
 use std::collections::HashSet;
-use std::path::PathBuf;
 
-use run_make_support::object::read::archive::ArchiveFile;
 use run_make_support::object::read::Object;
+use run_make_support::object::read::archive::ArchiveFile;
 use run_make_support::object::{ObjectSection, ObjectSymbol, RelocationTarget};
 use run_make_support::rfs::{read, read_dir};
-use run_make_support::{cmd, env_var, object};
+use run_make_support::{cargo, object, path, target};
 
 fn main() {
-    let target_dir = PathBuf::from("target");
-    let target = env_var("TARGET");
-
-    println!("Testing compiler_builtins for {}", target);
-
-    let manifest_path = PathBuf::from("Cargo.toml");
-
-    let path = env_var("PATH");
-    let rustc = env_var("RUSTC");
-    let cargo = env_var("CARGO");
-    let mut cmd = cmd(cargo);
-    cmd.args(&[
-        "build",
-        "--manifest-path",
-        manifest_path.to_str().unwrap(),
-        "-Zbuild-std=core",
-        "--target",
-        &target,
-    ])
-    .env("PATH", path)
-    .env("RUSTC", rustc)
-    .env("RUSTFLAGS", "-Copt-level=0 -Cdebug-assertions=yes")
-    .env("CARGO_TARGET_DIR", &target_dir)
-    .env("RUSTC_BOOTSTRAP", "1")
-    // Visual Studio 2022 requires that the LIB env var be set so it can
-    // find the Windows SDK.
-    .env("LIB", std::env::var("LIB").unwrap_or_default());
-
-    cmd.run();
-
-    let rlibs_path = target_dir.join(target).join("debug").join("deps");
+    let target_dir = path("target");
+
+    println!("Testing compiler_builtins for {}", target());
+
+    cargo()
+        .args(&[
+            "build",
+            "--manifest-path",
+            "Cargo.toml",
+            "-Zbuild-std=core",
+            "--target",
+            &target(),
+        ])
+        .env("RUSTFLAGS", "-Copt-level=0 -Cdebug-assertions=yes")
+        .env("CARGO_TARGET_DIR", &target_dir)
+        .env("RUSTC_BOOTSTRAP", "1")
+        // Visual Studio 2022 requires that the LIB env var be set so it can
+        // find the Windows SDK.
+        .env("LIB", std::env::var("LIB").unwrap_or_default())
+        .run();
+
+    let rlibs_path = target_dir.join(target()).join("debug").join("deps");
     let compiler_builtins_rlib = read_dir(rlibs_path)
         .find_map(|e| {
             let path = e.unwrap().path();
diff --git a/tests/run-make/compressed-debuginfo-zstd/rmake.rs b/tests/run-make/compressed-debuginfo-zstd/rmake.rs
index 8356373e949aa..cd8cf223047d3 100644
--- a/tests/run-make/compressed-debuginfo-zstd/rmake.rs
+++ b/tests/run-make/compressed-debuginfo-zstd/rmake.rs
@@ -8,7 +8,7 @@
 //@ only-linux
 //@ ignore-cross-compile
 
-use run_make_support::{llvm_readobj, run_in_tmpdir, Rustc};
+use run_make_support::{Rustc, llvm_readobj, run_in_tmpdir};
 
 fn check_compression(compression: &str, to_find: &str) {
     // check compressed debug sections via rustc flag
diff --git a/tests/run-make/crate-loading/multiple-dep-versions.rs b/tests/run-make/crate-loading/multiple-dep-versions.rs
index 8ef042bf41842..113af9c30255b 100644
--- a/tests/run-make/crate-loading/multiple-dep-versions.rs
+++ b/tests/run-make/crate-loading/multiple-dep-versions.rs
@@ -1,7 +1,7 @@
 extern crate dep_2_reexport;
 extern crate dependency;
 use dep_2_reexport::Type;
-use dependency::{do_something, Trait};
+use dependency::{Trait, do_something};
 
 fn main() {
     do_something(Type);
diff --git a/tests/run-make/crate-loading/rmake.rs b/tests/run-make/crate-loading/rmake.rs
index 95a9011669ec4..5d3302c7b02a0 100644
--- a/tests/run-make/crate-loading/rmake.rs
+++ b/tests/run-make/crate-loading/rmake.rs
@@ -64,10 +64,10 @@ note: there are multiple different versions of crate `dependency` in the depende
 5 |     fn foo(&self);
   |     -------------- the method is available for `dep_2_reexport::Type` here
   |
- ::: multiple-dep-versions.rs:4:32
+ ::: multiple-dep-versions.rs:4:18
   |
-4 | use dependency::{do_something, Trait};
-  |                                ----- `Trait` imported here doesn't correspond to the right version of crate `dependency`"#,
+4 | use dependency::{Trait, do_something};
+  |                  ----- `Trait` imported here doesn't correspond to the right version of crate `dependency`"#,
         )
         .assert_stderr_contains(
             r#"
@@ -92,9 +92,9 @@ note: there are multiple different versions of crate `dependency` in the depende
 6 |     fn bar();
   |     --------- the associated function is available for `dep_2_reexport::Type` here
   |
- ::: multiple-dep-versions.rs:4:32
+ ::: multiple-dep-versions.rs:4:18
   |
-4 | use dependency::{do_something, Trait};
-  |                                ----- `Trait` imported here doesn't correspond to the right version of crate `dependency`"#,
+4 | use dependency::{Trait, do_something};
+  |                  ----- `Trait` imported here doesn't correspond to the right version of crate `dependency`"#,
         );
 }
diff --git a/tests/run-make/extern-fn-explicit-align/test.rs b/tests/run-make/extern-fn-explicit-align/test.rs
index 81991b5919ce3..8933a2d07f54a 100644
--- a/tests/run-make/extern-fn-explicit-align/test.rs
+++ b/tests/run-make/extern-fn-explicit-align/test.rs
@@ -1,6 +1,6 @@
 // Issue #80127: Passing structs via FFI should work with explicit alignment.
 
-use std::ffi::{c_char, CStr};
+use std::ffi::{CStr, c_char};
 use std::ptr::null_mut;
 
 #[repr(C)]
diff --git a/tests/run-make/foreign-exceptions/foo.rs b/tests/run-make/foreign-exceptions/foo.rs
index ccf858d858794..208c5f407e976 100644
--- a/tests/run-make/foreign-exceptions/foo.rs
+++ b/tests/run-make/foreign-exceptions/foo.rs
@@ -2,7 +2,7 @@
 // are caught by catch_unwind. Also tests that Rust panics can unwind through
 // C++ code.
 
-use std::panic::{catch_unwind, AssertUnwindSafe};
+use std::panic::{AssertUnwindSafe, catch_unwind};
 
 struct DropCheck<'a>(&'a mut bool);
 impl<'a> Drop for DropCheck<'a> {
diff --git a/tests/run-make/naked-symbol-visibility/rmake.rs b/tests/run-make/naked-symbol-visibility/rmake.rs
index 07ff253788d0a..d026196f43baa 100644
--- a/tests/run-make/naked-symbol-visibility/rmake.rs
+++ b/tests/run-make/naked-symbol-visibility/rmake.rs
@@ -1,7 +1,7 @@
 //@ ignore-windows
 //@ only-x86_64
-use run_make_support::object::read::{File, Object, Symbol};
 use run_make_support::object::ObjectSymbol;
+use run_make_support::object::read::{File, Object, Symbol};
 use run_make_support::targets::is_windows;
 use run_make_support::{dynamic_lib_name, rfs, rustc};
 
diff --git a/tests/run-make/rustdoc-shared-flags/rmake.rs b/tests/run-make/rustdoc-shared-flags/rmake.rs
index d9a16d78a3428..4adb5b5a2eb34 100644
--- a/tests/run-make/rustdoc-shared-flags/rmake.rs
+++ b/tests/run-make/rustdoc-shared-flags/rmake.rs
@@ -1,4 +1,4 @@
-use run_make_support::{rustc, rustdoc, Diff};
+use run_make_support::{Diff, rustc, rustdoc};
 
 fn compare_outputs(args: &[&str]) {
     let rustc_output = rustc().args(args).run().stdout_utf8();
diff --git a/tests/run-make/split-debuginfo/main.rs b/tests/run-make/split-debuginfo/main.rs
index e815672fa8197..21fa16e40a4ab 100644
--- a/tests/run-make/split-debuginfo/main.rs
+++ b/tests/run-make/split-debuginfo/main.rs
@@ -1,6 +1,6 @@
 extern crate bar;
 
-use bar::{make_bar, Bar};
+use bar::{Bar, make_bar};
 
 fn main() {
     let b = make_bar(3);
diff --git a/tests/run-make/thumb-none-cortex-m/rmake.rs b/tests/run-make/thumb-none-cortex-m/rmake.rs
index 9112646290f20..27afef874da64 100644
--- a/tests/run-make/thumb-none-cortex-m/rmake.rs
+++ b/tests/run-make/thumb-none-cortex-m/rmake.rs
@@ -14,10 +14,7 @@
 
 //@ only-thumb
 
-use std::path::PathBuf;
-
-use run_make_support::rfs::create_dir;
-use run_make_support::{cmd, env_var, target};
+use run_make_support::{cargo, cmd, env, env_var, target};
 
 const CRATE: &str = "cortex-m";
 const CRATE_URL: &str = "https://github.com/rust-embedded/cortex-m";
@@ -28,32 +25,21 @@ fn main() {
     // See below link for git usage:
     // https://stackoverflow.com/questions/3489173#14091182
     cmd("git").args(["clone", CRATE_URL, CRATE]).run();
-    std::env::set_current_dir(CRATE).unwrap();
+    env::set_current_dir(CRATE);
     cmd("git").args(["reset", "--hard", CRATE_SHA1]).run();
 
-    let target_dir = PathBuf::from("target");
-    let manifest_path = PathBuf::from("Cargo.toml");
-
-    let path = env_var("PATH");
-    let rustc = env_var("RUSTC");
-    let cargo = env_var("CARGO");
-    // FIXME: extract cargo invocations to a proper command
-    // https://github.com/rust-lang/rust/issues/128734
-    let mut cmd = cmd(cargo);
-    cmd.args(&[
-        "build",
-        "--manifest-path",
-        manifest_path.to_str().unwrap(),
-        "-Zbuild-std=core",
-        "--target",
-        &target(),
-    ])
-    .env("PATH", path)
-    .env("RUSTC", rustc)
-    .env("CARGO_TARGET_DIR", &target_dir)
-    // Don't make lints fatal, but they need to at least warn
-    // or they break Cargo's target info parsing.
-    .env("RUSTFLAGS", "-Copt-level=0 -Cdebug-assertions=yes --cap-lints=warn");
-
-    cmd.run();
+    cargo()
+        .args(&[
+            "build",
+            "--manifest-path",
+            "Cargo.toml",
+            "-Zbuild-std=core",
+            "--target",
+            &target(),
+        ])
+        .env("CARGO_TARGET_DIR", "target")
+        // Don't make lints fatal, but they need to at least warn
+        // or they break Cargo's target info parsing.
+        .env("RUSTFLAGS", "-Copt-level=0 -Cdebug-assertions=yes --cap-lints=warn")
+        .run();
 }
diff --git a/tests/run-make/thumb-none-qemu/rmake.rs b/tests/run-make/thumb-none-qemu/rmake.rs
index d0f42bc880897..a505bb013f9b7 100644
--- a/tests/run-make/thumb-none-qemu/rmake.rs
+++ b/tests/run-make/thumb-none-qemu/rmake.rs
@@ -14,49 +14,34 @@
 //!
 //! FIXME: https://github.com/rust-lang/rust/issues/128733 this test uses external
 //! dependencies, and needs an active internet connection
-//!
-//! FIXME: https://github.com/rust-lang/rust/issues/128734 extract bootstrap cargo
-//! to a proper command
 
 //@ only-thumb
 
 use std::path::PathBuf;
 
-use run_make_support::{cmd, env_var, path_helpers, target};
+use run_make_support::{cargo, cmd, env_var, path, target};
 
 const CRATE: &str = "example";
 
 fn main() {
     std::env::set_current_dir(CRATE).unwrap();
 
-    let bootstrap_cargo = env_var("BOOTSTRAP_CARGO");
-    let path = env_var("PATH");
-    let rustc = env_var("RUSTC");
-
-    let target_dir = path_helpers::path("target");
-    let manifest_path = path_helpers::path("Cargo.toml");
-
-    let debug = {
-        let mut cmd = cmd(&bootstrap_cargo);
-        cmd.args(&["run", "--target", &target()])
-            .env("RUSTFLAGS", "-C linker=arm-none-eabi-ld -C link-arg=-Tlink.x")
-            .env("CARGO_TARGET_DIR", &target_dir)
-            .env("PATH", &path)
-            .env("RUSTC", &rustc);
-        cmd.run()
-    };
-
-    debug.assert_stdout_contains("x = 42");
-
-    let release = {
-        let mut cmd = cmd(&bootstrap_cargo);
-        cmd.args(&["run", "--release", "--target", &target()])
-            .env("RUSTFLAGS", "-C linker=arm-none-eabi-ld -C link-arg=-Tlink.x")
-            .env("CARGO_TARGET_DIR", &target_dir)
-            .env("PATH", &path)
-            .env("RUSTC", &rustc);
-        cmd.run()
-    };
-
-    release.assert_stdout_contains("x = 42");
+    let target_dir = path("target");
+    let manifest_path = path("Cargo.toml");
+
+    // Debug
+    cargo()
+        .args(&["run", "--target", &target()])
+        .env("RUSTFLAGS", "-C linker=arm-none-eabi-ld -C link-arg=-Tlink.x")
+        .env("CARGO_TARGET_DIR", &target_dir)
+        .run()
+        .assert_stdout_contains("x = 42");
+
+    // Release
+    cargo()
+        .args(&["run", "--release", "--target", &target()])
+        .env("RUSTFLAGS", "-C linker=arm-none-eabi-ld -C link-arg=-Tlink.x")
+        .env("CARGO_TARGET_DIR", &target_dir)
+        .run()
+        .assert_stdout_contains("x = 42");
 }
diff --git a/tests/run-make/type-mismatch-same-crate-name/crateA.rs b/tests/run-make/type-mismatch-same-crate-name/crateA.rs
index 0dccfbb4bed6f..7ad8fd2a6480b 100644
--- a/tests/run-make/type-mismatch-same-crate-name/crateA.rs
+++ b/tests/run-make/type-mismatch-same-crate-name/crateA.rs
@@ -12,5 +12,5 @@ mod bar {
 
 // This makes the publicly accessible path
 // differ from the internal one.
-pub use bar::{bar, Bar};
+pub use bar::{Bar, bar};
 pub use foo::Foo;
diff --git a/tests/run-make/wasm-export-all-symbols/rmake.rs b/tests/run-make/wasm-export-all-symbols/rmake.rs
index 4148cc29ec2f8..0c0a785c67cde 100644
--- a/tests/run-make/wasm-export-all-symbols/rmake.rs
+++ b/tests/run-make/wasm-export-all-symbols/rmake.rs
@@ -20,16 +20,13 @@ fn test(args: &[&str]) {
     rustc().input("main.rs").target("wasm32-wasip1").args(args).run();
 
     verify_exports(Path::new("foo.wasm"), &[("foo", Func), ("FOO", Global), ("memory", Memory)]);
-    verify_exports(
-        Path::new("main.wasm"),
-        &[
-            ("foo", Func),
-            ("FOO", Global),
-            ("_start", Func),
-            ("__main_void", Func),
-            ("memory", Memory),
-        ],
-    );
+    verify_exports(Path::new("main.wasm"), &[
+        ("foo", Func),
+        ("FOO", Global),
+        ("_start", Func),
+        ("__main_void", Func),
+        ("memory", Memory),
+    ]);
 }
 
 fn verify_exports(path: &Path, exports: &[(&str, wasmparser::ExternalKind)]) {
diff --git a/tests/run-pass-valgrind/exit-flushes.rs b/tests/run-pass-valgrind/exit-flushes.rs
index c2072cf0bf834..4e25ef76d39af 100644
--- a/tests/run-pass-valgrind/exit-flushes.rs
+++ b/tests/run-pass-valgrind/exit-flushes.rs
@@ -4,7 +4,7 @@
 // https://github.com/rust-lang/rust/pull/30365#issuecomment-165763679
 
 use std::env;
-use std::process::{exit, Command};
+use std::process::{Command, exit};
 
 fn main() {
     if env::args().len() > 1 {
diff --git a/tests/rustdoc-gui/anchors.goml b/tests/rustdoc-gui/anchors.goml
index 61b2e8880c602..3168c8e17c52f 100644
--- a/tests/rustdoc-gui/anchors.goml
+++ b/tests/rustdoc-gui/anchors.goml
@@ -12,8 +12,7 @@ define-function: (
         call-function: ("switch-theme", {"theme": |theme|})
 
         assert-css: ("#toggle-all-docs", {"color": |main_color|})
-        assert-css: (".main-heading h1 a:nth-of-type(1)", {"color": |main_heading_color|})
-        assert-css: (".main-heading a:nth-of-type(2)", {"color": |main_heading_type_color|})
+        assert-css: (".main-heading h1 span", {"color": |main_heading_type_color|})
         assert-css: (
              ".rightside a.src",
              {"color": |src_link_color|, "text-decoration": "none solid " + |src_link_color|},
@@ -55,7 +54,7 @@ define-function: (
         assert-css: ("#top-doc-prose-title", {"color": |title_color|})
 
         assert-css: (".sidebar .block a", {"color": |sidebar_link_color|})
-        assert-css: (".main-heading h1 a", {"color": |title_color|})
+        assert-css: (".main-heading h1", {"color": |title_color|})
 
         // We move the cursor over the "Implementations" title so the anchor is displayed.
         move-cursor-to: "h2#implementations"
diff --git a/tests/rustdoc-gui/docblock-code-block-line-number.goml b/tests/rustdoc-gui/docblock-code-block-line-number.goml
index fed916ac24675..53f756dfcd64a 100644
--- a/tests/rustdoc-gui/docblock-code-block-line-number.goml
+++ b/tests/rustdoc-gui/docblock-code-block-line-number.goml
@@ -87,7 +87,7 @@ assert-css: ("#settings", {"display": "block"})
 
 // Then, click the toggle button.
 click: "input#line-numbers"
-wait-for: 100 // wait-for-false does not exist
+wait-for: 100 // FIXME: `wait-for-false` does not exist
 assert-false: "pre.example-line-numbers"
 assert-local-storage: {"rustdoc-line-numbers": "false" }
 
@@ -107,6 +107,8 @@ assert-css: (
 click: "input#line-numbers"
 wait-for: "pre.example-line-numbers"
 assert-local-storage: {"rustdoc-line-numbers": "true" }
+wait-for: 100 // FIXME: `wait-for-false` does not exist
+assert: "pre.example-line-numbers"
 
 // Same check with scraped examples line numbers.
 go-to: "file://" + |DOC_PATH| + "/scrape_examples/fn.test_many.html"
@@ -145,9 +147,6 @@ assert-css: (
     ALL,
 )
 
-// Checking line numbers on scraped code examples.
-go-to: "file://" + |DOC_PATH| + "/scrape_examples/fn.test_many.html"
-
 define-function: (
     "check-padding",
     [path, padding_bottom],
@@ -157,19 +156,19 @@ define-function: (
             "padding-bottom": "0px",
             "padding-left": "0px",
             "padding-right": "0px",
-        })
+        }, ALL)
         assert-css: (|path| + " .src-line-numbers > pre", {
             "padding-top": "14px",
             "padding-bottom": |padding_bottom|,
             "padding-left": "0px",
             "padding-right": "0px",
-        })
+        }, ALL)
         assert-css: (|path| + " .src-line-numbers > pre > span", {
             "padding-top": "0px",
             "padding-bottom": "0px",
             "padding-left": "8px",
             "padding-right": "8px",
-        })
+        }, ALL)
     },
 )
 
@@ -188,6 +187,35 @@ call-function: ("check-padding", {
     "padding_bottom": "14px",
 })
 
+define-function: ("check-line-numbers-existence", [], block {
+    assert-local-storage: {"rustdoc-line-numbers": "true" }
+    assert-false: ".example-line-numbers"
+    click: "#settings-menu"
+    wait-for: "#settings"
+
+    // Then, click the toggle button.
+    click: "input#line-numbers"
+    wait-for: 100 // FIXME: `wait-for-false` does not exist
+    assert-local-storage-false: {"rustdoc-line-numbers": "true" }
+    assert-false: ".example-line-numbers"
+    // Line numbers should still be there.
+    assert: ".src-line-numbers"
+    // Now disabling the setting.
+    click: "input#line-numbers"
+    wait-for: 100 // FIXME: `wait-for-false` does not exist
+    assert-local-storage: {"rustdoc-line-numbers": "true" }
+    assert-false: ".example-line-numbers"
+    // Line numbers should still be there.
+    assert: ".src-line-numbers"
+    // Closing settings menu.
+    click: "#settings-menu"
+    wait-for-css: ("#settings", {"display": "none"})
+})
+
+// Checking that turning off the line numbers setting won't remove line numbers from scraped
+// examples.
+call-function: ("check-line-numbers-existence", {})
+
 // Now checking the line numbers in the source code page.
 click: ".src"
 assert-css: (".src-line-numbers", {
@@ -202,3 +230,28 @@ assert-css: (".src-line-numbers > a", {
     "padding-left": "8px",
     "padding-right": "8px",
 })
+// Checking that turning off the line numbers setting won't remove line numbers.
+call-function: ("check-line-numbers-existence", {})
+
+// Now checking that even non-rust code blocks have line numbers generated.
+go-to: "file://" + |DOC_PATH| + "/lib2/sub_mod/struct.Foo.html"
+assert-local-storage: {"rustdoc-line-numbers": "true" }
+assert: ".example-wrap > pre.language-txt"
+assert: ".example-wrap > pre.rust"
+assert-count: (".example-wrap", 2)
+assert-count: (".example-wrap > pre.example-line-numbers", 2)
+
+click: "#settings-menu"
+wait-for: "#settings"
+
+// Then, click the toggle button.
+click: "input#line-numbers"
+wait-for: 100 // FIXME: `wait-for-false` does not exist
+assert-local-storage-false: {"rustdoc-line-numbers": "true" }
+assert-count: (".example-wrap > pre.example-line-numbers", 0)
+
+// Now turning off the setting.
+click: "input#line-numbers"
+wait-for: 100 // FIXME: `wait-for-false` does not exist
+assert-local-storage: {"rustdoc-line-numbers": "true" }
+assert-count: (".example-wrap > pre.example-line-numbers", 2)
diff --git a/tests/rustdoc-gui/help-page.goml b/tests/rustdoc-gui/help-page.goml
index f1a2675128ce4..6d6e353ae362b 100644
--- a/tests/rustdoc-gui/help-page.goml
+++ b/tests/rustdoc-gui/help-page.goml
@@ -4,7 +4,7 @@ set-window-size: (1000, 1000) // Try desktop size first.
 wait-for: "#help"
 assert-css: ("#help", {"display": "block"})
 assert-css: ("#help dd", {"font-size": "16px"})
-click: "#help-button > a"
+assert-false: "#help-button > a"
 assert-css: ("#help", {"display": "block"})
 compare-elements-property: (".sub", "#help", ["offsetWidth"])
 compare-elements-position: (".sub", "#help", ["x"])
@@ -50,7 +50,8 @@ call-function: ("check-colors", {
 })
 
 // This test ensures that opening the help popover without switching pages works.
-go-to: "file://" + |DOC_PATH| + "/test_docs/index.html"
+go-to: "file://" + |DOC_PATH| + "/test_docs/index.html?search=a"
+wait-for: "#search-tabs" // Waiting for the search.js to load.
 set-window-size: (1000, 1000) // Only supported on desktop.
 assert-false: "#help"
 click: "#help-button > a"
@@ -62,7 +63,8 @@ compare-elements-property-false: (".sub", "#help", ["offsetWidth"])
 compare-elements-position-false: (".sub", "#help", ["x"])
 
 // This test ensures that the "the rustdoc book" anchor link within the help popover works.
-go-to: "file://" + |DOC_PATH| + "/test_docs/index.html"
+go-to: "file://" + |DOC_PATH| + "/test_docs/index.html?search=a"
+wait-for: "#search-tabs" // Waiting for the search.js to load.
 set-window-size: (1000, 1000) // Popover only appears when the screen width is >700px.
 assert-false: "#help"
 click: "#help-button > a"
diff --git a/tests/rustdoc-gui/item-info.goml b/tests/rustdoc-gui/item-info.goml
index 7a0194c6cc1f6..c8aa7b31cadc6 100644
--- a/tests/rustdoc-gui/item-info.goml
+++ b/tests/rustdoc-gui/item-info.goml
@@ -20,7 +20,7 @@ store-position: (
     {"x": second_line_x, "y": second_line_y},
 )
 assert: |first_line_x| != |second_line_x| && |first_line_x| == 516 && |second_line_x| == 272
-assert: |first_line_y| != |second_line_y| && |first_line_y| == 688 && |second_line_y| == 711
+assert: |first_line_y| != |second_line_y| && |first_line_y| == 714 && |second_line_y| == 737
 
 // Now we ensure that they're not rendered on the same line.
 set-window-size: (1100, 800)
diff --git a/tests/rustdoc-gui/mobile.goml b/tests/rustdoc-gui/mobile.goml
index e576385cd5370..a9eee53dd1d50 100644
--- a/tests/rustdoc-gui/mobile.goml
+++ b/tests/rustdoc-gui/mobile.goml
@@ -5,23 +5,8 @@ set-window-size: (400, 600)
 set-font-size: 18
 wait-for: 100 // wait a bit for the resize and the font-size change to be fully taken into account.
 
-// The out-of-band info (source, stable version, collapse) should be below the
-// h1 when the screen gets narrow enough.
-assert-css: (".main-heading", {
-  "display": "flex",
-  "flex-direction": "column"
-})
-
 assert-property: (".mobile-topbar h2", {"offsetHeight": 33})
 
-// Note: We can't use assert-text here because the 'Since' is set by CSS and
-// is therefore not part of the DOM.
-assert-css: (".content .out-of-band .since::before", { "content": "\"Since \"" })
-
-set-window-size: (1000, 1000)
-wait-for: 100 // wait a bit for the resize to be fully taken into account.
-assert-css-false: (".content .out-of-band .since::before", { "content": "\"Since \"" })
-
 // On the settings page, the theme buttons should not line-wrap. Instead, they should
 // all be placed as a group on a line below the setting name "Theme."
 go-to: "file://" + |DOC_PATH| + "/settings.html"
diff --git a/tests/rustdoc-gui/notable-trait.goml b/tests/rustdoc-gui/notable-trait.goml
index e2a8a43007eb0..b8fa26b17f6b6 100644
--- a/tests/rustdoc-gui/notable-trait.goml
+++ b/tests/rustdoc-gui/notable-trait.goml
@@ -248,12 +248,13 @@ click: "//*[@id='method.create_an_iterator_from_read']//*[@class='tooltip']"
 assert-count: ("//*[@class='tooltip popover']", 1)
 assert-false: "//*[@class='sidebar shown']"
 
-// Also check the focus handling for the help button.
+// Also check the focus handling for the settings button.
 set-window-size: (1100, 600)
 reload:
 assert-count: ("//*[@class='tooltip popover']", 0)
 click: "//*[@id='method.create_an_iterator_from_read']//*[@class='tooltip']"
 assert-count: ("//*[@class='tooltip popover']", 1)
-click: "#help-button a"
+click: "#settings-menu a"
+wait-for: "#settings"
 assert-count: ("//*[@class='tooltip popover']", 0)
 assert-false: "#method\.create_an_iterator_from_read .tooltip:focus"
diff --git a/tests/rustdoc-gui/pocket-menu.goml b/tests/rustdoc-gui/pocket-menu.goml
index ec31f492abe7c..4a062fec7516d 100644
--- a/tests/rustdoc-gui/pocket-menu.goml
+++ b/tests/rustdoc-gui/pocket-menu.goml
@@ -1,6 +1,7 @@
 // This test ensures that the "pocket menus" are working as expected.
 include: "utils.goml"
-go-to: "file://" + |DOC_PATH| + "/test_docs/index.html"
+go-to: "file://" + |DOC_PATH| + "/test_docs/index.html?search=test"
+wait-for: "#crate-search"
 // First we check that the help menu doesn't exist yet.
 assert-false: "#help-button .popover"
 // Then we display the help menu.
diff --git a/tests/rustdoc-gui/scrape-examples-layout.goml b/tests/rustdoc-gui/scrape-examples-layout.goml
index be14e202b37d0..fd0774c91b675 100644
--- a/tests/rustdoc-gui/scrape-examples-layout.goml
+++ b/tests/rustdoc-gui/scrape-examples-layout.goml
@@ -80,8 +80,8 @@ click: ".scraped-example .button-holder .expand"
 store-value: (offset_y, 4)
 
 // First with desktop
-assert-position: (".scraped-example", {"y": 226})
-assert-position: (".scraped-example .prev", {"y": 226 + |offset_y|})
+assert-position: (".scraped-example", {"y": 252})
+assert-position: (".scraped-example .prev", {"y": 252 + |offset_y|})
 
 // Gradient background should be at the top of the code block.
 assert-css: (".scraped-example .example-wrap::before", {"top": "0px"})
@@ -90,8 +90,8 @@ assert-css: (".scraped-example .example-wrap::after", {"bottom": "0px"})
 // Then with mobile
 set-window-size: (600, 600)
 store-size: (".scraped-example .scraped-example-title", {"height": title_height})
-assert-position: (".scraped-example", {"y": 284})
-assert-position: (".scraped-example .prev", {"y": 284 + |offset_y| + |title_height|})
+assert-position: (".scraped-example", {"y": 281})
+assert-position: (".scraped-example .prev", {"y": 281 + |offset_y| + |title_height|})
 
 define-function: (
     "check_title_and_code_position",
diff --git a/tests/rustdoc-gui/search-filter.goml b/tests/rustdoc-gui/search-filter.goml
index d6421599a207b..c5038e0892b04 100644
--- a/tests/rustdoc-gui/search-filter.goml
+++ b/tests/rustdoc-gui/search-filter.goml
@@ -56,7 +56,8 @@ assert-property: ("#crate-search", {"value": "lib2"})
 assert-false: "#results .externcrate"
 
 // Checking that the text for the "title" is correct (the "all crates" comes from the "` isn't bigger than its container (".search-results-title").
+assert-size: ("#crate-search", {"width": 509})
+assert-size: (".search-results-title", {
+    "height": |search_results_title_height|,
+})
 assert-css: ("#search", {"width": "640px"})
+assert: |search_results_title_width| <= 640
 
 // Now checking that the crate filter is working as expected too.
 show-text: true
diff --git a/tests/rustdoc-gui/search-result-go-to-first.goml b/tests/rustdoc-gui/search-result-go-to-first.goml
index f4cfe096386d5..136213c517ebb 100644
--- a/tests/rustdoc-gui/search-result-go-to-first.goml
+++ b/tests/rustdoc-gui/search-result-go-to-first.goml
@@ -16,4 +16,5 @@ assert-css: ("#main-content", {"display": "none"})
 // Now we can check that the feature is working as expected!
 go-to: "file://" + |DOC_PATH| + "/test_docs/index.html?search=struct%3AFoo&go_to_first=true"
 // Waiting for the page to load...
-wait-for-text: (".main-heading h1", "Struct test_docs::FooCopy item path")
+wait-for-text: (".main-heading .rustdoc-breadcrumbs", "test_docs")
+wait-for-text: (".main-heading h1", "Struct FooCopy item path")
diff --git a/tests/rustdoc-gui/settings-button.goml b/tests/rustdoc-gui/settings-button.goml
index c38a537e04782..d78034769e245 100644
--- a/tests/rustdoc-gui/settings-button.goml
+++ b/tests/rustdoc-gui/settings-button.goml
@@ -11,8 +11,8 @@ define-function: (
         call-function: ("switch-theme", {"theme": |theme|})
         assert-css: ("#settings-menu > a::before", {
             "filter": |filter|,
-            "width": "22px",
-            "height": "22px",
+            "width": "18px",
+            "height": "18px",
         })
     }
 )
@@ -23,9 +23,9 @@ call-function: ("check-image", {
 })
 call-function: ("check-image", {
     "theme": "dark",
-    "filter": "none",
+    "filter": "invert(0.65)",
 })
 call-function: ("check-image", {
     "theme": "light",
-    "filter": "none",
+    "filter": "invert(0.35)",
 })
diff --git a/tests/rustdoc-gui/settings.goml b/tests/rustdoc-gui/settings.goml
index 3f4f2946bf5af..1d93c07f9ec5c 100644
--- a/tests/rustdoc-gui/settings.goml
+++ b/tests/rustdoc-gui/settings.goml
@@ -305,6 +305,7 @@ wait-for-css: ("#help-button .popover", {"display": "block"})
 // Now we go to the settings page to check that the CSS is loaded as expected.
 go-to: "file://" + |DOC_PATH| + "/settings.html"
 wait-for: "#settings"
+assert-false: "#settings-menu"
 assert-css: (".setting-radio", {"cursor": "pointer"})
 
 assert-attribute-false: ("#settings", {"class": "popover"}, CONTAINS)
@@ -324,6 +325,5 @@ javascript: true
 show-text: true
 reload:
 set-window-size: (300, 1000)
-click: "#settings-menu"
 wait-for: "#settings"
 assert-css: (".setting-radio", {"cursor": "pointer"})
diff --git a/tests/rustdoc-gui/shortcuts.goml b/tests/rustdoc-gui/shortcuts.goml
index 2c61ee5428b86..5a6171d6f761a 100644
--- a/tests/rustdoc-gui/shortcuts.goml
+++ b/tests/rustdoc-gui/shortcuts.goml
@@ -13,19 +13,19 @@ press-key: "Escape"
 assert-css: ("#help-button .popover", {"display": "none"})
 // Checking doc collapse and expand.
 // It should be displaying a "-":
-assert-text: ("#toggle-all-docs", "[−]")
+assert-text: ("#toggle-all-docs", "Summary")
 press-key: "-"
-wait-for-text: ("#toggle-all-docs", "[+]")
+wait-for-text: ("#toggle-all-docs", "Show all")
 assert-attribute: ("#toggle-all-docs", {"class": "will-expand"})
 // Pressing it again shouldn't do anything.
 press-key: "-"
-assert-text: ("#toggle-all-docs", "[+]")
+assert-text: ("#toggle-all-docs", "Show all")
 assert-attribute: ("#toggle-all-docs", {"class": "will-expand"})
 // Expanding now.
 press-key: "+"
-wait-for-text: ("#toggle-all-docs", "[−]")
+wait-for-text: ("#toggle-all-docs", "Summary")
 assert-attribute: ("#toggle-all-docs", {"class": ""})
 // Pressing it again shouldn't do anything.
 press-key: "+"
-assert-text: ("#toggle-all-docs", "[−]")
+assert-text: ("#toggle-all-docs", "Summary")
 assert-attribute: ("#toggle-all-docs", {"class": ""})
diff --git a/tests/rustdoc-gui/sidebar-source-code-display.goml b/tests/rustdoc-gui/sidebar-source-code-display.goml
index 67152afbbaa33..c3e02c4e9b409 100644
--- a/tests/rustdoc-gui/sidebar-source-code-display.goml
+++ b/tests/rustdoc-gui/sidebar-source-code-display.goml
@@ -141,7 +141,7 @@ click: "#sidebar-button"
 wait-for-css: (".src .sidebar > *", {"visibility": "hidden"})
 // We scroll to line 117 to change the scroll position.
 scroll-to: '//*[@id="117"]'
-store-value: (y_offset, "2493")
+store-value: (y_offset, "2564")
 assert-window-property: {"pageYOffset": |y_offset|}
 // Expanding the sidebar...
 click: "#sidebar-button"
diff --git a/tests/rustdoc-gui/sidebar.goml b/tests/rustdoc-gui/sidebar.goml
index 7794cdbe9e264..bb7453fdeacf1 100644
--- a/tests/rustdoc-gui/sidebar.goml
+++ b/tests/rustdoc-gui/sidebar.goml
@@ -160,12 +160,12 @@ click: "//ul[@class='block mod']/preceding-sibling::h3/a"
 // PAGE: index.html
 assert-css: ("#modules", {"background-color": "#fdffd3"})
 
-// Finally, assert that the `[+]/[−]` toggle doesn't affect sidebar width.
+// Finally, assert that the Summary toggle doesn't affect sidebar width.
 click: "#toggle-all-docs"
-assert-text: ("#toggle-all-docs", "[+]")
+assert-text: ("#toggle-all-docs", "Show all")
 assert-property: (".sidebar", {"clientWidth": "200"})
 click: "#toggle-all-docs"
-assert-text: ("#toggle-all-docs", "[−]")
+assert-text: ("#toggle-all-docs", "Summary")
 assert-property: (".sidebar", {"clientWidth": "200"})
 
 // Checks that all.html and index.html have their sidebar link in the same place.
diff --git a/tests/rustdoc-gui/source-anchor-scroll.goml b/tests/rustdoc-gui/source-anchor-scroll.goml
index 3508b26a0bf24..166890abe4b36 100644
--- a/tests/rustdoc-gui/source-anchor-scroll.goml
+++ b/tests/rustdoc-gui/source-anchor-scroll.goml
@@ -8,13 +8,13 @@ set-window-size: (600, 800)
 assert-property: ("html", {"scrollTop": "0"})
 
 click: '//a[text() = "barbar" and @href="#5-7"]'
-assert-property: ("html", {"scrollTop": "123"})
+assert-property: ("html", {"scrollTop": "194"})
 click: '//a[text() = "bar" and @href="#28-36"]'
-assert-property: ("html", {"scrollTop": "154"})
+assert-property: ("html", {"scrollTop": "225"})
 click: '//a[normalize-space() = "sub_fn" and @href="#2-4"]'
-assert-property: ("html", {"scrollTop": "51"})
+assert-property: ("html", {"scrollTop": "122"})
 
 // We now check that clicking on lines doesn't change the scroll
 // Extra information: the "sub_fn" function header is on line 1.
 click: '//*[@id="6"]'
-assert-property: ("html", {"scrollTop": "51"})
+assert-property: ("html", {"scrollTop": "122"})
diff --git a/tests/rustdoc-gui/source-code-page.goml b/tests/rustdoc-gui/source-code-page.goml
index 619d2b37d8daf..095354c2f4c1c 100644
--- a/tests/rustdoc-gui/source-code-page.goml
+++ b/tests/rustdoc-gui/source-code-page.goml
@@ -89,9 +89,9 @@ assert-css: (".src-line-numbers", {"text-align": "right"})
 // do anything (and certainly not add a `#NaN` to the URL!).
 go-to: "file://" + |DOC_PATH| + "/src/test_docs/lib.rs.html"
 // We use this assert-position to know where we will click.
-assert-position: ("//*[@id='1']", {"x": 88, "y": 86})
+assert-position: ("//*[@id='1']", {"x": 88, "y": 163})
 // We click on the left of the "1" anchor but still in the "src-line-number" `
`.
-click: (87, 77)
+click: (163, 77)
 assert-document-property: ({"URL": "/lib.rs.html"}, ENDS_WITH)
 
 // Checking the source code sidebar.
@@ -159,19 +159,21 @@ call-function: ("check-sidebar-dir-entry", {
 // Check the search form
 assert-css: ("nav.sub", {"flex-direction": "row"})
 // The goal of this test is to ensure the search input is perfectly centered
-// between the top of the page and the top of the gray code block.
+// between the top of the page and the header.
 // To check this, we maintain the invariant:
 //
 // offsetTop[nav.sub form] = offsetTop[#main-content] - offsetHeight[nav.sub form] - offsetTop[nav.sub form]
-assert-property: ("nav.sub form", {"offsetTop": 15, "offsetHeight": 34})
-assert-property: ("#main-content", {"offsetTop": 64})
+assert-position: ("nav.sub form", {"y": 15})
+assert-property: ("nav.sub form", {"offsetHeight": 34})
+assert-position: ("h1", {"y": 64})
 // 15 = 64 - 34 - 15
 
 // Now do the same check on moderately-sized, tablet mobile.
 set-window-size: (700, 700)
 assert-css: ("nav.sub", {"flex-direction": "row"})
-assert-property: ("nav.sub form", {"offsetTop": 8, "offsetHeight": 34})
-assert-property: ("#main-content", {"offsetTop": 50})
+assert-position: ("nav.sub form", {"y": 8})
+assert-property: ("nav.sub form", {"offsetHeight": 34})
+assert-position: ("h1", {"y": 50})
 // 8 = 50 - 34 - 8
 
 // Check the sidebar directory entries have a marker and spacing (tablet).
diff --git a/tests/rustdoc-gui/src/theme_css/custom-theme.css b/tests/rustdoc-gui/src/theme_css/custom-theme.css
index 366f09f22b230..5ea5009fb2e0a 100644
--- a/tests/rustdoc-gui/src/theme_css/custom-theme.css
+++ b/tests/rustdoc-gui/src/theme_css/custom-theme.css
@@ -52,6 +52,8 @@
 	--search-tab-button-selected-border-top-color: #0089ff;
 	--search-tab-button-selected-background: #fff;
 	--settings-menu-filter: none;
+	--settings-menu-hover-filter: invert(35%);
+	--settings-menu-disabled-filter: invert(14%) sepia(11%) saturate(14%) hue-rotate(337deg);
 	--stab-background-color: #fff5d6;
 	--stab-code-color: #000;
 	--code-highlight-kw-color: #8959a8;
diff --git a/tests/rustdoc-gui/toggle-click-deadspace.goml b/tests/rustdoc-gui/toggle-click-deadspace.goml
index 37bc3f7c37270..caca1b61493d2 100644
--- a/tests/rustdoc-gui/toggle-click-deadspace.goml
+++ b/tests/rustdoc-gui/toggle-click-deadspace.goml
@@ -12,4 +12,5 @@ assert-attribute-false: (".impl-items .toggle", {"open": ""})
 
 // Click the "Trait" part of "impl Trait" and verify it navigates.
 click: "#impl-Trait-for-Foo h3 a:first-of-type"
-assert-text: (".main-heading h1", "Trait lib2::TraitCopy item path")
+assert-text: (".main-heading .rustdoc-breadcrumbs", "lib2")
+assert-text: (".main-heading h1", "Trait TraitCopy item path")
diff --git a/tests/rustdoc-gui/toggle-docs-mobile.goml b/tests/rustdoc-gui/toggle-docs-mobile.goml
index b69aa6e30ca0b..59233d94fcc45 100644
--- a/tests/rustdoc-gui/toggle-docs-mobile.goml
+++ b/tests/rustdoc-gui/toggle-docs-mobile.goml
@@ -3,12 +3,12 @@
 go-to: "file://" + |DOC_PATH| + "/test_docs/struct.Foo.html"
 set-window-size: (433, 600)
 assert-attribute: (".top-doc", {"open": ""})
-click: (4, 270) // This is the position of the top doc comment toggle
+click: (4, 260) // This is the position of the top doc comment toggle
 assert-attribute-false: (".top-doc", {"open": ""})
-click: (4, 270)
+click: (4, 260)
 assert-attribute: (".top-doc", {"open": ""})
 // To ensure that the toggle isn't over the text, we check that the toggle isn't clicked.
-click: (3, 270)
+click: (3, 260)
 assert-attribute: (".top-doc", {"open": ""})
 
 // Assert the position of the toggle on the top doc block.
@@ -24,10 +24,10 @@ assert-position: (
 // Now we do the same but with a little bigger width
 set-window-size: (600, 600)
 assert-attribute: (".top-doc", {"open": ""})
-click: (4, 270) // New Y position since all search elements are back on one line.
+click: (4, 260) // New Y position since all search elements are back on one line.
 assert-attribute-false: (".top-doc", {"open": ""})
-click: (4, 270)
+click: (4, 260)
 assert-attribute: (".top-doc", {"open": ""})
 // To ensure that the toggle isn't over the text, we check that the toggle isn't clicked.
-click: (3, 270)
+click: (3, 260)
 assert-attribute: (".top-doc", {"open": ""})
diff --git a/tests/rustdoc-gui/toggle-docs.goml b/tests/rustdoc-gui/toggle-docs.goml
index 1235ee4b754ce..4607c604eeb3d 100644
--- a/tests/rustdoc-gui/toggle-docs.goml
+++ b/tests/rustdoc-gui/toggle-docs.goml
@@ -2,12 +2,12 @@
 include: "utils.goml"
 go-to: "file://" + |DOC_PATH| + "/test_docs/index.html"
 assert-attribute: ("#main-content > details.top-doc", {"open": ""})
-assert-text: ("#toggle-all-docs", "[−]")
+assert-text: ("#toggle-all-docs", "Summary")
 click: "#toggle-all-docs"
 wait-for: 50
 // This is now collapsed so there shouldn't be the "open" attribute on details.
 assert-attribute-false: ("#main-content > details.top-doc", {"open": ""})
-assert-text: ("#toggle-all-docs", "[+]")
+assert-text: ("#toggle-all-docs", "Show all")
 assert-css: (
     "#main-content > details.top-doc > summary",
     {"font-family": '"Fira Sans", Arial, NanumBarunGothic, sans-serif'},
@@ -15,12 +15,12 @@ assert-css: (
 click: "#toggle-all-docs"
 // Not collapsed anymore so the "open" attribute should be back.
 wait-for-attribute: ("#main-content > details.top-doc", {"open": ""})
-assert-text: ("#toggle-all-docs", "[−]")
+assert-text: ("#toggle-all-docs", "Summary")
 
 // Check that it works on non-module pages as well.
 go-to: "file://" + |DOC_PATH| + "/test_docs/struct.Foo.html"
 // We first check that everything is visible.
-assert-text: ("#toggle-all-docs", "[−]")
+assert-text: ("#toggle-all-docs", "Summary")
 assert-attribute: ("#implementations-list details.toggle", {"open": ""}, ALL)
 assert-attribute: ("#trait-implementations-list details.toggle", {"open": ""}, ALL)
 assert-attribute-false: (
@@ -31,7 +31,7 @@ assert-attribute-false: (
 
 // We collapse them all.
 click: "#toggle-all-docs"
-wait-for-text: ("#toggle-all-docs", "[+]")
+wait-for-text: ("#toggle-all-docs", "Show all")
 // We check that all 
are collapsed (except for the impl block ones). assert-attribute-false: ("details.toggle:not(.implementors-toggle)", {"open": ""}, ALL) assert-attribute: ("#implementations-list > details.implementors-toggle", {"open": ""}) @@ -43,7 +43,7 @@ assert-attribute-false: ( ) // We open them all again. click: "#toggle-all-docs" -wait-for-text: ("#toggle-all-docs", "[−]") +wait-for-text: ("#toggle-all-docs", "Summary") assert-attribute: ("details.toggle", {"open": ""}, ALL) // Checking the toggles style. diff --git a/tests/rustdoc-gui/type-declation-overflow.goml b/tests/rustdoc-gui/type-declation-overflow.goml index 8df946c6f39ed..4f8fe78ea4dc6 100644 --- a/tests/rustdoc-gui/type-declation-overflow.goml +++ b/tests/rustdoc-gui/type-declation-overflow.goml @@ -51,22 +51,23 @@ store-property: (".mobile-topbar", {"scrollWidth": scrollWidth}) assert-property: (".mobile-topbar", {"clientWidth": |scrollWidth|}) assert-css: (".mobile-topbar h2", {"overflow-x": "hidden"}) -// Check wrapping for top main-heading h1 and out-of-band. -// On desktop, they wrap when too big. +// Check that main heading and toolbar go side-by-side, both on desktop and on mobile. set-window-size: (1100, 800) go-to: "file://" + |DOC_PATH| + "/lib2/too_long/struct.SuperIncrediblyLongLongLongLongLongLongLongGigaGigaGigaMegaLongLongLongStructName.html" -compare-elements-position-false: (".main-heading h1", ".main-heading .out-of-band", ["y"]) +compare-elements-position: (".main-heading h1", ".main-heading rustdoc-toolbar", ["y"]) +compare-elements-position-near-false: (".main-heading h1", ".main-heading rustdoc-toolbar", {"x": 550}) go-to: "file://" + |DOC_PATH| + "/lib2/index.html" -compare-elements-position: (".main-heading h1", ".main-heading .out-of-band", ["y"]) -// make sure there is a gap between them -compare-elements-position-near-false: (".main-heading h1", ".main-heading .out-of-band", {"x": 550}) +compare-elements-position: (".main-heading h1", ".main-heading rustdoc-toolbar", ["y"]) +compare-elements-position-near-false: (".main-heading h1", ".main-heading rustdoc-toolbar", {"x": 550}) // On mobile, they always wrap. set-window-size: (600, 600) go-to: "file://" + |DOC_PATH| + "/lib2/too_long/struct.SuperIncrediblyLongLongLongLongLongLongLongGigaGigaGigaMegaLongLongLongStructName.html" -compare-elements-position-false: (".main-heading h1", ".main-heading .out-of-band", ["y"]) +compare-elements-position: (".main-heading h1", ".main-heading rustdoc-toolbar", ["y"]) +compare-elements-position-near-false: (".main-heading h1", ".main-heading rustdoc-toolbar", {"x": 200}) go-to: "file://" + |DOC_PATH| + "/lib2/index.html" -compare-elements-position-false: (".main-heading h1", ".main-heading .out-of-band", ["y"]) +compare-elements-position: (".main-heading h1", ".main-heading rustdoc-toolbar", ["y"]) +compare-elements-position-near-false: (".main-heading h1", ".main-heading rustdoc-toolbar", {"x": 200}) // Now we will check that the scrolling is working. // First on an item with "hidden methods". diff --git a/tests/rustdoc-js-std/path-maxeditdistance.js b/tests/rustdoc-js-std/path-maxeditdistance.js index 822389aaa4ffd..632df658f756d 100644 --- a/tests/rustdoc-js-std/path-maxeditdistance.js +++ b/tests/rustdoc-js-std/path-maxeditdistance.js @@ -11,7 +11,7 @@ const EXPECTED = [ { 'path': 'std::vec::IntoIter', 'name': 'into_iter' }, { 'path': 'std::vec::ExtractIf', 'name': 'into_iter' }, { 'path': 'std::vec::Splice', 'name': 'into_iter' }, - { 'path': 'std::collections::VecDeque', 'name': 'into_iter' }, + { 'path': 'std::collections::vec_deque::VecDeque', 'name': 'into_iter' }, ], }, { @@ -25,10 +25,10 @@ const EXPECTED = [ { 'path': 'std::vec::IntoIter', 'name': 'into_iter' }, { 'path': 'std::vec::ExtractIf', 'name': 'into_iter' }, { 'path': 'std::vec::Splice', 'name': 'into_iter' }, - { 'path': 'std::collections::VecDeque', 'name': 'iter' }, - { 'path': 'std::collections::VecDeque', 'name': 'iter_mut' }, - { 'path': 'std::collections::VecDeque', 'name': 'from_iter' }, - { 'path': 'std::collections::VecDeque', 'name': 'into_iter' }, + { 'path': 'std::collections::vec_deque::VecDeque', 'name': 'iter' }, + { 'path': 'std::collections::vec_deque::VecDeque', 'name': 'iter_mut' }, + { 'path': 'std::collections::vec_deque::VecDeque', 'name': 'from_iter' }, + { 'path': 'std::collections::vec_deque::VecDeque', 'name': 'into_iter' }, ], }, { diff --git a/tests/rustdoc-json/reexport/same_name_different_types.rs b/tests/rustdoc-json/reexport/same_name_different_types.rs index e9bc4a5ac406d..760e2c6f77502 100644 --- a/tests/rustdoc-json/reexport/same_name_different_types.rs +++ b/tests/rustdoc-json/reexport/same_name_different_types.rs @@ -17,6 +17,6 @@ pub mod nested { //@ ismany "$.index[*].inner[?(@.use.name == 'Bar')].use.id" $foo_fn $foo_struct //@ count "$.index[*].inner[?(@.use.name == 'Foo')]" 2 -pub use nested::Foo; //@ count "$.index[*].inner[?(@.use.name == 'Bar')]" 2 pub use Foo as Bar; +pub use nested::Foo; diff --git a/tests/rustdoc-json/type/inherent_associated_type_bound.rs b/tests/rustdoc-json/type/inherent_associated_type_bound.rs index d0a88b1970fe3..cb008291b7226 100644 --- a/tests/rustdoc-json/type/inherent_associated_type_bound.rs +++ b/tests/rustdoc-json/type/inherent_associated_type_bound.rs @@ -16,5 +16,8 @@ pub struct Carrier<'a>(&'a ()); pub fn user(_: for<'b> fn(Carrier<'b>::Focus)) {} impl<'a> Carrier<'a> { - pub type Focus = &'a mut T where T: 'a; + pub type Focus + = &'a mut T + where + T: 'a; } diff --git a/tests/rustdoc-ui/doctest/non-local-defs-impl.rs b/tests/rustdoc-ui/doctest/non-local-defs-impl.rs index 37c80bc1f2728..b1ab5323a2bc8 100644 --- a/tests/rustdoc-ui/doctest/non-local-defs-impl.rs +++ b/tests/rustdoc-ui/doctest/non-local-defs-impl.rs @@ -15,7 +15,10 @@ /// # use pub_trait::Trait; /// /// struct Local; -/// impl Trait for &Local {} +/// +/// fn foo() { +/// impl Trait for &Local {} +/// } /// ``` /// /// But this shoudln't produce a warning: diff --git a/tests/rustdoc-ui/doctest/non-local-defs-impl.stdout b/tests/rustdoc-ui/doctest/non-local-defs-impl.stdout index 27797e22f8ecb..f39d2c2608b88 100644 --- a/tests/rustdoc-ui/doctest/non-local-defs-impl.stdout +++ b/tests/rustdoc-ui/doctest/non-local-defs-impl.stdout @@ -1,24 +1,23 @@ running 2 tests test $DIR/non-local-defs-impl.rs - doctest (line 13) - compile ... FAILED -test $DIR/non-local-defs-impl.rs - doctest (line 22) - compile ... ok +test $DIR/non-local-defs-impl.rs - doctest (line 25) - compile ... ok failures: ---- $DIR/non-local-defs-impl.rs - doctest (line 13) stdout ---- error: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/non-local-defs-impl.rs:18:1 + --> $DIR/non-local-defs-impl.rs:20:5 | -LL | impl Trait for &Local {} - | ^^^^^-----^^^^^------ - | | | - | | `&'_ Local` is not local - | | help: remove `&` to make the `impl` local - | `Trait` is not local +LL | fn foo() { + | -------- move the `impl` block outside of this function `foo` and up 3 bodies +LL | impl Trait for &Local {} + | ^^^^^-----^^^^^^----- + | | | + | | `Local` is not local + | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` - = help: make this doc-test a standalone test with its own `fn main() { ... }` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue note: the lint level is defined here --> $DIR/non-local-defs-impl.rs:11:9 diff --git a/tests/rustdoc-ui/doctest/non_local_defs.rs b/tests/rustdoc-ui/doctest/non_local_defs.rs index 83327eb1e3f49..a2f66c392231a 100644 --- a/tests/rustdoc-ui/doctest/non_local_defs.rs +++ b/tests/rustdoc-ui/doctest/non_local_defs.rs @@ -4,8 +4,6 @@ //@ normalize-stderr-test: "tests/rustdoc-ui/doctest" -> "$$DIR" //@ normalize-stdout-test: "finished in \d+\.\d+s" -> "finished in $$TIME" -#![doc(test(attr(warn(non_local_definitions))))] - //! ``` //! #[macro_export] //! macro_rules! a_macro { () => {} } diff --git a/tests/rustdoc-ui/doctest/non_local_defs.stderr b/tests/rustdoc-ui/doctest/non_local_defs.stderr index 13cd2558793f8..2b47e6b5bc4d5 100644 --- a/tests/rustdoc-ui/doctest/non_local_defs.stderr +++ b/tests/rustdoc-ui/doctest/non_local_defs.stderr @@ -1,5 +1,5 @@ warning: non-local `macro_rules!` definition, `#[macro_export]` macro should be written at top level module - --> $DIR/non_local_defs.rs:11:1 + --> $DIR/non_local_defs.rs:9:1 | LL | macro_rules! a_macro { () => {} } | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -7,11 +7,7 @@ LL | macro_rules! a_macro { () => {} } = help: remove the `#[macro_export]` or make this doc-test a standalone test with its own `fn main() { ... }` = note: a `macro_rules!` definition is non-local if it is nested inside an item and has a `#[macro_export]` attribute = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/non_local_defs.rs:8:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(non_local_definitions)]` on by default warning: 1 warning emitted diff --git a/tests/rustdoc-ui/doctest/non_local_defs.stdout b/tests/rustdoc-ui/doctest/non_local_defs.stdout index 61b4074886e4b..bee195fcdd772 100644 --- a/tests/rustdoc-ui/doctest/non_local_defs.stdout +++ b/tests/rustdoc-ui/doctest/non_local_defs.stdout @@ -1,6 +1,6 @@ running 1 test -test $DIR/non_local_defs.rs - (line 9) ... ok +test $DIR/non_local_defs.rs - (line 7) ... ok test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME diff --git a/tests/rustdoc/const-display.rs b/tests/rustdoc/const-display.rs index ac55a6302f785..a71825d883d6a 100644 --- a/tests/rustdoc/const-display.rs +++ b/tests/rustdoc/const-display.rs @@ -1,8 +1,6 @@ #![crate_name = "foo"] -#![unstable(feature = "humans", - reason = "who ever let humans program computers, we're apparently really bad at it", - issue = "none")] +#![stable(feature = "rust1", since = "1.0.0")] #![feature(foo, foo2)] #![feature(staged_api)] @@ -48,10 +46,18 @@ pub const unsafe fn foo2_gated() -> u32 { 42 } #[rustc_const_stable(feature = "rust1", since = "1.0.0")] pub const unsafe fn bar2_gated() -> u32 { 42 } -//@ has 'foo/fn.bar_not_gated.html' '//pre' 'pub const unsafe fn bar_not_gated() -> u32' -//@ !hasraw - '//span[@class="since"]' -pub const unsafe fn bar_not_gated() -> u32 { 42 } +#[unstable( + feature = "humans", + reason = "who ever let humans program computers, we're apparently really bad at it", + issue = "none", +)] +pub mod unstable { + //@ has 'foo/unstable/fn.bar_not_gated.html' '//pre' 'pub const unsafe fn bar_not_gated() -> u32' + //@ !hasraw - '//span[@class="since"]' + pub const unsafe fn bar_not_gated() -> u32 { 42 } +} +#[stable(feature = "rust1", since = "1.0.0")] pub struct Foo; impl Foo { diff --git a/tests/rustdoc/empty-mod-private.rs b/tests/rustdoc/empty-mod-private.rs index 4e408e3d4240a..5a8638cd5f5cd 100644 --- a/tests/rustdoc/empty-mod-private.rs +++ b/tests/rustdoc/empty-mod-private.rs @@ -2,15 +2,18 @@ //@ has 'empty_mod_private/index.html' '//a[@href="foo/index.html"]' 'foo' //@ hasraw 'empty_mod_private/sidebar-items.js' 'foo' -//@ matches 'empty_mod_private/foo/index.html' '//h1' 'Module empty_mod_private::foo' +//@ matches 'empty_mod_private/foo/index.html' '//h1' 'Module foo' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'empty_mod_private' mod foo {} //@ has 'empty_mod_private/index.html' '//a[@href="bar/index.html"]' 'bar' //@ hasraw 'empty_mod_private/sidebar-items.js' 'bar' -//@ matches 'empty_mod_private/bar/index.html' '//h1' 'Module empty_mod_private::bar' +//@ matches 'empty_mod_private/bar/index.html' '//h1' 'Module bar' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'empty_mod_private' mod bar { //@ has 'empty_mod_private/bar/index.html' '//a[@href="baz/index.html"]' 'baz' //@ hasraw 'empty_mod_private/bar/sidebar-items.js' 'baz' - //@ matches 'empty_mod_private/bar/baz/index.html' '//h1' 'Module empty_mod_private::bar::baz' + //@ matches 'empty_mod_private/bar/baz/index.html' '//h1' 'Module baz' + //@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'empty_mod_private::bar' mod baz {} } diff --git a/tests/rustdoc/empty-mod-public.rs b/tests/rustdoc/empty-mod-public.rs index b5a63525524ce..f06ac69f3ed81 100644 --- a/tests/rustdoc/empty-mod-public.rs +++ b/tests/rustdoc/empty-mod-public.rs @@ -1,14 +1,17 @@ //@ has 'empty_mod_public/index.html' '//a[@href="foo/index.html"]' 'foo' //@ hasraw 'empty_mod_public/sidebar-items.js' 'foo' -//@ matches 'empty_mod_public/foo/index.html' '//h1' 'Module empty_mod_public::foo' +//@ matches 'empty_mod_public/foo/index.html' '//h1' 'Module foo' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'empty_mod_public' pub mod foo {} //@ has 'empty_mod_public/index.html' '//a[@href="bar/index.html"]' 'bar' //@ hasraw 'empty_mod_public/sidebar-items.js' 'bar' -//@ matches 'empty_mod_public/bar/index.html' '//h1' 'Module empty_mod_public::bar' +//@ matches 'empty_mod_public/bar/index.html' '//h1' 'Module bar' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'empty_mod_public' pub mod bar { //@ has 'empty_mod_public/bar/index.html' '//a[@href="baz/index.html"]' 'baz' //@ hasraw 'empty_mod_public/bar/sidebar-items.js' 'baz' - //@ matches 'empty_mod_public/bar/baz/index.html' '//h1' 'Module empty_mod_public::bar::baz' + //@ matches 'empty_mod_public/bar/baz/index.html' '//h1' 'Module baz' + //@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'empty_mod_public::bar' pub mod baz {} } diff --git a/tests/rustdoc/html-no-source.rs b/tests/rustdoc/html-no-source.rs index 100ab0031f787..248afbd00eff9 100644 --- a/tests/rustdoc/html-no-source.rs +++ b/tests/rustdoc/html-no-source.rs @@ -11,14 +11,14 @@ //@ files 'src/foo' '[]' //@ has foo/fn.foo.html -//@ has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · ' -//@ !has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · source · ' +//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0' +//@ !has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · source' #[stable(feature = "bar", since = "1.0")] pub fn foo() {} //@ has foo/struct.Bar.html -//@ has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · ' -//@ !has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · source · ' +//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0' +//@ !has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · source' #[stable(feature = "bar", since = "1.0")] pub struct Bar; diff --git a/tests/rustdoc/inline_cross/renamed-via-module.rs b/tests/rustdoc/inline_cross/renamed-via-module.rs index bdaf2cf1f620c..8bcdd9f7a39d0 100644 --- a/tests/rustdoc/inline_cross/renamed-via-module.rs +++ b/tests/rustdoc/inline_cross/renamed-via-module.rs @@ -10,15 +10,19 @@ extern crate foo; //@ has - '//a/[@href="struct.DeprecatedStepBy.html"]' "DeprecatedStepBy" //@ has - '//a/[@href="struct.StepBy.html"]' "StepBy" //@ has foo/iter/struct.DeprecatedStepBy.html -//@ has - '//h1' "Struct foo::iter::DeprecatedStepBy" +//@ has - '//h1' "Struct DeprecatedStepBy" +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo::iter' //@ has foo/iter/struct.StepBy.html -//@ has - '//h1' "Struct foo::iter::StepBy" +//@ has - '//h1' "Struct StepBy" +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo::iter' //@ has bar/iter/index.html //@ has - '//a/[@href="struct.DeprecatedStepBy.html"]' "DeprecatedStepBy" //@ has - '//a/[@href="struct.StepBy.html"]' "StepBy" //@ has bar/iter/struct.DeprecatedStepBy.html -//@ has - '//h1' "Struct bar::iter::DeprecatedStepBy" +//@ has - '//h1' "Struct DeprecatedStepBy" +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'bar::iter' //@ has bar/iter/struct.StepBy.html -//@ has - '//h1' "Struct bar::iter::StepBy" +//@ has - '//h1' "Struct StepBy" +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'bar::iter' pub use foo::iter; diff --git a/tests/rustdoc/keyword.rs b/tests/rustdoc/keyword.rs index 0157c35288e87..519e1944bc78a 100644 --- a/tests/rustdoc/keyword.rs +++ b/tests/rustdoc/keyword.rs @@ -6,7 +6,6 @@ //@ has foo/index.html '//a[@href="keyword.match.html"]' 'match' //@ has foo/index.html '//div[@class="sidebar-elems"]//li/a' 'Keywords' //@ has foo/index.html '//div[@class="sidebar-elems"]//li/a/@href' '#keywords' -//@ has foo/keyword.match.html '//a[@class="keyword"]' 'match' //@ has foo/keyword.match.html '//h1' 'Keyword match' //@ has foo/keyword.match.html '//section[@id="main-content"]//div[@class="docblock"]//p' 'this is a test!' //@ has foo/index.html '//a/@href' '../foo/index.html' diff --git a/tests/rustdoc/primitive-reference.rs b/tests/rustdoc/primitive-reference.rs index c12d65ee0c578..bd6b2a32f754f 100644 --- a/tests/rustdoc/primitive-reference.rs +++ b/tests/rustdoc/primitive-reference.rs @@ -8,7 +8,6 @@ //@ has - '//div[@class="sidebar-elems"]//li/a' 'Primitive Types' //@ has - '//div[@class="sidebar-elems"]//li/a/@href' '#primitives' //@ has foo/primitive.reference.html -//@ has - '//a[@class="primitive"]' 'reference' //@ has - '//h1' 'Primitive Type reference' //@ has - '//section[@id="main-content"]//div[@class="docblock"]//p' 'this is a test!' diff --git a/tests/rustdoc/primitive-slice-auto-trait.rs b/tests/rustdoc/primitive-slice-auto-trait.rs index a877b73cf9f86..e78d1d9461421 100644 --- a/tests/rustdoc/primitive-slice-auto-trait.rs +++ b/tests/rustdoc/primitive-slice-auto-trait.rs @@ -3,8 +3,7 @@ #![crate_name = "foo"] #![feature(rustc_attrs)] -//@ has foo/primitive.slice.html '//a[@class="primitive"]' 'slice' -//@ has - '//h1' 'Primitive Type slice' +//@ has foo/primitive.slice.html '//h1' 'Primitive Type slice' //@ has - '//section[@id="main-content"]//div[@class="docblock"]//p' 'this is a test!' //@ has - '//h2[@id="synthetic-implementations"]' 'Auto Trait Implementations' //@ has - '//div[@id="synthetic-implementations-list"]//h3' 'impl Send for [T]where T: Send' diff --git a/tests/rustdoc/primitive-tuple-auto-trait.rs b/tests/rustdoc/primitive-tuple-auto-trait.rs index 060c4ecfbdc1d..045478e6b4f8c 100644 --- a/tests/rustdoc/primitive-tuple-auto-trait.rs +++ b/tests/rustdoc/primitive-tuple-auto-trait.rs @@ -3,8 +3,7 @@ #![crate_name = "foo"] #![feature(rustc_attrs)] -//@ has foo/primitive.tuple.html '//a[@class="primitive"]' 'tuple' -//@ has - '//h1' 'Primitive Type tuple' +//@ has foo/primitive.tuple.html '//h1' 'Primitive Type tuple' //@ has - '//section[@id="main-content"]//div[@class="docblock"]//p' 'this is a test!' //@ has - '//h2[@id="synthetic-implementations"]' 'Auto Trait Implementations' //@ has - '//div[@id="synthetic-implementations-list"]//h3' 'Send' diff --git a/tests/rustdoc/primitive-unit-auto-trait.rs b/tests/rustdoc/primitive-unit-auto-trait.rs index 7751a2bf1d043..6cae094c21c81 100644 --- a/tests/rustdoc/primitive-unit-auto-trait.rs +++ b/tests/rustdoc/primitive-unit-auto-trait.rs @@ -3,8 +3,7 @@ #![crate_name = "foo"] #![feature(rustc_attrs)] -//@ has foo/primitive.unit.html '//a[@class="primitive"]' 'unit' -//@ has - '//h1' 'Primitive Type unit' +//@ has foo/primitive.unit.html '//h1' 'Primitive Type unit' //@ has - '//section[@id="main-content"]//div[@class="docblock"]//p' 'this is a test!' //@ has - '//h2[@id="synthetic-implementations"]' 'Auto Trait Implementations' //@ has - '//div[@id="synthetic-implementations-list"]//h3' 'impl Send for ()' diff --git a/tests/rustdoc/source-version-separator.rs b/tests/rustdoc/source-version-separator.rs index a998c538eed74..9709bbe3c7181 100644 --- a/tests/rustdoc/source-version-separator.rs +++ b/tests/rustdoc/source-version-separator.rs @@ -3,7 +3,7 @@ #![feature(staged_api)] //@ has foo/trait.Bar.html -//@ has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · source · ' +//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · source' #[stable(feature = "bar", since = "1.0")] pub trait Bar { //@ has - '//*[@id="tymethod.foo"]/*[@class="rightside"]' '3.0.0 · source' @@ -14,7 +14,7 @@ pub trait Bar { //@ has - '//div[@id="implementors-list"]//*[@class="rightside"]' '4.0.0 · source' //@ has foo/struct.Foo.html -//@ has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · source · ' +//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · source' #[stable(feature = "baz", since = "1.0")] pub struct Foo; diff --git a/tests/rustdoc/stability.rs b/tests/rustdoc/stability.rs index 270da822c009b..de855b43ba538 100644 --- a/tests/rustdoc/stability.rs +++ b/tests/rustdoc/stability.rs @@ -1,6 +1,6 @@ #![feature(staged_api)] -#![unstable(feature = "test", issue = "none")] +#![stable(feature = "rust1", since = "1.0.0")] //@ has stability/index.html //@ has - '//ul[@class="item-table"]/li[1]//a' AaStable @@ -10,6 +10,7 @@ #[stable(feature = "rust2", since = "2.2.2")] pub struct AaStable; +#[unstable(feature = "test", issue = "none")] pub struct Unstable { //@ has stability/struct.Unstable.html \ // '//span[@class="item-info"]//div[@class="stab unstable"]' \ @@ -21,3 +22,31 @@ pub struct Unstable { #[stable(feature = "rust2", since = "2.2.2")] pub struct ZzStable; + +#[unstable(feature = "unstable", issue = "none")] +pub mod unstable { + //@ !hasraw stability/unstable/struct.Foo.html '//span[@class="since"]' + //@ has - '//div[@class="stab unstable"]' 'experimental' + #[stable(feature = "rust1", since = "1.0.0")] + pub struct Foo; +} + +#[stable(feature = "rust2", since = "2.2.2")] +pub mod stable_later { + //@ has stability/stable_later/struct.Bar.html '//span[@class="since"]' '2.2.2' + #[stable(feature = "rust1", since = "1.0.0")] + pub struct Bar; +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod stable_earlier { + //@ has stability/stable_earlier/struct.Foo.html '//span[@class="since"]' '1.0.0' + #[doc(inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use crate::unstable::Foo; + + //@ has stability/stable_earlier/struct.Bar.html '//span[@class="since"]' '1.0.0' + #[doc(inline)] + #[stable(feature = "rust1", since = "1.0.0")] + pub use crate::stable_later::Bar; +} diff --git a/tests/rustdoc/titles.rs b/tests/rustdoc/titles.rs index bdf950b0a6225..922068adc5927 100644 --- a/tests/rustdoc/titles.rs +++ b/tests/rustdoc/titles.rs @@ -5,53 +5,65 @@ //@ matches 'foo/index.html' '//div[@class="sidebar-crate"]/h2/a' 'foo' //@ count 'foo/index.html' '//h2[@class="location"]' 0 -//@ matches 'foo/foo_mod/index.html' '//h1' 'Module foo::foo_mod' -//@ matches 'foo/foo_mod/index.html' '//h2[@class="location"]' 'Module foo_mod' +//@ matches 'foo/foo_mod/index.html' '//h1' 'Module foo_mod' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' +//@ matches - '//h2[@class="location"]' 'Module foo_mod' pub mod foo_mod { pub struct __Thing {} } extern "C" { - //@ matches 'foo/fn.foo_ffn.html' '//h1' 'Function foo::foo_ffn' + //@ matches 'foo/fn.foo_ffn.html' '//h1' 'Function foo_ffn' + //@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' pub fn foo_ffn(); } -//@ matches 'foo/fn.foo_fn.html' '//h1' 'Function foo::foo_fn' +//@ matches 'foo/fn.foo_fn.html' '//h1' 'Function foo_fn' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' pub fn foo_fn() {} -//@ matches 'foo/trait.FooTrait.html' '//h1' 'Trait foo::FooTrait' -//@ matches 'foo/trait.FooTrait.html' '//h2[@class="location"]' 'FooTrait' +//@ matches 'foo/trait.FooTrait.html' '//h1' 'Trait FooTrait' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' +//@ matches - '//h2[@class="location"]' 'FooTrait' pub trait FooTrait {} -//@ matches 'foo/struct.FooStruct.html' '//h1' 'Struct foo::FooStruct' -//@ matches 'foo/struct.FooStruct.html' '//h2[@class="location"]' 'FooStruct' +//@ matches 'foo/struct.FooStruct.html' '//h1' 'Struct FooStruct' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' +//@ matches - '//h2[@class="location"]' 'FooStruct' pub struct FooStruct; -//@ matches 'foo/enum.FooEnum.html' '//h1' 'Enum foo::FooEnum' -//@ matches 'foo/enum.FooEnum.html' '//h2[@class="location"]' 'FooEnum' +//@ matches 'foo/enum.FooEnum.html' '//h1' 'Enum FooEnum' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' +//@ matches - '//h2[@class="location"]' 'FooEnum' pub enum FooEnum {} -//@ matches 'foo/type.FooType.html' '//h1' 'Type Alias foo::FooType' -//@ matches 'foo/type.FooType.html' '//h2[@class="location"]' 'FooType' +//@ matches 'foo/type.FooType.html' '//h1' 'Type Alias FooType' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' +//@ matches - '//h2[@class="location"]' 'FooType' pub type FooType = FooStruct; -//@ matches 'foo/macro.foo_macro.html' '//h1' 'Macro foo::foo_macro' +//@ matches 'foo/macro.foo_macro.html' '//h1' 'Macro foo_macro' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' #[macro_export] macro_rules! foo_macro { () => {}; } //@ matches 'foo/primitive.bool.html' '//h1' 'Primitive Type bool' +//@ count - '//*[@class="rustdoc-breadcrumbs"]' 0 #[rustc_doc_primitive = "bool"] mod bool {} -//@ matches 'foo/static.FOO_STATIC.html' '//h1' 'Static foo::FOO_STATIC' +//@ matches 'foo/static.FOO_STATIC.html' '//h1' 'Static FOO_STATIC' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' pub static FOO_STATIC: FooStruct = FooStruct; extern "C" { - //@ matches 'foo/static.FOO_FSTATIC.html' '//h1' 'Static foo::FOO_FSTATIC' + //@ matches 'foo/static.FOO_FSTATIC.html' '//h1' 'Static FOO_FSTATIC' + //@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' pub static FOO_FSTATIC: FooStruct; } -//@ matches 'foo/constant.FOO_CONSTANT.html' '//h1' 'Constant foo::FOO_CONSTANT' +//@ matches 'foo/constant.FOO_CONSTANT.html' '//h1' 'Constant FOO_CONSTANT' +//@ matches - '//*[@class="rustdoc-breadcrumbs"]' 'foo' pub const FOO_CONSTANT: FooStruct = FooStruct; diff --git a/tests/rustdoc/version-separator-without-source.rs b/tests/rustdoc/version-separator-without-source.rs index e439681484c36..7cd1780f1d30e 100644 --- a/tests/rustdoc/version-separator-without-source.rs +++ b/tests/rustdoc/version-separator-without-source.rs @@ -4,14 +4,14 @@ #![crate_name = "foo"] //@ has foo/fn.foo.html -//@ has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · ' -//@ !has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · source · ' +//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0' +//@ !has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · source' #[stable(feature = "bar", since = "1.0")] pub fn foo() {} //@ has foo/struct.Bar.html -//@ has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · ' -//@ !has - '//div[@class="main-heading"]/*[@class="out-of-band"]' '1.0.0 · source · ' +//@ has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0' +//@ !has - '//div[@class="main-heading"]/*[@class="sub-heading"]' '1.0.0 · source' #[stable(feature = "bar", since = "1.0")] pub struct Bar; diff --git a/tests/ui/associated-type-bounds/return-type-notation/bad-inputs-and-output.rs b/tests/ui/associated-type-bounds/return-type-notation/bad-inputs-and-output.rs index af64901ace022..f00aaec1a8c2c 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/bad-inputs-and-output.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/bad-inputs-and-output.rs @@ -1,7 +1,6 @@ //@ edition: 2021 #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait { async fn method() {} diff --git a/tests/ui/associated-type-bounds/return-type-notation/bad-inputs-and-output.stderr b/tests/ui/associated-type-bounds/return-type-notation/bad-inputs-and-output.stderr index 6808147008756..c6b9f3eff90ec 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/bad-inputs-and-output.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/bad-inputs-and-output.stderr @@ -1,66 +1,57 @@ error[E0575]: expected associated type, found associated function `Trait::method` - --> $DIR/bad-inputs-and-output.rs:28:36 + --> $DIR/bad-inputs-and-output.rs:27:36 | LL | fn foo_qualified() where ::method(i32): Send {} | ^^^^^^^^^^^^^^^^^^^^^^^^^ not a associated type error[E0575]: expected associated type, found associated function `Trait::method` - --> $DIR/bad-inputs-and-output.rs:31:36 + --> $DIR/bad-inputs-and-output.rs:30:36 | LL | fn bar_qualified() where ::method() -> (): Send {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not a associated type error[E0575]: expected associated type, found associated function `Trait::method` - --> $DIR/bad-inputs-and-output.rs:34:36 + --> $DIR/bad-inputs-and-output.rs:33:36 | LL | fn baz_qualified() where ::method(): Send {} | ^^^^^^^^^^^^^^^^^^^^^^ not a associated type -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/bad-inputs-and-output.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: argument types not allowed with return type notation - --> $DIR/bad-inputs-and-output.rs:10:23 + --> $DIR/bad-inputs-and-output.rs:9:23 | LL | fn foo>() {} | ^^^^^ help: remove the input types: `()` error: return type not allowed with return type notation - --> $DIR/bad-inputs-and-output.rs:13:25 + --> $DIR/bad-inputs-and-output.rs:12:25 | LL | fn bar (): Send>>() {} | ^^^^^^ help: remove the return type error: return type notation arguments must be elided with `..` - --> $DIR/bad-inputs-and-output.rs:16:23 + --> $DIR/bad-inputs-and-output.rs:15:23 | LL | fn baz>() {} | ^^ help: add `..`: `(..)` error: argument types not allowed with return type notation - --> $DIR/bad-inputs-and-output.rs:19:40 + --> $DIR/bad-inputs-and-output.rs:18:40 | LL | fn foo_path() where T::method(i32): Send {} | ^^^^^ help: remove the input types: `()` error: return type not allowed with return type notation - --> $DIR/bad-inputs-and-output.rs:22:42 + --> $DIR/bad-inputs-and-output.rs:21:42 | LL | fn bar_path() where T::method() -> (): Send {} | ^^^^^^ help: remove the return type error: return type notation arguments must be elided with `..` - --> $DIR/bad-inputs-and-output.rs:25:40 + --> $DIR/bad-inputs-and-output.rs:24:40 | LL | fn baz_path() where T::method(): Send {} | ^^ help: add `..`: `(..)` -error: aborting due to 9 previous errors; 1 warning emitted +error: aborting due to 9 previous errors For more information about this error, try `rustc --explain E0575`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/bare-path.rs b/tests/ui/associated-type-bounds/return-type-notation/bare-path.rs index 185c05236332b..2bbeb62b922cb 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/bare-path.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/bare-path.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Tr { const CONST: usize; diff --git a/tests/ui/associated-type-bounds/return-type-notation/bare-path.stderr b/tests/ui/associated-type-bounds/return-type-notation/bare-path.stderr index dca2bdeab0a7d..913f84b924c28 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/bare-path.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/bare-path.stderr @@ -1,23 +1,14 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/bare-path.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: return type notation not allowed in this position yet - --> $DIR/bare-path.rs:15:23 + --> $DIR/bare-path.rs:14:23 | LL | let _ = T::CONST::(..); | ^^^^ error: return type notation not allowed in this position yet - --> $DIR/bare-path.rs:17:12 + --> $DIR/bare-path.rs:16:12 | LL | let _: T::method(..); | ^^^^^^^^^^^^^ -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 2 previous errors diff --git a/tests/ui/associated-type-bounds/return-type-notation/basic.rs b/tests/ui/associated-type-bounds/return-type-notation/basic.rs index be489a19a7ad2..cb5872dff444c 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/basic.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/basic.rs @@ -3,7 +3,6 @@ //@ [with] check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Foo { async fn method() -> Result<(), ()>; diff --git a/tests/ui/associated-type-bounds/return-type-notation/basic.with.stderr b/tests/ui/associated-type-bounds/return-type-notation/basic.with.stderr deleted file mode 100644 index 9d4bb356caa8b..0000000000000 --- a/tests/ui/associated-type-bounds/return-type-notation/basic.with.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/basic.rs:5:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/associated-type-bounds/return-type-notation/basic.without.stderr b/tests/ui/associated-type-bounds/return-type-notation/basic.without.stderr index e9fd8503296e9..110d2a0058310 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/basic.without.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/basic.without.stderr @@ -1,29 +1,20 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/basic.rs:5:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: future cannot be sent between threads safely - --> $DIR/basic.rs:23:13 + --> $DIR/basic.rs:22:13 | LL | is_send(foo::()); | ^^^^^^^^^^ future returned by `foo` is not `Send` | = help: within `impl Future>`, the trait `Send` is not implemented for `impl Future> { ::method(..) }`, which is required by `impl Future>: Send` note: future is not `Send` as it awaits another future which is not `Send` - --> $DIR/basic.rs:13:5 + --> $DIR/basic.rs:12:5 | LL | T::method().await?; | ^^^^^^^^^^^ await occurs here on type `impl Future> { ::method(..) }`, which is not `Send` note: required by a bound in `is_send` - --> $DIR/basic.rs:17:20 + --> $DIR/basic.rs:16:20 | LL | fn is_send(_: impl Send) {} | ^^^^ required by this bound in `is_send` -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 1 previous error diff --git a/tests/ui/associated-type-bounds/return-type-notation/display.rs b/tests/ui/associated-type-bounds/return-type-notation/display.rs index c5be2ca00ea1c..2d613b71c55d2 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/display.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/display.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait {} fn needs_trait(_: impl Trait) {} diff --git a/tests/ui/associated-type-bounds/return-type-notation/display.stderr b/tests/ui/associated-type-bounds/return-type-notation/display.stderr index 4915ec1aa8315..b895d79695272 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/display.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/display.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/display.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0277]: the trait bound `impl Sized { ::method(..) }: Trait` is not satisfied - --> $DIR/display.rs:15:17 + --> $DIR/display.rs:14:17 | LL | needs_trait(T::method()); | ----------- ^^^^^^^^^^^ the trait `Trait` is not implemented for `impl Sized { ::method(..) }` @@ -16,13 +7,13 @@ LL | needs_trait(T::method()); | required by a bound introduced by this call | note: required by a bound in `needs_trait` - --> $DIR/display.rs:5:24 + --> $DIR/display.rs:4:24 | LL | fn needs_trait(_: impl Trait) {} | ^^^^^ required by this bound in `needs_trait` error[E0277]: the trait bound `impl Sized { ::method_with_lt(..) }: Trait` is not satisfied - --> $DIR/display.rs:17:17 + --> $DIR/display.rs:16:17 | LL | needs_trait(T::method_with_lt()); | ----------- ^^^^^^^^^^^^^^^^^^^ the trait `Trait` is not implemented for `impl Sized { ::method_with_lt(..) }` @@ -30,13 +21,13 @@ LL | needs_trait(T::method_with_lt()); | required by a bound introduced by this call | note: required by a bound in `needs_trait` - --> $DIR/display.rs:5:24 + --> $DIR/display.rs:4:24 | LL | fn needs_trait(_: impl Trait) {} | ^^^^^ required by this bound in `needs_trait` error[E0277]: the trait bound `impl Sized: Trait` is not satisfied - --> $DIR/display.rs:19:17 + --> $DIR/display.rs:18:17 | LL | needs_trait(T::method_with_ty()); | ----------- ^^^^^^^^^^^^^^^^^^^ the trait `Trait` is not implemented for `impl Sized` @@ -44,18 +35,18 @@ LL | needs_trait(T::method_with_ty()); | required by a bound introduced by this call | help: this trait has no implementations, consider adding one - --> $DIR/display.rs:4:1 + --> $DIR/display.rs:3:1 | LL | trait Trait {} | ^^^^^^^^^^^ note: required by a bound in `needs_trait` - --> $DIR/display.rs:5:24 + --> $DIR/display.rs:4:24 | LL | fn needs_trait(_: impl Trait) {} | ^^^^^ required by this bound in `needs_trait` error[E0277]: the trait bound `impl Sized: Trait` is not satisfied - --> $DIR/display.rs:21:17 + --> $DIR/display.rs:20:17 | LL | needs_trait(T::method_with_ct()); | ----------- ^^^^^^^^^^^^^^^^^^^ the trait `Trait` is not implemented for `impl Sized` @@ -63,16 +54,16 @@ LL | needs_trait(T::method_with_ct()); | required by a bound introduced by this call | help: this trait has no implementations, consider adding one - --> $DIR/display.rs:4:1 + --> $DIR/display.rs:3:1 | LL | trait Trait {} | ^^^^^^^^^^^ note: required by a bound in `needs_trait` - --> $DIR/display.rs:5:24 + --> $DIR/display.rs:4:24 | LL | fn needs_trait(_: impl Trait) {} | ^^^^^ required by this bound in `needs_trait` -error: aborting due to 4 previous errors; 1 warning emitted +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/equality.rs b/tests/ui/associated-type-bounds/return-type-notation/equality.rs index 95c16fa1e3f84..cff0df58b7496 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/equality.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/equality.rs @@ -1,7 +1,6 @@ //@ edition: 2021 #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete use std::future::Future; diff --git a/tests/ui/associated-type-bounds/return-type-notation/equality.stderr b/tests/ui/associated-type-bounds/return-type-notation/equality.stderr index d76b1bd1c0510..870f17ee70d2e 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/equality.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/equality.stderr @@ -1,17 +1,8 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/equality.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: return type notation is not allowed to use type equality - --> $DIR/equality.rs:12:18 + --> $DIR/equality.rs:11:18 | LL | fn test>>>() {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 1 previous error diff --git a/tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.rs b/tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.rs index d4f21f47c6c64..c6ae6690c72f5 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.rs @@ -1,7 +1,6 @@ //@ check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait<'a> { fn late<'b>(&'b self, _: &'a ()) -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.stderr b/tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.stderr deleted file mode 100644 index c67231c07f723..0000000000000 --- a/tests/ui/associated-type-bounds/return-type-notation/higher-ranked-bound-works.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/higher-ranked-bound-works.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/associated-type-bounds/return-type-notation/issue-120208-higher-ranked-const.rs b/tests/ui/associated-type-bounds/return-type-notation/issue-120208-higher-ranked-const.rs index 4d026b7d1d859..69d0b4b1f8ac4 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/issue-120208-higher-ranked-const.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/issue-120208-higher-ranked-const.rs @@ -1,7 +1,6 @@ //@ edition: 2021 #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait HealthCheck { async fn check() -> bool; diff --git a/tests/ui/associated-type-bounds/return-type-notation/issue-120208-higher-ranked-const.stderr b/tests/ui/associated-type-bounds/return-type-notation/issue-120208-higher-ranked-const.stderr index 12f32a75eda32..2abf47f002672 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/issue-120208-higher-ranked-const.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/issue-120208-higher-ranked-const.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/issue-120208-higher-ranked-const.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: return type notation is not allowed for functions that have const parameters - --> $DIR/issue-120208-higher-ranked-const.rs:12:21 + --> $DIR/issue-120208-higher-ranked-const.rs:11:21 | LL | async fn check() -> bool; | -------------- const parameter declared here @@ -16,5 +7,5 @@ LL | async fn check() -> bool; LL | HC: HealthCheck + Send + 'static, | ^^^^^^^^^^^^^^^ -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 1 previous error diff --git a/tests/ui/associated-type-bounds/return-type-notation/missing.rs b/tests/ui/associated-type-bounds/return-type-notation/missing.rs index 3a04a56339ba5..e116ae0ca3bb4 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/missing.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/missing.rs @@ -1,7 +1,6 @@ //@ edition: 2021 #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait { async fn method() {} diff --git a/tests/ui/associated-type-bounds/return-type-notation/missing.stderr b/tests/ui/associated-type-bounds/return-type-notation/missing.stderr index 5cb8e2642f51c..0eb965603439c 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/missing.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/missing.stderr @@ -1,18 +1,9 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/missing.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0220]: associated function `methid` not found for `Trait` - --> $DIR/missing.rs:10:17 + --> $DIR/missing.rs:9:17 | LL | fn bar>() {} | ^^^^^^ help: there is an associated function with a similar name: `method` -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0220`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/namespace-conflict.rs b/tests/ui/associated-type-bounds/return-type-notation/namespace-conflict.rs index 9bdc2d00233e0..8dfc2376fbd4e 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/namespace-conflict.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/namespace-conflict.rs @@ -2,7 +2,6 @@ #![allow(non_camel_case_types)] #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Foo { type test; diff --git a/tests/ui/associated-type-bounds/return-type-notation/namespace-conflict.stderr b/tests/ui/associated-type-bounds/return-type-notation/namespace-conflict.stderr deleted file mode 100644 index f4ece074b2856..0000000000000 --- a/tests/ui/associated-type-bounds/return-type-notation/namespace-conflict.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/namespace-conflict.rs:4:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/associated-type-bounds/return-type-notation/non-rpitit.rs b/tests/ui/associated-type-bounds/return-type-notation/non-rpitit.rs index 35d6dd799c703..0e9dd90095286 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/non-rpitit.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/non-rpitit.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait { fn method() {} diff --git a/tests/ui/associated-type-bounds/return-type-notation/non-rpitit.stderr b/tests/ui/associated-type-bounds/return-type-notation/non-rpitit.stderr index e308c927bf0e8..4d3dac2d168f7 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/non-rpitit.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/non-rpitit.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/non-rpitit.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: return type notation used on function that is not `async` and does not return `impl Trait` - --> $DIR/non-rpitit.rs:8:19 + --> $DIR/non-rpitit.rs:7:19 | LL | fn method() {} | ----------- this function must be `async` or return `impl Trait` @@ -19,7 +10,7 @@ LL | fn bound>() {} = note: function returns `()`, which is not compatible with associated type return bounds error: return type notation used on function that is not `async` and does not return `impl Trait` - --> $DIR/non-rpitit.rs:11:30 + --> $DIR/non-rpitit.rs:10:30 | LL | fn method() {} | ----------- this function must be `async` or return `impl Trait` @@ -29,5 +20,5 @@ LL | fn path() where T: Trait, T::method(..): Send {} | = note: function returns `()`, which is not compatible with associated type return bounds -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 2 previous errors diff --git a/tests/ui/associated-type-bounds/return-type-notation/not-a-method.rs b/tests/ui/associated-type-bounds/return-type-notation/not-a-method.rs index d94ec6b74d9d2..89a414a3bc863 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/not-a-method.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/not-a-method.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete fn function() {} diff --git a/tests/ui/associated-type-bounds/return-type-notation/not-a-method.stderr b/tests/ui/associated-type-bounds/return-type-notation/not-a-method.stderr index 8add2d4629675..ab987ee48e6c8 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/not-a-method.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/not-a-method.stderr @@ -1,49 +1,40 @@ error[E0575]: expected function, found function `function` - --> $DIR/not-a-method.rs:8:5 + --> $DIR/not-a-method.rs:7:5 | LL | function(..): Send, | ^^^^^^^^^^^^ not a function error[E0573]: expected type, found function `function` - --> $DIR/not-a-method.rs:16:5 + --> $DIR/not-a-method.rs:15:5 | LL | function(): Send, | ^^^^^^^^^^ not a type error[E0576]: cannot find function `method` in this scope - --> $DIR/not-a-method.rs:28:5 + --> $DIR/not-a-method.rs:27:5 | LL | method(..): Send, | ^^^^^^ not found in this scope error[E0412]: cannot find type `method` in this scope - --> $DIR/not-a-method.rs:37:5 + --> $DIR/not-a-method.rs:36:5 | LL | method(): Send, | ^^^^^^ not found in this scope -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/not-a-method.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: return type notation not allowed in this position yet - --> $DIR/not-a-method.rs:8:5 + --> $DIR/not-a-method.rs:7:5 | LL | function(..): Send, | ^^^^^^^^^^^^ error: return type notation not allowed in this position yet - --> $DIR/not-a-method.rs:28:5 + --> $DIR/not-a-method.rs:27:5 | LL | method(..): Send, | ^^^^^^^^^^ -error: aborting due to 6 previous errors; 1 warning emitted +error: aborting due to 6 previous errors Some errors have detailed explanations: E0412, E0573, E0575, E0576. For more information about an error, try `rustc --explain E0412`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-ambiguous.rs b/tests/ui/associated-type-bounds/return-type-notation/path-ambiguous.rs index cb42c33e364da..f9aba1754653a 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-ambiguous.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-ambiguous.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait A { fn method() -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-ambiguous.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-ambiguous.stderr index e841049ac66bd..80705424035ce 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-ambiguous.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/path-ambiguous.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-ambiguous.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0221]: ambiguous associated function `method` in bounds of `T` - --> $DIR/path-ambiguous.rs:13:5 + --> $DIR/path-ambiguous.rs:12:5 | LL | fn method() -> impl Sized; | -------------------------- ambiguous `method` from `A` @@ -29,7 +20,7 @@ LL | ::method(..): Send, | ~~~~~~~~~~ error[E0221]: ambiguous associated function `method` in bounds of `T` - --> $DIR/path-ambiguous.rs:22:5 + --> $DIR/path-ambiguous.rs:21:5 | LL | fn method() -> impl Sized; | -------------------------- ambiguous `method` from `A` @@ -49,6 +40,6 @@ help: use fully-qualified syntax to disambiguate LL | ::method(..): Send, | ~~~~~~~~~~ -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0221`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-constrained-in-method.rs b/tests/ui/associated-type-bounds/return-type-notation/path-constrained-in-method.rs index 56abd167fb6b7..d8bdec0910752 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-constrained-in-method.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-constrained-in-method.rs @@ -1,7 +1,6 @@ //@ check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait { fn method() -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-constrained-in-method.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-constrained-in-method.stderr deleted file mode 100644 index 3db033d8cf5ed..0000000000000 --- a/tests/ui/associated-type-bounds/return-type-notation/path-constrained-in-method.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-constrained-in-method.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-higher-ranked.rs b/tests/ui/associated-type-bounds/return-type-notation/path-higher-ranked.rs index a4d8f00537105..8591357dd9eaa 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-higher-ranked.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-higher-ranked.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait A<'a> { fn method() -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-higher-ranked.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-higher-ranked.stderr index 22de6165503a1..2a9a1a1e8994c 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-higher-ranked.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/path-higher-ranked.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-higher-ranked.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0212]: cannot use the associated function of a trait with uninferred generic parameters - --> $DIR/path-higher-ranked.rs:12:5 + --> $DIR/path-higher-ranked.rs:11:5 | LL | T::method(..): Send, | ^^^^^^^^^^^^^ @@ -19,7 +10,7 @@ LL | >::method(..): Send, | ~~~~~~~~~~~~~~ error[E0212]: cannot use the associated function of a trait with uninferred generic parameters - --> $DIR/path-higher-ranked.rs:20:5 + --> $DIR/path-higher-ranked.rs:19:5 | LL | T::method(..): Send, | ^^^^^^^^^^^^^ @@ -29,6 +20,6 @@ help: use a fully qualified path with inferred lifetimes LL | >::method(..): Send, | ~~~~~~~~~~~~~~ -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0212`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-missing.rs b/tests/ui/associated-type-bounds/return-type-notation/path-missing.rs index c1a7b95ca2daa..8cab48bd0c454 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-missing.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-missing.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait A { #[allow(non_camel_case_types)] diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-missing.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-missing.stderr index 0130c3bc61460..edac09db89dae 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-missing.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/path-missing.stderr @@ -1,33 +1,24 @@ error[E0576]: cannot find method or associated constant `method` in trait `A` - --> $DIR/path-missing.rs:11:15 + --> $DIR/path-missing.rs:10:15 | LL | ::method(..): Send, | ^^^^^^ not found in `A` error[E0575]: expected method or associated constant, found associated type `A::bad` - --> $DIR/path-missing.rs:13:5 + --> $DIR/path-missing.rs:12:5 | LL | ::bad(..): Send, | ^^^^^^^^^^^^^^^^^ | = note: can't use a type alias as a constructor -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-missing.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0220]: associated function `method` not found for `T` - --> $DIR/path-missing.rs:20:8 + --> $DIR/path-missing.rs:19:8 | LL | T::method(..): Send, | ^^^^^^ associated function `method` not found -error: aborting due to 3 previous errors; 1 warning emitted +error: aborting due to 3 previous errors Some errors have detailed explanations: E0220, E0575, E0576. For more information about an error, try `rustc --explain E0220`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-no-qself.rs b/tests/ui/associated-type-bounds/return-type-notation/path-no-qself.rs index d2636789c10ab..17a3d0f7af675 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-no-qself.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-no-qself.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait { fn method() -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-no-qself.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-no-qself.stderr index d66b0a109fc17..6dbb5dabc0e43 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-no-qself.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/path-no-qself.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-no-qself.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0223]: ambiguous associated type - --> $DIR/path-no-qself.rs:10:5 + --> $DIR/path-no-qself.rs:9:5 | LL | Trait::method(..): Send, | ^^^^^^^^^^^^^^^^^ @@ -18,6 +9,6 @@ help: if there were a type named `Example` that implemented `Trait`, you could u LL | ::method: Send, | ~~~~~~~~~~~~~~~~~~~~~~~~~~ -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0223`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-non-param-qself.rs b/tests/ui/associated-type-bounds/return-type-notation/path-non-param-qself.rs index b0e6ea852b04d..8107772f151ef 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-non-param-qself.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-non-param-qself.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait { fn method() -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-non-param-qself.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-non-param-qself.stderr index cd1aa9813e351..38202bdbf0727 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-non-param-qself.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/path-non-param-qself.stderr @@ -1,30 +1,21 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-non-param-qself.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0223]: ambiguous associated function - --> $DIR/path-non-param-qself.rs:12:5 + --> $DIR/path-non-param-qself.rs:11:5 | LL | <()>::method(..): Send, | ^^^^^^^^^^^^^^^^ error[E0223]: ambiguous associated function - --> $DIR/path-non-param-qself.rs:14:5 + --> $DIR/path-non-param-qself.rs:13:5 | LL | i32::method(..): Send, | ^^^^^^^^^^^^^^^ error[E0223]: ambiguous associated function - --> $DIR/path-non-param-qself.rs:16:5 + --> $DIR/path-non-param-qself.rs:15:5 | LL | Adt::method(..): Send, | ^^^^^^^^^^^^^^^ -error: aborting due to 3 previous errors; 1 warning emitted +error: aborting due to 3 previous errors For more information about this error, try `rustc --explain E0223`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-self-qself.rs b/tests/ui/associated-type-bounds/return-type-notation/path-self-qself.rs index 0cf84457ba73f..d805556f4c720 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-self-qself.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-self-qself.rs @@ -1,7 +1,6 @@ //@ check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Foo { fn method() -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-self-qself.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-self-qself.stderr deleted file mode 100644 index ab33647583ca3..0000000000000 --- a/tests/ui/associated-type-bounds/return-type-notation/path-self-qself.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-self-qself.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-type-param.rs b/tests/ui/associated-type-bounds/return-type-notation/path-type-param.rs index 693a300eb1d98..6e2355c389b88 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-type-param.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-type-param.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Foo { fn method() -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-type-param.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-type-param.stderr index 0d33d4f97d7ac..67e83060a76b2 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-type-param.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/path-type-param.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-type-param.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: return type notation is not allowed for functions that have type parameters - --> $DIR/path-type-param.rs:10:5 + --> $DIR/path-type-param.rs:9:5 | LL | fn method() -> impl Sized; | - type parameter declared here @@ -17,7 +8,7 @@ LL | ::method(..): Send, | ^^^^^^^^^^^^^^^^^^^^^^ error: return type notation is not allowed for functions that have type parameters - --> $DIR/path-type-param.rs:17:5 + --> $DIR/path-type-param.rs:16:5 | LL | fn method() -> impl Sized; | - type parameter declared here @@ -25,5 +16,5 @@ LL | fn method() -> impl Sized; LL | ::method(..): Send, | ^^^^^^^^^^^^^^^^^^^^^^ -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 2 previous errors diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-unsatisfied.rs b/tests/ui/associated-type-bounds/return-type-notation/path-unsatisfied.rs index a5b0b0e4e251c..c9cb0f953e26b 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-unsatisfied.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-unsatisfied.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait { fn method() -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-unsatisfied.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-unsatisfied.stderr index 7d32a428555e8..95810342d5ae2 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-unsatisfied.stderr +++ b/tests/ui/associated-type-bounds/return-type-notation/path-unsatisfied.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-unsatisfied.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0277]: `*mut ()` cannot be sent between threads safely - --> $DIR/path-unsatisfied.rs:23:12 + --> $DIR/path-unsatisfied.rs:22:12 | LL | fn method() -> impl Sized { | ---------- within this `impl Sized` @@ -18,12 +9,12 @@ LL | test::(); | = help: within `impl Sized`, the trait `Send` is not implemented for `*mut ()`, which is required by `impl Sized: Send` note: required because it appears within the type `impl Sized` - --> $DIR/path-unsatisfied.rs:10:20 + --> $DIR/path-unsatisfied.rs:9:20 | LL | fn method() -> impl Sized { | ^^^^^^^^^^ note: required by a bound in `test` - --> $DIR/path-unsatisfied.rs:18:20 + --> $DIR/path-unsatisfied.rs:17:20 | LL | fn test() | ---- required by a bound in this function @@ -31,6 +22,6 @@ LL | where LL | T::method(..): Send, | ^^^^ required by this bound in `test` -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0277`. diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-works.rs b/tests/ui/associated-type-bounds/return-type-notation/path-works.rs index 027bc89f13e08..87abfc07ee9f2 100644 --- a/tests/ui/associated-type-bounds/return-type-notation/path-works.rs +++ b/tests/ui/associated-type-bounds/return-type-notation/path-works.rs @@ -1,7 +1,6 @@ //@ check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Trait { fn method() -> impl Sized; diff --git a/tests/ui/associated-type-bounds/return-type-notation/path-works.stderr b/tests/ui/associated-type-bounds/return-type-notation/path-works.stderr deleted file mode 100644 index b1ec8069ba0d4..0000000000000 --- a/tests/ui/associated-type-bounds/return-type-notation/path-works.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/path-works.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/async-await/return-type-notation/issue-110963-early.stderr b/tests/ui/async-await/return-type-notation/issue-110963-early.stderr index acad8bd379170..d6c3bd12aee3b 100644 --- a/tests/ui/async-await/return-type-notation/issue-110963-early.stderr +++ b/tests/ui/async-await/return-type-notation/issue-110963-early.stderr @@ -1,12 +1,3 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/issue-110963-early.rs:4:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: implementation of `Send` is not general enough --> $DIR/issue-110963-early.rs:14:5 | @@ -36,5 +27,5 @@ LL | | }); = note: ...but `Send` is actually implemented for the type `impl Future { ::check<'2>(..) }`, for some specific lifetime `'2` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 2 previous errors diff --git a/tests/ui/async-await/return-type-notation/issue-110963-late.rs b/tests/ui/async-await/return-type-notation/issue-110963-late.rs index cb9c0b97f1e99..1f56361f5e50f 100644 --- a/tests/ui/async-await/return-type-notation/issue-110963-late.rs +++ b/tests/ui/async-await/return-type-notation/issue-110963-late.rs @@ -2,7 +2,6 @@ //@ check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait HealthCheck { async fn check(&mut self) -> bool; diff --git a/tests/ui/async-await/return-type-notation/issue-110963-late.stderr b/tests/ui/async-await/return-type-notation/issue-110963-late.stderr deleted file mode 100644 index 9c6966537a73a..0000000000000 --- a/tests/ui/async-await/return-type-notation/issue-110963-late.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/issue-110963-late.rs:4:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.current.stderr b/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.current.stderr deleted file mode 100644 index 4837815fad4ad..0000000000000 --- a/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.current.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/normalizing-self-auto-trait-issue-109924.rs:7:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.next.stderr b/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.next.stderr deleted file mode 100644 index 4837815fad4ad..0000000000000 --- a/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.next.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/normalizing-self-auto-trait-issue-109924.rs:7:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.rs b/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.rs index 24041ed080752..3fbd74eddcbbf 100644 --- a/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.rs +++ b/tests/ui/async-await/return-type-notation/normalizing-self-auto-trait-issue-109924.rs @@ -5,7 +5,6 @@ //@ edition:2021 #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Foo { async fn bar(&self); diff --git a/tests/ui/async-await/return-type-notation/rtn-implied-in-supertrait.rs b/tests/ui/async-await/return-type-notation/rtn-implied-in-supertrait.rs index 2f6e04c385384..fdbeb4f3c8758 100644 --- a/tests/ui/async-await/return-type-notation/rtn-implied-in-supertrait.rs +++ b/tests/ui/async-await/return-type-notation/rtn-implied-in-supertrait.rs @@ -2,7 +2,6 @@ //@ check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete use std::future::Future; diff --git a/tests/ui/async-await/return-type-notation/rtn-implied-in-supertrait.stderr b/tests/ui/async-await/return-type-notation/rtn-implied-in-supertrait.stderr deleted file mode 100644 index 4a52e807bff9e..0000000000000 --- a/tests/ui/async-await/return-type-notation/rtn-implied-in-supertrait.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/rtn-implied-in-supertrait.rs:4:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/async-await/return-type-notation/rtn-in-impl-signature.rs b/tests/ui/async-await/return-type-notation/rtn-in-impl-signature.rs index 1e971d0aea71d..bbdfcf607318b 100644 --- a/tests/ui/async-await/return-type-notation/rtn-in-impl-signature.rs +++ b/tests/ui/async-await/return-type-notation/rtn-in-impl-signature.rs @@ -1,5 +1,4 @@ #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete // Shouldn't ICE when we have a (bad) RTN in an impl header diff --git a/tests/ui/async-await/return-type-notation/rtn-in-impl-signature.stderr b/tests/ui/async-await/return-type-notation/rtn-in-impl-signature.stderr index e061587f49189..2bbf1d504747f 100644 --- a/tests/ui/async-await/return-type-notation/rtn-in-impl-signature.stderr +++ b/tests/ui/async-await/return-type-notation/rtn-in-impl-signature.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/rtn-in-impl-signature.rs:1:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0229]: associated item constraints are not allowed here - --> $DIR/rtn-in-impl-signature.rs:10:17 + --> $DIR/rtn-in-impl-signature.rs:9:17 | LL | impl Super1<'_, bar(..): Send> for () {} | ^^^^^^^^^^^^^ associated item constraint not allowed here @@ -20,7 +11,7 @@ LL + impl Super1<'_> for () {} | error[E0046]: not all trait items implemented, missing: `bar` - --> $DIR/rtn-in-impl-signature.rs:10:1 + --> $DIR/rtn-in-impl-signature.rs:9:1 | LL | fn bar<'b>() -> bool; | --------------------- `bar` from trait @@ -28,7 +19,7 @@ LL | fn bar<'b>() -> bool; LL | impl Super1<'_, bar(..): Send> for () {} | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `bar` in implementation -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 2 previous errors Some errors have detailed explanations: E0046, E0229. For more information about an error, try `rustc --explain E0046`. diff --git a/tests/ui/async-await/return-type-notation/super-method-bound-ambig.rs b/tests/ui/async-await/return-type-notation/super-method-bound-ambig.rs index 452568f3e4695..1db19628fa37d 100644 --- a/tests/ui/async-await/return-type-notation/super-method-bound-ambig.rs +++ b/tests/ui/async-await/return-type-notation/super-method-bound-ambig.rs @@ -1,7 +1,6 @@ //@ edition:2021 #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Super1<'a> { async fn test(); diff --git a/tests/ui/async-await/return-type-notation/super-method-bound-ambig.stderr b/tests/ui/async-await/return-type-notation/super-method-bound-ambig.stderr index 9a6fdd7f2ac6b..e32b07771dc92 100644 --- a/tests/ui/async-await/return-type-notation/super-method-bound-ambig.stderr +++ b/tests/ui/async-await/return-type-notation/super-method-bound-ambig.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/super-method-bound-ambig.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error[E0221]: ambiguous associated function `test` in bounds of `Foo` - --> $DIR/super-method-bound-ambig.rs:25:12 + --> $DIR/super-method-bound-ambig.rs:24:12 | LL | async fn test(); | ---------------- ambiguous `test` from `for<'a> Super1<'a>` @@ -19,6 +10,6 @@ LL | async fn test(); LL | T: Foo, | ^^^^^^^^^^^^^^ ambiguous associated function `test` -error: aborting due to 1 previous error; 1 warning emitted +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0221`. diff --git a/tests/ui/async-await/return-type-notation/super-method-bound.rs b/tests/ui/async-await/return-type-notation/super-method-bound.rs index 1aa8258a09b7d..a1d0307698218 100644 --- a/tests/ui/async-await/return-type-notation/super-method-bound.rs +++ b/tests/ui/async-await/return-type-notation/super-method-bound.rs @@ -2,7 +2,6 @@ //@ check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Super<'a> { async fn test(); diff --git a/tests/ui/async-await/return-type-notation/super-method-bound.stderr b/tests/ui/async-await/return-type-notation/super-method-bound.stderr deleted file mode 100644 index 64fda71c1a1d9..0000000000000 --- a/tests/ui/async-await/return-type-notation/super-method-bound.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/super-method-bound.rs:4:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/async-await/return-type-notation/supertrait-bound.rs b/tests/ui/async-await/return-type-notation/supertrait-bound.rs index 9c74c10b33319..8d73a34ac482f 100644 --- a/tests/ui/async-await/return-type-notation/supertrait-bound.rs +++ b/tests/ui/async-await/return-type-notation/supertrait-bound.rs @@ -1,7 +1,6 @@ //@ check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete and may not be safe to use trait IntFactory { fn stream(&self) -> impl Iterator; diff --git a/tests/ui/async-await/return-type-notation/supertrait-bound.stderr b/tests/ui/async-await/return-type-notation/supertrait-bound.stderr deleted file mode 100644 index eb6917fc7d58c..0000000000000 --- a/tests/ui/async-await/return-type-notation/supertrait-bound.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/supertrait-bound.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/async-await/return-type-notation/ty-or-ct-params.rs b/tests/ui/async-await/return-type-notation/ty-or-ct-params.rs index 06a966df4451a..edb92d8e26588 100644 --- a/tests/ui/async-await/return-type-notation/ty-or-ct-params.rs +++ b/tests/ui/async-await/return-type-notation/ty-or-ct-params.rs @@ -1,7 +1,6 @@ //@ edition: 2021 #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Foo { async fn bar() {} diff --git a/tests/ui/async-await/return-type-notation/ty-or-ct-params.stderr b/tests/ui/async-await/return-type-notation/ty-or-ct-params.stderr index 1c000bc6c3318..0e43d69bddc68 100644 --- a/tests/ui/async-await/return-type-notation/ty-or-ct-params.stderr +++ b/tests/ui/async-await/return-type-notation/ty-or-ct-params.stderr @@ -1,14 +1,5 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/ty-or-ct-params.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - error: return type notation is not allowed for functions that have type parameters - --> $DIR/ty-or-ct-params.rs:14:12 + --> $DIR/ty-or-ct-params.rs:13:12 | LL | async fn bar() {} | - type parameter declared here @@ -17,7 +8,7 @@ LL | T: Foo, | ^^^^^^^^^^^^^ error: return type notation is not allowed for functions that have const parameters - --> $DIR/ty-or-ct-params.rs:14:27 + --> $DIR/ty-or-ct-params.rs:13:27 | LL | async fn baz() {} | -------------- const parameter declared here @@ -25,5 +16,5 @@ LL | async fn baz() {} LL | T: Foo, | ^^^^^^^^^^^^^ -error: aborting due to 2 previous errors; 1 warning emitted +error: aborting due to 2 previous errors diff --git a/tests/ui/binop/binary-op-suggest-deref.stderr b/tests/ui/binop/binary-op-suggest-deref.stderr index ec17074e3050f..01852fbc63308 100644 --- a/tests/ui/binop/binary-op-suggest-deref.stderr +++ b/tests/ui/binop/binary-op-suggest-deref.stderr @@ -303,8 +303,8 @@ LL | let _ = FOO & (*"Sized".to_string().into_boxed_str()); | = help: the trait `BitAnd` is not implemented for `i32` = help: the following other types implement trait `BitAnd`: - `&'a i32` implements `BitAnd` - `&i32` implements `BitAnd<&i32>` + `&i32` implements `BitAnd` + `&i32` implements `BitAnd` `i32` implements `BitAnd<&i32>` `i32` implements `BitAnd` diff --git a/tests/ui/binop/binop-mul-i32-f32.stderr b/tests/ui/binop/binop-mul-i32-f32.stderr index 33d8fba172ce2..dfb96a078cc6c 100644 --- a/tests/ui/binop/binop-mul-i32-f32.stderr +++ b/tests/ui/binop/binop-mul-i32-f32.stderr @@ -6,8 +6,8 @@ LL | x * y | = help: the trait `Mul` is not implemented for `i32` = help: the following other types implement trait `Mul`: - `&'a i32` implements `Mul` - `&i32` implements `Mul<&i32>` + `&i32` implements `Mul` + `&i32` implements `Mul` `i32` implements `Mul<&i32>` `i32` implements `Mul` diff --git a/tests/ui/binop/shift-various-bad-types.stderr b/tests/ui/binop/shift-various-bad-types.stderr index 7313cb3fb84f3..d7c9eb5f9df32 100644 --- a/tests/ui/binop/shift-various-bad-types.stderr +++ b/tests/ui/binop/shift-various-bad-types.stderr @@ -6,14 +6,14 @@ LL | 22 >> p.char; | = help: the trait `Shr` is not implemented for `{integer}` = help: the following other types implement trait `Shr`: - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` + `&i128` implements `Shr<&i16>` + `&i128` implements `Shr<&i32>` + `&i128` implements `Shr<&i64>` + `&i128` implements `Shr<&i8>` + `&i128` implements `Shr<&isize>` + `&i128` implements `Shr<&u128>` + `&i128` implements `Shr<&u16>` + `&i128` implements `Shr<&u32>` and 568 others error[E0277]: no implementation for `{integer} >> &str` @@ -24,14 +24,14 @@ LL | 22 >> p.str; | = help: the trait `Shr<&str>` is not implemented for `{integer}` = help: the following other types implement trait `Shr`: - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` + `&i128` implements `Shr<&i16>` + `&i128` implements `Shr<&i32>` + `&i128` implements `Shr<&i64>` + `&i128` implements `Shr<&i8>` + `&i128` implements `Shr<&isize>` + `&i128` implements `Shr<&u128>` + `&i128` implements `Shr<&u16>` + `&i128` implements `Shr<&u32>` and 568 others error[E0277]: no implementation for `{integer} >> &Panolpy` @@ -42,14 +42,14 @@ LL | 22 >> p; | = help: the trait `Shr<&Panolpy>` is not implemented for `{integer}` = help: the following other types implement trait `Shr`: - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` - `&'a i128` implements `Shr` + `&i128` implements `Shr<&i16>` + `&i128` implements `Shr<&i32>` + `&i128` implements `Shr<&i64>` + `&i128` implements `Shr<&i8>` + `&i128` implements `Shr<&isize>` + `&i128` implements `Shr<&u128>` + `&i128` implements `Shr<&u16>` + `&i128` implements `Shr<&u32>` and 568 others error[E0308]: mismatched types diff --git a/tests/ui/borrowck/alias-liveness/rtn-static.rs b/tests/ui/borrowck/alias-liveness/rtn-static.rs index 6aa5d8fc7a107..5b6cf5b5c7ccc 100644 --- a/tests/ui/borrowck/alias-liveness/rtn-static.rs +++ b/tests/ui/borrowck/alias-liveness/rtn-static.rs @@ -1,7 +1,6 @@ //@ check-pass #![feature(return_type_notation)] -//~^ WARN the feature `return_type_notation` is incomplete trait Foo { fn borrow(&mut self) -> impl Sized + '_; diff --git a/tests/ui/borrowck/alias-liveness/rtn-static.stderr b/tests/ui/borrowck/alias-liveness/rtn-static.stderr deleted file mode 100644 index e9202db2c7902..0000000000000 --- a/tests/ui/borrowck/alias-liveness/rtn-static.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: the feature `return_type_notation` is incomplete and may not be safe to use and/or cause compiler crashes - --> $DIR/rtn-static.rs:3:12 - | -LL | #![feature(return_type_notation)] - | ^^^^^^^^^^^^^^^^^^^^ - | - = note: see issue #109417 for more information - = note: `#[warn(incomplete_features)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr b/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr index b3bf2f924fc3e..89b15a7a659dd 100644 --- a/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr +++ b/tests/ui/borrowck/two-phase-surprise-no-conflict.stderr @@ -75,7 +75,7 @@ LL | reg.register_univ(Box::new(CapturePass::new(®.sess_mut))); | ^^^^^^^^^^^^^^^^^^-----------------------------------------^ | | | | | | | immutable borrow occurs here - | | cast requires that `reg.sess_mut` is borrowed for `'a` + | | coercion requires that `reg.sess_mut` is borrowed for `'a` | mutable borrow occurs here | = note: due to object lifetime defaults, `Box LateLintPass<'b>>` actually means `Box<(dyn for<'b> LateLintPass<'b> + 'static)>` @@ -119,7 +119,7 @@ LL | reg.register_univ(Box::new(CapturePass::new_mut(&mut reg.sess_mut))); | ^^^^^^^^^^^^^^^^^^-------------------------------------------------^ | | | | | | | first mutable borrow occurs here - | | cast requires that `reg.sess_mut` is borrowed for `'a` + | | coercion requires that `reg.sess_mut` is borrowed for `'a` | second mutable borrow occurs here | = note: due to object lifetime defaults, `Box LateLintPass<'b>>` actually means `Box<(dyn for<'b> LateLintPass<'b> + 'static)>` diff --git a/tests/ui/cast/casts-differing-anon.stderr b/tests/ui/cast/casts-differing-anon.stderr index 8ddd97137c30d..fc4882d2d2774 100644 --- a/tests/ui/cast/casts-differing-anon.stderr +++ b/tests/ui/cast/casts-differing-anon.stderr @@ -4,7 +4,7 @@ error[E0606]: casting `*mut impl Debug + ?Sized` as `*mut impl Debug + ?Sized` i LL | b_raw = f_raw as *mut _; | ^^^^^^^^^^^^^^^ | - = note: vtable kinds may not match + = note: the pointers may have different metadata error: aborting due to 1 previous error diff --git a/tests/ui/cast/ptr-to-trait-obj-different-args.rs b/tests/ui/cast/ptr-to-trait-obj-different-args.rs index c6038cfe86401..bb103f789f55b 100644 --- a/tests/ui/cast/ptr-to-trait-obj-different-args.rs +++ b/tests/ui/cast/ptr-to-trait-obj-different-args.rs @@ -18,14 +18,14 @@ fn main() { let b: *const dyn B = a as _; //~ error: casting `*const dyn A` as `*const dyn B` is invalid let x: *const dyn Trait = &(); - let y: *const dyn Trait = x as _; //~ error: mismatched types + let y: *const dyn Trait = x as _; //~ error: casting `*const dyn Trait` as `*const dyn Trait` is invalid _ = (b, y); } fn generic(x: *const dyn Trait, t: *const dyn Trait) { - let _: *const dyn Trait = x as _; //~ error: mismatched types - let _: *const dyn Trait = t as _; //~ error: mismatched types + let _: *const dyn Trait = x as _; //~ error: casting `*const (dyn Trait + 'static)` as `*const dyn Trait` is invalid + let _: *const dyn Trait = t as _; //~ error: casting `*const (dyn Trait + 'static)` as `*const dyn Trait` is invalid } trait Assocked { @@ -33,5 +33,5 @@ trait Assocked { } fn change_assoc(x: *mut dyn Assocked) -> *mut dyn Assocked { - x as _ //~ error: mismatched types + x as _ //~ error: casting `*mut (dyn Assocked + 'static)` as `*mut (dyn Assocked + 'static)` is invalid } diff --git a/tests/ui/cast/ptr-to-trait-obj-different-args.stderr b/tests/ui/cast/ptr-to-trait-obj-different-args.stderr index 8e60ca42f0a52..e571a43959ffd 100644 --- a/tests/ui/cast/ptr-to-trait-obj-different-args.stderr +++ b/tests/ui/cast/ptr-to-trait-obj-different-args.stderr @@ -4,53 +4,40 @@ error[E0606]: casting `*const dyn A` as `*const dyn B` is invalid LL | let b: *const dyn B = a as _; | ^^^^^^ | - = note: vtable kinds may not match + = note: the trait objects may have different vtables -error[E0308]: mismatched types +error[E0606]: casting `*const dyn Trait` as `*const dyn Trait` is invalid --> $DIR/ptr-to-trait-obj-different-args.rs:21:34 | LL | let y: *const dyn Trait = x as _; - | ^^^^^^ expected `X`, found `Y` + | ^^^^^^ | - = note: expected trait object `dyn Trait` - found trait object `dyn Trait` - = help: `dyn Trait` implements `Trait` so you could box the found value and coerce it to the trait object `Box`, you will have to change the expected type as well + = note: the trait objects may have different vtables -error[E0308]: mismatched types +error[E0606]: casting `*const (dyn Trait + 'static)` as `*const dyn Trait` is invalid --> $DIR/ptr-to-trait-obj-different-args.rs:27:34 | -LL | fn generic(x: *const dyn Trait, t: *const dyn Trait) { - | - found this type parameter LL | let _: *const dyn Trait = x as _; - | ^^^^^^ expected `X`, found type parameter `T` + | ^^^^^^ | - = note: expected trait object `dyn Trait` - found trait object `dyn Trait` - = help: `dyn Trait` implements `Trait` so you could box the found value and coerce it to the trait object `Box`, you will have to change the expected type as well + = note: the trait objects may have different vtables -error[E0308]: mismatched types +error[E0606]: casting `*const (dyn Trait + 'static)` as `*const dyn Trait` is invalid --> $DIR/ptr-to-trait-obj-different-args.rs:28:34 | -LL | fn generic(x: *const dyn Trait, t: *const dyn Trait) { - | - expected this type parameter -LL | let _: *const dyn Trait = x as _; LL | let _: *const dyn Trait = t as _; - | ^^^^^^ expected type parameter `T`, found `X` + | ^^^^^^ | - = note: expected trait object `dyn Trait` - found trait object `dyn Trait` - = help: `dyn Trait` implements `Trait` so you could box the found value and coerce it to the trait object `Box`, you will have to change the expected type as well + = note: the trait objects may have different vtables -error[E0308]: mismatched types +error[E0606]: casting `*mut (dyn Assocked + 'static)` as `*mut (dyn Assocked + 'static)` is invalid --> $DIR/ptr-to-trait-obj-different-args.rs:36:5 | LL | x as _ - | ^^^^^^ expected `u8`, found `u32` + | ^^^^^^ | - = note: expected trait object `dyn Assocked` - found trait object `dyn Assocked` + = note: the trait objects may have different vtables error: aborting due to 5 previous errors -Some errors have detailed explanations: E0308, E0606. -For more information about an error, try `rustc --explain E0308`. +For more information about this error, try `rustc --explain E0606`. diff --git a/tests/ui/cast/ptr-to-trait-obj-different-regions-id-trait.current.stderr b/tests/ui/cast/ptr-to-trait-obj-different-regions-id-trait.current.stderr index 5a5b4bfcacf43..4e43d3b93fa35 100644 --- a/tests/ui/cast/ptr-to-trait-obj-different-regions-id-trait.current.stderr +++ b/tests/ui/cast/ptr-to-trait-obj-different-regions-id-trait.current.stderr @@ -1,11 +1,11 @@ error: lifetime may not live long enough - --> $DIR/ptr-to-trait-obj-different-regions-id-trait.rs:24:17 + --> $DIR/ptr-to-trait-obj-different-regions-id-trait.rs:24:27 | LL | fn m<'a>() { | -- lifetime `'a` defined here LL | let unsend: *const dyn Cat<'a> = &(); LL | let _send = unsend as *const S>; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` | = note: requirement occurs because of the type `S>`, which makes the generic argument `dyn Cat<'_>` invariant = note: the struct `S` is invariant over the parameter `T` diff --git a/tests/ui/cast/ptr-to-trait-obj-different-regions-id-trait.next.stderr b/tests/ui/cast/ptr-to-trait-obj-different-regions-id-trait.next.stderr index 5a5b4bfcacf43..4e43d3b93fa35 100644 --- a/tests/ui/cast/ptr-to-trait-obj-different-regions-id-trait.next.stderr +++ b/tests/ui/cast/ptr-to-trait-obj-different-regions-id-trait.next.stderr @@ -1,11 +1,11 @@ error: lifetime may not live long enough - --> $DIR/ptr-to-trait-obj-different-regions-id-trait.rs:24:17 + --> $DIR/ptr-to-trait-obj-different-regions-id-trait.rs:24:27 | LL | fn m<'a>() { | -- lifetime `'a` defined here LL | let unsend: *const dyn Cat<'a> = &(); LL | let _send = unsend as *const S>; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` | = note: requirement occurs because of the type `S>`, which makes the generic argument `dyn Cat<'_>` invariant = note: the struct `S` is invariant over the parameter `T` diff --git a/tests/ui/cast/ptr-to-trait-obj-different-regions-misc.rs b/tests/ui/cast/ptr-to-trait-obj-different-regions-misc.rs index 01c347bfae5a0..d7c6c50d8bebc 100644 --- a/tests/ui/cast/ptr-to-trait-obj-different-regions-misc.rs +++ b/tests/ui/cast/ptr-to-trait-obj-different-regions-misc.rs @@ -33,5 +33,10 @@ fn change_assoc_1<'a, 'b>( //~| error: lifetime may not live long enough } +// This tests the default borrow check error, without the special casing for return values. +fn require_static(_: *const dyn Trait<'static>) {} +fn extend_to_static<'a>(ptr: *const dyn Trait<'a>) { + require_static(ptr as _) //~ error: lifetime may not live long enough +} fn main() {} diff --git a/tests/ui/cast/ptr-to-trait-obj-different-regions-misc.stderr b/tests/ui/cast/ptr-to-trait-obj-different-regions-misc.stderr index 7044e4dec1fe5..6069f4f3b5563 100644 --- a/tests/ui/cast/ptr-to-trait-obj-different-regions-misc.stderr +++ b/tests/ui/cast/ptr-to-trait-obj-different-regions-misc.stderr @@ -132,5 +132,13 @@ help: `'b` and `'a` must be the same: replace one with the other | = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 8 previous errors +error: lifetime may not live long enough + --> $DIR/ptr-to-trait-obj-different-regions-misc.rs:39:20 + | +LL | fn extend_to_static<'a>(ptr: *const dyn Trait<'a>) { + | -- lifetime `'a` defined here +LL | require_static(ptr as _) + | ^^^^^^^^ cast requires that `'a` must outlive `'static` + +error: aborting due to 9 previous errors diff --git a/tests/ui/cast/ptr-to-trait-obj-wrap-upcast.stderr b/tests/ui/cast/ptr-to-trait-obj-wrap-upcast.stderr index 38c8ba96bc5b7..5687aba625ff7 100644 --- a/tests/ui/cast/ptr-to-trait-obj-wrap-upcast.stderr +++ b/tests/ui/cast/ptr-to-trait-obj-wrap-upcast.stderr @@ -4,7 +4,7 @@ error[E0606]: casting `*const (dyn Sub + 'static)` as `*const Wrapper LL | ptr as _ | ^^^^^^^^ | - = note: vtable kinds may not match + = note: the trait objects may have different vtables error: aborting due to 1 previous error diff --git a/tests/ui/const-generics/generic_const_exprs/different-fn.stderr b/tests/ui/const-generics/generic_const_exprs/different-fn.stderr index 52917df0da157..ac80463480db1 100644 --- a/tests/ui/const-generics/generic_const_exprs/different-fn.stderr +++ b/tests/ui/const-generics/generic_const_exprs/different-fn.stderr @@ -2,10 +2,10 @@ error[E0308]: mismatched types --> $DIR/different-fn.rs:10:5 | LL | [0; size_of::>()] - | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `size_of::()`, found `size_of::>()` + | ^^^^^^^^^^^^^^^^^^^^^^^^ expected `size_of::()`, found `0` | = note: expected constant `size_of::()` - found constant `size_of::>()` + found constant `0` error: unconstrained generic constant --> $DIR/different-fn.rs:10:9 diff --git a/tests/ui/const-generics/occurs-check/unused-substs-1.stderr b/tests/ui/const-generics/occurs-check/unused-substs-1.stderr index 8c66c4fefb7ed..0184a05932707 100644 --- a/tests/ui/const-generics/occurs-check/unused-substs-1.stderr +++ b/tests/ui/const-generics/occurs-check/unused-substs-1.stderr @@ -4,7 +4,7 @@ error[E0277]: the trait bound `A<_>: Bar<_>` is not satisfied LL | let _ = A; | ^ the trait `Bar<_>` is not implemented for `A<_>` | - = help: the trait `Bar<_>` is implemented for `A<7>` + = help: the trait `Bar<_>` is implemented for `A<{ 6 + 1 }>` note: required by a bound in `A` --> $DIR/unused-substs-1.rs:9:11 | diff --git a/tests/ui/const-generics/unsized_const_params/symbol_mangling_v0_str.rs b/tests/ui/const-generics/unsized_const_params/symbol_mangling_v0_str.rs new file mode 100644 index 0000000000000..359126f125167 --- /dev/null +++ b/tests/ui/const-generics/unsized_const_params/symbol_mangling_v0_str.rs @@ -0,0 +1,24 @@ +//@ check-pass +//@ compile-flags: -Csymbol-mangling-version=v0 +#![allow(incomplete_features)] +#![feature(unsized_const_params)] + +// Regression test for #116303 + +#[derive(PartialEq, Eq)] +struct MyStr(str); +impl std::marker::UnsizedConstParamTy for MyStr {} + +fn function_with_my_str() -> &'static MyStr { + S +} + +impl MyStr { + const fn new(s: &'static str) -> &'static MyStr { + unsafe { std::mem::transmute(s) } + } +} + +pub fn main() { + let f = function_with_my_str::<{ MyStr::new("hello") }>(); +} diff --git a/tests/ui/const-generics/wrong-normalization.rs b/tests/ui/const-generics/wrong-normalization.rs index 8b2323e3d479c..f1ce317b3f78b 100644 --- a/tests/ui/const-generics/wrong-normalization.rs +++ b/tests/ui/const-generics/wrong-normalization.rs @@ -15,6 +15,5 @@ pub struct I8; impl as Identity>::Identity { //~^ ERROR no nominal type found for inherent implementation -//~| ERROR no associated item named `MIN` found for type `i8` pub fn foo(&self) {} } diff --git a/tests/ui/const-generics/wrong-normalization.stderr b/tests/ui/const-generics/wrong-normalization.stderr index 379a5593dd640..2f8dfc895b279 100644 --- a/tests/ui/const-generics/wrong-normalization.stderr +++ b/tests/ui/const-generics/wrong-normalization.stderr @@ -6,18 +6,6 @@ LL | impl as Identity>::Identity { | = note: either implement a trait on it or create a newtype to wrap it instead -error[E0599]: no associated item named `MIN` found for type `i8` in the current scope - --> $DIR/wrong-normalization.rs:16:15 - | -LL | impl as Identity>::Identity { - | ^^^ associated item not found in `i8` - | -help: you are looking for the module in `std`, not the primitive type - | -LL | impl as Identity>::Identity { - | +++++ - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error -Some errors have detailed explanations: E0118, E0599. -For more information about an error, try `rustc --explain E0118`. +For more information about this error, try `rustc --explain E0118`. diff --git a/tests/ui/consts/const-eval/const-eval-overflow-3b.stderr b/tests/ui/consts/const-eval/const-eval-overflow-3b.stderr index 0d9b718cd067f..f6eda69e12791 100644 --- a/tests/ui/consts/const-eval/const-eval-overflow-3b.stderr +++ b/tests/ui/consts/const-eval/const-eval-overflow-3b.stderr @@ -12,8 +12,8 @@ LL | = [0; (i8::MAX + 1u8) as usize]; | = help: the trait `Add` is not implemented for `i8` = help: the following other types implement trait `Add`: - `&'a i8` implements `Add` - `&i8` implements `Add<&i8>` + `&i8` implements `Add` + `&i8` implements `Add` `i8` implements `Add<&i8>` `i8` implements `Add` diff --git a/tests/ui/consts/const-eval/const-eval-overflow-4b.stderr b/tests/ui/consts/const-eval/const-eval-overflow-4b.stderr index 32fe30dc88247..399f21a989429 100644 --- a/tests/ui/consts/const-eval/const-eval-overflow-4b.stderr +++ b/tests/ui/consts/const-eval/const-eval-overflow-4b.stderr @@ -12,8 +12,8 @@ LL | : [u32; (i8::MAX as i8 + 1u8) as usize] | = help: the trait `Add` is not implemented for `i8` = help: the following other types implement trait `Add`: - `&'a i8` implements `Add` - `&i8` implements `Add<&i8>` + `&i8` implements `Add` + `&i8` implements `Add` `i8` implements `Add<&i8>` `i8` implements `Add` diff --git a/tests/ui/consts/const-eval/raw-pointer-ub.rs b/tests/ui/consts/const-eval/raw-pointer-ub.rs index 3320e62781288..5724293f145ff 100644 --- a/tests/ui/consts/const-eval/raw-pointer-ub.rs +++ b/tests/ui/consts/const-eval/raw-pointer-ub.rs @@ -1,6 +1,3 @@ -#![feature(const_intrinsic_copy)] - - const MISALIGNED_LOAD: () = unsafe { let mem = [0u32; 8]; let ptr = mem.as_ptr().byte_add(1); diff --git a/tests/ui/consts/const-eval/raw-pointer-ub.stderr b/tests/ui/consts/const-eval/raw-pointer-ub.stderr index aeb46725c0642..3426a768cb607 100644 --- a/tests/ui/consts/const-eval/raw-pointer-ub.stderr +++ b/tests/ui/consts/const-eval/raw-pointer-ub.stderr @@ -1,11 +1,11 @@ error[E0080]: evaluation of constant value failed - --> $DIR/raw-pointer-ub.rs:7:16 + --> $DIR/raw-pointer-ub.rs:4:16 | LL | let _val = *ptr; | ^^^^ accessing memory based on pointer with alignment 1, but alignment 4 is required error[E0080]: evaluation of constant value failed - --> $DIR/raw-pointer-ub.rs:14:5 + --> $DIR/raw-pointer-ub.rs:11:5 | LL | *ptr = 0; | ^^^^^^^^ accessing memory based on pointer with alignment 1, but alignment 4 is required @@ -20,19 +20,19 @@ note: inside `copy_nonoverlapping::` note: inside `std::ptr::const_ptr::::copy_to_nonoverlapping` --> $SRC_DIR/core/src/ptr/const_ptr.rs:LL:COL note: inside `MISALIGNED_COPY` - --> $DIR/raw-pointer-ub.rs:22:5 + --> $DIR/raw-pointer-ub.rs:19:5 | LL | y.copy_to_nonoverlapping(&mut z, 1); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error[E0080]: evaluation of constant value failed - --> $DIR/raw-pointer-ub.rs:34:16 + --> $DIR/raw-pointer-ub.rs:31:16 | LL | let _val = (*ptr).0; | ^^^^^^^^ accessing memory based on pointer with alignment 4, but alignment 16 is required error[E0080]: evaluation of constant value failed - --> $DIR/raw-pointer-ub.rs:41:16 + --> $DIR/raw-pointer-ub.rs:38:16 | LL | let _val = *ptr; | ^^^^ memory access failed: expected a pointer to 8 bytes of memory, but got ALLOC0 which is only 4 bytes from the end of the allocation diff --git a/tests/ui/consts/const-eval/stable-metric/evade-deduplication-issue-118612.rs b/tests/ui/consts/const-eval/stable-metric/evade-deduplication-issue-118612.rs new file mode 100644 index 0000000000000..a2d34eaa384c9 --- /dev/null +++ b/tests/ui/consts/const-eval/stable-metric/evade-deduplication-issue-118612.rs @@ -0,0 +1,24 @@ +//@ check-pass + +#![allow(long_running_const_eval)] + +//@ compile-flags: -Z tiny-const-eval-limit -Z deduplicate-diagnostics=yes +const FOO: () = { + let mut i = 0; + loop { + //~^ WARN is taking a long time + //~| WARN is taking a long time + //~| WARN is taking a long time + //~| WARN is taking a long time + //~| WARN is taking a long time + if i == 1000 { + break; + } else { + i += 1; + } + } +}; + +fn main() { + FOO +} diff --git a/tests/ui/consts/const-eval/stable-metric/evade-deduplication-issue-118612.stderr b/tests/ui/consts/const-eval/stable-metric/evade-deduplication-issue-118612.stderr new file mode 100644 index 0000000000000..cb19c59b15bc0 --- /dev/null +++ b/tests/ui/consts/const-eval/stable-metric/evade-deduplication-issue-118612.stderr @@ -0,0 +1,92 @@ +warning: constant evaluation is taking a long time + --> $DIR/evade-deduplication-issue-118612.rs:8:5 + | +LL | / loop { +LL | | +LL | | +LL | | +... | +LL | | } +LL | | } + | |_____^ the const evaluator is currently interpreting this expression + | +help: the constant being evaluated + --> $DIR/evade-deduplication-issue-118612.rs:6:1 + | +LL | const FOO: () = { + | ^^^^^^^^^^^^^ + +warning: constant evaluation is taking a long time + --> $DIR/evade-deduplication-issue-118612.rs:8:5 + | +LL | / loop { +LL | | +LL | | +LL | | +... | +LL | | } +LL | | } + | |_____^ the const evaluator is currently interpreting this expression + | +help: the constant being evaluated + --> $DIR/evade-deduplication-issue-118612.rs:6:1 + | +LL | const FOO: () = { + | ^^^^^^^^^^^^^ + +warning: constant evaluation is taking a long time + --> $DIR/evade-deduplication-issue-118612.rs:8:5 + | +LL | / loop { +LL | | +LL | | +LL | | +... | +LL | | } +LL | | } + | |_____^ the const evaluator is currently interpreting this expression + | +help: the constant being evaluated + --> $DIR/evade-deduplication-issue-118612.rs:6:1 + | +LL | const FOO: () = { + | ^^^^^^^^^^^^^ + +warning: constant evaluation is taking a long time + --> $DIR/evade-deduplication-issue-118612.rs:8:5 + | +LL | / loop { +LL | | +LL | | +LL | | +... | +LL | | } +LL | | } + | |_____^ the const evaluator is currently interpreting this expression + | +help: the constant being evaluated + --> $DIR/evade-deduplication-issue-118612.rs:6:1 + | +LL | const FOO: () = { + | ^^^^^^^^^^^^^ + +warning: constant evaluation is taking a long time + --> $DIR/evade-deduplication-issue-118612.rs:8:5 + | +LL | / loop { +LL | | +LL | | +LL | | +... | +LL | | } +LL | | } + | |_____^ the const evaluator is currently interpreting this expression + | +help: the constant being evaluated + --> $DIR/evade-deduplication-issue-118612.rs:6:1 + | +LL | const FOO: () = { + | ^^^^^^^^^^^^^ + +warning: 5 warnings emitted + diff --git a/tests/ui/dropck/dropck_trait_cycle_checked.stderr b/tests/ui/dropck/dropck_trait_cycle_checked.stderr index 63fd07a91633d..f32736f1a674c 100644 --- a/tests/ui/dropck/dropck_trait_cycle_checked.stderr +++ b/tests/ui/dropck/dropck_trait_cycle_checked.stderr @@ -2,7 +2,7 @@ error[E0597]: `o2` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:111:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -- binding `o2` declared here -------- cast requires that `o2` is borrowed for `'static` + | -- binding `o2` declared here -------- coercion requires that `o2` is borrowed for `'static` LL | o1.set0(&o2); | ^^^ borrowed value does not live long enough ... @@ -15,7 +15,7 @@ error[E0597]: `o3` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:112:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -- binding `o3` declared here -------- cast requires that `o3` is borrowed for `'static` + | -- binding `o3` declared here -------- coercion requires that `o3` is borrowed for `'static` LL | o1.set0(&o2); LL | o1.set1(&o3); | ^^^ borrowed value does not live long enough @@ -29,7 +29,7 @@ error[E0597]: `o2` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:113:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -- binding `o2` declared here -------- cast requires that `o2` is borrowed for `'static` + | -- binding `o2` declared here -------- coercion requires that `o2` is borrowed for `'static` ... LL | o2.set0(&o2); | ^^^ borrowed value does not live long enough @@ -43,7 +43,7 @@ error[E0597]: `o3` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:114:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -- binding `o3` declared here -------- cast requires that `o3` is borrowed for `'static` + | -- binding `o3` declared here -------- coercion requires that `o3` is borrowed for `'static` ... LL | o2.set1(&o3); | ^^^ borrowed value does not live long enough @@ -57,7 +57,7 @@ error[E0597]: `o1` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:115:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -- binding `o1` declared here -------- cast requires that `o1` is borrowed for `'static` + | -- binding `o1` declared here -------- coercion requires that `o1` is borrowed for `'static` ... LL | o3.set0(&o1); | ^^^ borrowed value does not live long enough @@ -71,7 +71,7 @@ error[E0597]: `o2` does not live long enough --> $DIR/dropck_trait_cycle_checked.rs:116:13 | LL | let (o1, o2, o3): (Box, Box, Box) = (O::new(), O::new(), O::new()); - | -- binding `o2` declared here -------- cast requires that `o2` is borrowed for `'static` + | -- binding `o2` declared here -------- coercion requires that `o2` is borrowed for `'static` ... LL | o3.set1(&o2); | ^^^ borrowed value does not live long enough diff --git a/tests/ui/dyn-star/dyn-to-rigid.rs b/tests/ui/dyn-star/dyn-to-rigid.rs index e80ee15902eef..dc33e288f24e6 100644 --- a/tests/ui/dyn-star/dyn-to-rigid.rs +++ b/tests/ui/dyn-star/dyn-to-rigid.rs @@ -5,7 +5,7 @@ trait Tr {} fn f(x: dyn* Tr) -> usize { x as usize - //~^ ERROR casting `(dyn* Tr + 'static)` as `usize` is invalid + //~^ ERROR non-primitive cast: `(dyn* Tr + 'static)` as `usize` } fn main() {} diff --git a/tests/ui/dyn-star/dyn-to-rigid.stderr b/tests/ui/dyn-star/dyn-to-rigid.stderr index b198c5245dea0..49b8f268aa4e9 100644 --- a/tests/ui/dyn-star/dyn-to-rigid.stderr +++ b/tests/ui/dyn-star/dyn-to-rigid.stderr @@ -1,9 +1,9 @@ -error[E0606]: casting `(dyn* Tr + 'static)` as `usize` is invalid +error[E0605]: non-primitive cast: `(dyn* Tr + 'static)` as `usize` --> $DIR/dyn-to-rigid.rs:7:5 | LL | x as usize - | ^^^^^^^^^^ + | ^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0606`. +For more information about this error, try `rustc --explain E0605`. diff --git a/tests/ui/dyn-star/enum-cast.rs b/tests/ui/dyn-star/enum-cast.rs new file mode 100644 index 0000000000000..6e895e9527aba --- /dev/null +++ b/tests/ui/dyn-star/enum-cast.rs @@ -0,0 +1,18 @@ +//@ check-pass + +// This used to ICE, because the compiler confused a pointer-like to dyn* coercion +// with a c-like enum to integer cast. + +#![feature(dyn_star)] +#![expect(incomplete_features)] + +enum E { + Num(usize), +} + +trait Trait {} +impl Trait for E {} + +fn main() { + let _ = E::Num(42) as dyn* Trait; +} diff --git a/tests/ui/feature-gates/feature-gate-rustc-attrs-1.rs b/tests/ui/feature-gates/feature-gate-rustc-attrs-1.rs index 667bc9f8ddf18..7ae4a8d911bad 100644 --- a/tests/ui/feature-gates/feature-gate-rustc-attrs-1.rs +++ b/tests/ui/feature-gates/feature-gate-rustc-attrs-1.rs @@ -2,6 +2,6 @@ #[rustc_variance] //~ ERROR the `#[rustc_variance]` attribute is just used for rustc unit tests and will never be stable #[rustc_error] //~ ERROR the `#[rustc_error]` attribute is just used for rustc unit tests and will never be stable -#[rustc_nonnull_optimization_guaranteed] //~ ERROR the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable niche optimizations in libcore and libstd and will never be stable +#[rustc_nonnull_optimization_guaranteed] //~ ERROR the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to document guaranteed niche optimizations in libcore and libstd and will never be stable fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-rustc-attrs-1.stderr b/tests/ui/feature-gates/feature-gate-rustc-attrs-1.stderr index 8177d5ef6bedb..8c3a8eb2df875 100644 --- a/tests/ui/feature-gates/feature-gate-rustc-attrs-1.stderr +++ b/tests/ui/feature-gates/feature-gate-rustc-attrs-1.stderr @@ -16,7 +16,8 @@ LL | #[rustc_error] = help: add `#![feature(rustc_attrs)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -error[E0658]: the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to enable niche optimizations in libcore and libstd and will never be stable +error[E0658]: the `#[rustc_nonnull_optimization_guaranteed]` attribute is just used to document guaranteed niche optimizations in libcore and libstd and will never be stable + (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) --> $DIR/feature-gate-rustc-attrs-1.rs:5:1 | LL | #[rustc_nonnull_optimization_guaranteed] diff --git a/tests/ui/feature-gates/feature-gate-unqualified-local-imports.rs b/tests/ui/feature-gates/feature-gate-unqualified-local-imports.rs new file mode 100644 index 0000000000000..29929e40f89bc --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-unqualified-local-imports.rs @@ -0,0 +1,6 @@ +//@ check-pass + +#![allow(unqualified_local_imports)] +//~^ WARNING unknown lint: `unqualified_local_imports` + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-unqualified-local-imports.stderr b/tests/ui/feature-gates/feature-gate-unqualified-local-imports.stderr new file mode 100644 index 0000000000000..22cd3bf4c6faf --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-unqualified-local-imports.stderr @@ -0,0 +1,13 @@ +warning: unknown lint: `unqualified_local_imports` + --> $DIR/feature-gate-unqualified-local-imports.rs:3:1 + | +LL | #![allow(unqualified_local_imports)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: the `unqualified_local_imports` lint is unstable + = help: add `#![feature(unqualified_local_imports)]` to the crate attributes to enable + = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date + = note: `#[warn(unknown_lints)]` on by default + +warning: 1 warning emitted + diff --git a/tests/ui/impl-trait/equality.stderr b/tests/ui/impl-trait/equality.stderr index 12d886a002454..fd6f4b34241aa 100644 --- a/tests/ui/impl-trait/equality.stderr +++ b/tests/ui/impl-trait/equality.stderr @@ -30,8 +30,8 @@ LL | n + sum_to(n - 1) | = help: the trait `Add` is not implemented for `u32` = help: the following other types implement trait `Add`: - `&'a u32` implements `Add` - `&u32` implements `Add<&u32>` + `&u32` implements `Add` + `&u32` implements `Add` `u32` implements `Add<&u32>` `u32` implements `Add` diff --git a/tests/ui/impl-trait/where-allowed.rs b/tests/ui/impl-trait/where-allowed.rs index 72ce617693e40..3f435f0f443b4 100644 --- a/tests/ui/impl-trait/where-allowed.rs +++ b/tests/ui/impl-trait/where-allowed.rs @@ -42,7 +42,7 @@ fn in_dyn_Fn_return_in_parameters(_: &dyn Fn() -> impl Debug) { panic!() } fn in_dyn_Fn_parameter_in_return() -> &'static dyn Fn(impl Debug) { panic!() } //~^ ERROR `impl Trait` is not allowed in the parameters of `Fn` trait bounds -// Allowed +// Allowed (but it's still ambiguous; nothing constrains the RPIT in this body). fn in_dyn_Fn_return_in_return() -> &'static dyn Fn() -> impl Debug { panic!() } //~^ ERROR: type annotations needed @@ -79,7 +79,6 @@ fn in_impl_Trait_in_parameters(_: impl Iterator) { panic!( // Allowed fn in_impl_Trait_in_return() -> impl IntoIterator { vec![vec![0; 10], vec![12; 7], vec![8; 3]] - //~^ ERROR: no function or associated item named `into_vec` found for slice `[_]` } // Disallowed diff --git a/tests/ui/impl-trait/where-allowed.stderr b/tests/ui/impl-trait/where-allowed.stderr index 1fb69db98c162..2770a6cc40e59 100644 --- a/tests/ui/impl-trait/where-allowed.stderr +++ b/tests/ui/impl-trait/where-allowed.stderr @@ -17,7 +17,7 @@ LL | fn in_impl_Fn_parameter_in_return() -> &'static impl Fn(impl Debug) { panic | outer `impl Trait` error[E0658]: `impl Trait` in associated types is unstable - --> $DIR/where-allowed.rs:122:16 + --> $DIR/where-allowed.rs:121:16 | LL | type Out = impl Debug; | ^^^^^^^^^^ @@ -27,7 +27,7 @@ LL | type Out = impl Debug; = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0658]: `impl Trait` in type aliases is unstable - --> $DIR/where-allowed.rs:159:23 + --> $DIR/where-allowed.rs:158:23 | LL | type InTypeAlias = impl Debug; | ^^^^^^^^^^ @@ -37,7 +37,7 @@ LL | type InTypeAlias = impl Debug; = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0658]: `impl Trait` in type aliases is unstable - --> $DIR/where-allowed.rs:162:39 + --> $DIR/where-allowed.rs:161:39 | LL | type InReturnInTypeAlias = fn() -> impl Debug; | ^^^^^^^^^^ @@ -143,7 +143,7 @@ LL | fn in_Fn_return_in_generics impl Debug> (_: F) { panic!() } = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in field types - --> $DIR/where-allowed.rs:86:32 + --> $DIR/where-allowed.rs:85:32 | LL | struct InBraceStructField { x: impl Debug } | ^^^^^^^^^^ @@ -151,7 +151,7 @@ LL | struct InBraceStructField { x: impl Debug } = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in field types - --> $DIR/where-allowed.rs:90:41 + --> $DIR/where-allowed.rs:89:41 | LL | struct InAdtInBraceStructField { x: Vec } | ^^^^^^^^^^ @@ -159,7 +159,7 @@ LL | struct InAdtInBraceStructField { x: Vec } = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in field types - --> $DIR/where-allowed.rs:94:27 + --> $DIR/where-allowed.rs:93:27 | LL | struct InTupleStructField(impl Debug); | ^^^^^^^^^^ @@ -167,7 +167,7 @@ LL | struct InTupleStructField(impl Debug); = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in field types - --> $DIR/where-allowed.rs:99:25 + --> $DIR/where-allowed.rs:98:25 | LL | InBraceVariant { x: impl Debug }, | ^^^^^^^^^^ @@ -175,7 +175,7 @@ LL | InBraceVariant { x: impl Debug }, = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in field types - --> $DIR/where-allowed.rs:101:20 + --> $DIR/where-allowed.rs:100:20 | LL | InTupleVariant(impl Debug), | ^^^^^^^^^^ @@ -183,7 +183,7 @@ LL | InTupleVariant(impl Debug), = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in `extern fn` parameters - --> $DIR/where-allowed.rs:143:33 + --> $DIR/where-allowed.rs:142:33 | LL | fn in_foreign_parameters(_: impl Debug); | ^^^^^^^^^^ @@ -191,7 +191,7 @@ LL | fn in_foreign_parameters(_: impl Debug); = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in `extern fn` return types - --> $DIR/where-allowed.rs:146:31 + --> $DIR/where-allowed.rs:145:31 | LL | fn in_foreign_return() -> impl Debug; | ^^^^^^^^^^ @@ -199,7 +199,7 @@ LL | fn in_foreign_return() -> impl Debug; = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in `fn` pointer return types - --> $DIR/where-allowed.rs:162:39 + --> $DIR/where-allowed.rs:161:39 | LL | type InReturnInTypeAlias = fn() -> impl Debug; | ^^^^^^^^^^ @@ -207,7 +207,7 @@ LL | type InReturnInTypeAlias = fn() -> impl Debug; = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in traits - --> $DIR/where-allowed.rs:167:16 + --> $DIR/where-allowed.rs:166:16 | LL | impl PartialEq for () { | ^^^^^^^^^^ @@ -215,7 +215,7 @@ LL | impl PartialEq for () { = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in impl headers - --> $DIR/where-allowed.rs:172:24 + --> $DIR/where-allowed.rs:171:24 | LL | impl PartialEq<()> for impl Debug { | ^^^^^^^^^^ @@ -223,7 +223,7 @@ LL | impl PartialEq<()> for impl Debug { = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in impl headers - --> $DIR/where-allowed.rs:177:6 + --> $DIR/where-allowed.rs:176:6 | LL | impl impl Debug { | ^^^^^^^^^^ @@ -231,7 +231,7 @@ LL | impl impl Debug { = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in impl headers - --> $DIR/where-allowed.rs:183:24 + --> $DIR/where-allowed.rs:182:24 | LL | impl InInherentImplAdt { | ^^^^^^^^^^ @@ -239,7 +239,7 @@ LL | impl InInherentImplAdt { = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in bounds - --> $DIR/where-allowed.rs:189:11 + --> $DIR/where-allowed.rs:188:11 | LL | where impl Debug: Debug | ^^^^^^^^^^ @@ -247,7 +247,7 @@ LL | where impl Debug: Debug = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in bounds - --> $DIR/where-allowed.rs:196:15 + --> $DIR/where-allowed.rs:195:15 | LL | where Vec: Debug | ^^^^^^^^^^ @@ -255,7 +255,7 @@ LL | where Vec: Debug = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in bounds - --> $DIR/where-allowed.rs:203:24 + --> $DIR/where-allowed.rs:202:24 | LL | where T: PartialEq | ^^^^^^^^^^ @@ -263,7 +263,7 @@ LL | where T: PartialEq = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in the parameters of `Fn` trait bounds - --> $DIR/where-allowed.rs:210:17 + --> $DIR/where-allowed.rs:209:17 | LL | where T: Fn(impl Debug) | ^^^^^^^^^^ @@ -271,7 +271,7 @@ LL | where T: Fn(impl Debug) = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in the return type of `Fn` trait bounds - --> $DIR/where-allowed.rs:217:22 + --> $DIR/where-allowed.rs:216:22 | LL | where T: Fn() -> impl Debug | ^^^^^^^^^^ @@ -279,7 +279,7 @@ LL | where T: Fn() -> impl Debug = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in generic parameter defaults - --> $DIR/where-allowed.rs:223:40 + --> $DIR/where-allowed.rs:222:40 | LL | struct InStructGenericParamDefault(T); | ^^^^^^^^^^ @@ -287,7 +287,7 @@ LL | struct InStructGenericParamDefault(T); = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in generic parameter defaults - --> $DIR/where-allowed.rs:227:36 + --> $DIR/where-allowed.rs:226:36 | LL | enum InEnumGenericParamDefault { Variant(T) } | ^^^^^^^^^^ @@ -295,7 +295,7 @@ LL | enum InEnumGenericParamDefault { Variant(T) } = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in generic parameter defaults - --> $DIR/where-allowed.rs:231:38 + --> $DIR/where-allowed.rs:230:38 | LL | trait InTraitGenericParamDefault {} | ^^^^^^^^^^ @@ -303,7 +303,7 @@ LL | trait InTraitGenericParamDefault {} = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in generic parameter defaults - --> $DIR/where-allowed.rs:235:41 + --> $DIR/where-allowed.rs:234:41 | LL | type InTypeAliasGenericParamDefault = T; | ^^^^^^^^^^ @@ -311,7 +311,7 @@ LL | type InTypeAliasGenericParamDefault = T; = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in generic parameter defaults - --> $DIR/where-allowed.rs:239:11 + --> $DIR/where-allowed.rs:238:11 | LL | impl T {} | ^^^^^^^^^^ @@ -319,7 +319,7 @@ LL | impl T {} = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in generic parameter defaults - --> $DIR/where-allowed.rs:246:40 + --> $DIR/where-allowed.rs:245:40 | LL | fn in_method_generic_param_default(_: T) {} | ^^^^^^^^^^ @@ -327,7 +327,7 @@ LL | fn in_method_generic_param_default(_: T) {} = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in the type of variable bindings - --> $DIR/where-allowed.rs:252:29 + --> $DIR/where-allowed.rs:251:29 | LL | let _in_local_variable: impl Fn() = || {}; | ^^^^^^^^^ @@ -335,7 +335,7 @@ LL | let _in_local_variable: impl Fn() = || {}; = note: `impl Trait` is only allowed in arguments and return types of functions and methods error[E0562]: `impl Trait` is not allowed in closure return types - --> $DIR/where-allowed.rs:254:46 + --> $DIR/where-allowed.rs:253:46 | LL | let _in_return_in_local_variable = || -> impl Fn() { || {} }; | ^^^^^^^^^ @@ -363,7 +363,7 @@ LL | fn in_impl_Fn_return_in_return() -> &'static impl Fn() -> impl Debug { pani where Args: Tuple, F: Fn, A: Allocator, F: ?Sized; error: defaults for type parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions - --> $DIR/where-allowed.rs:239:7 + --> $DIR/where-allowed.rs:238:7 | LL | impl T {} | ^^^^^^^^^^^^^^ @@ -373,25 +373,15 @@ LL | impl T {} = note: `#[deny(invalid_type_param_default)]` on by default error[E0118]: no nominal type found for inherent implementation - --> $DIR/where-allowed.rs:239:1 + --> $DIR/where-allowed.rs:238:1 | LL | impl T {} | ^^^^^^^^^^^^^^^^^^^^^^^ impl requires a nominal type | = note: either implement a trait on it or create a newtype to wrap it instead -error[E0599]: no function or associated item named `into_vec` found for slice `[_]` in the current scope - --> $DIR/where-allowed.rs:81:5 - | -LL | vec![vec![0; 10], vec![12; 7], vec![8; 3]] - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ function or associated item not found in `[_]` - | -help: there is an associated function `to_vec` with a similar name - --> $SRC_DIR/alloc/src/slice.rs:LL:COL - = note: this error originates in the macro `vec` (in Nightly builds, run with -Z macro-backtrace for more info) - error[E0053]: method `in_trait_impl_return` has an incompatible type for trait - --> $DIR/where-allowed.rs:129:34 + --> $DIR/where-allowed.rs:128:34 | LL | type Out = impl Debug; | ---------- the expected opaque type @@ -400,7 +390,7 @@ LL | fn in_trait_impl_return() -> impl Debug { () } | ^^^^^^^^^^ expected opaque type, found a different opaque type | note: type in trait - --> $DIR/where-allowed.rs:119:34 + --> $DIR/where-allowed.rs:118:34 | LL | fn in_trait_impl_return() -> Self::Out; | ^^^^^^^^^ @@ -413,7 +403,7 @@ LL | fn in_trait_impl_return() -> <() as DummyTrait>::Out { () } | ~~~~~~~~~~~~~~~~~~~~~~~ error: unconstrained opaque type - --> $DIR/where-allowed.rs:122:16 + --> $DIR/where-allowed.rs:121:16 | LL | type Out = impl Debug; | ^^^^^^^^^^ @@ -421,7 +411,7 @@ LL | type Out = impl Debug; = note: `Out` must be used in combination with a concrete type within the same impl error: defaults for type parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions - --> $DIR/where-allowed.rs:246:36 + --> $DIR/where-allowed.rs:245:36 | LL | fn in_method_generic_param_default(_: T) {} | ^^^^^^^^^^^^^^ @@ -429,13 +419,13 @@ LL | fn in_method_generic_param_default(_: T) {} = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: for more information, see issue #36887 -error: aborting due to 50 previous errors +error: aborting due to 49 previous errors -Some errors have detailed explanations: E0053, E0118, E0283, E0562, E0599, E0658, E0666. +Some errors have detailed explanations: E0053, E0118, E0283, E0562, E0658, E0666. For more information about an error, try `rustc --explain E0053`. Future incompatibility report: Future breakage diagnostic: error: defaults for type parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions - --> $DIR/where-allowed.rs:239:7 + --> $DIR/where-allowed.rs:238:7 | LL | impl T {} | ^^^^^^^^^^^^^^ @@ -446,7 +436,7 @@ LL | impl T {} Future breakage diagnostic: error: defaults for type parameters are only allowed in `struct`, `enum`, `type`, or `trait` definitions - --> $DIR/where-allowed.rs:246:36 + --> $DIR/where-allowed.rs:245:36 | LL | fn in_method_generic_param_default(_: T) {} | ^^^^^^^^^^^^^^ diff --git a/tests/ui/issues/issue-11771.stderr b/tests/ui/issues/issue-11771.stderr index 8205ee0c38d53..5603dc18b635f 100644 --- a/tests/ui/issues/issue-11771.stderr +++ b/tests/ui/issues/issue-11771.stderr @@ -6,14 +6,14 @@ LL | 1 + | = help: the trait `Add<()>` is not implemented for `{integer}` = help: the following other types implement trait `Add`: - `&'a f128` implements `Add` - `&'a f16` implements `Add` - `&'a f32` implements `Add` - `&'a f64` implements `Add` - `&'a i128` implements `Add` - `&'a i16` implements `Add` - `&'a i32` implements `Add` - `&'a i64` implements `Add` + `&f128` implements `Add` + `&f128` implements `Add` + `&f16` implements `Add` + `&f16` implements `Add` + `&f32` implements `Add` + `&f32` implements `Add` + `&f64` implements `Add` + `&f64` implements `Add` and 56 others error[E0277]: cannot add `()` to `{integer}` @@ -24,14 +24,14 @@ LL | 1 + | = help: the trait `Add<()>` is not implemented for `{integer}` = help: the following other types implement trait `Add`: - `&'a f128` implements `Add` - `&'a f16` implements `Add` - `&'a f32` implements `Add` - `&'a f64` implements `Add` - `&'a i128` implements `Add` - `&'a i16` implements `Add` - `&'a i32` implements `Add` - `&'a i64` implements `Add` + `&f128` implements `Add` + `&f128` implements `Add` + `&f16` implements `Add` + `&f16` implements `Add` + `&f32` implements `Add` + `&f32` implements `Add` + `&f64` implements `Add` + `&f64` implements `Add` and 56 others error: aborting due to 2 previous errors diff --git a/tests/ui/issues/issue-24352.stderr b/tests/ui/issues/issue-24352.stderr index 2e7dc254d914d..3e0f812b5c757 100644 --- a/tests/ui/issues/issue-24352.stderr +++ b/tests/ui/issues/issue-24352.stderr @@ -6,8 +6,8 @@ LL | 1.0f64 - 1 | = help: the trait `Sub<{integer}>` is not implemented for `f64` = help: the following other types implement trait `Sub`: - `&'a f64` implements `Sub` - `&f64` implements `Sub<&f64>` + `&f64` implements `Sub` + `&f64` implements `Sub` `f64` implements `Sub<&f64>` `f64` implements `Sub` help: consider using a floating-point literal by writing it with `.0` diff --git a/tests/ui/issues/issue-50582.stderr b/tests/ui/issues/issue-50582.stderr index 7203fdeb0bbca..af7a36f62fb88 100644 --- a/tests/ui/issues/issue-50582.stderr +++ b/tests/ui/issues/issue-50582.stderr @@ -16,14 +16,14 @@ LL | Vec::<[(); 1 + for x in 0..1 {}]>::new(); | = help: the trait `Add<()>` is not implemented for `{integer}` = help: the following other types implement trait `Add`: - `&'a f128` implements `Add` - `&'a f16` implements `Add` - `&'a f32` implements `Add` - `&'a f64` implements `Add` - `&'a i128` implements `Add` - `&'a i16` implements `Add` - `&'a i32` implements `Add` - `&'a i64` implements `Add` + `&f128` implements `Add` + `&f128` implements `Add` + `&f16` implements `Add` + `&f16` implements `Add` + `&f32` implements `Add` + `&f32` implements `Add` + `&f64` implements `Add` + `&f64` implements `Add` and 56 others error: aborting due to 2 previous errors diff --git a/tests/ui/iterators/invalid-iterator-chain-fixable.stderr b/tests/ui/iterators/invalid-iterator-chain-fixable.stderr index a7685e4938d88..3d3bbab881926 100644 --- a/tests/ui/iterators/invalid-iterator-chain-fixable.stderr +++ b/tests/ui/iterators/invalid-iterator-chain-fixable.stderr @@ -33,7 +33,7 @@ LL | println!("{}", scores.sum::()); | = help: the trait `Sum<()>` is not implemented for `i32` = help: the following other types implement trait `Sum`: - `i32` implements `Sum<&'a i32>` + `i32` implements `Sum<&i32>` `i32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/invalid-iterator-chain-fixable.rs:14:10 @@ -66,7 +66,7 @@ LL | .sum::(), | = help: the trait `Sum<()>` is not implemented for `i32` = help: the following other types implement trait `Sum`: - `i32` implements `Sum<&'a i32>` + `i32` implements `Sum<&i32>` `i32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/invalid-iterator-chain-fixable.rs:23:14 @@ -99,7 +99,7 @@ LL | println!("{}", vec![0, 1].iter().map(|x| { x; }).sum::()); | = help: the trait `Sum<()>` is not implemented for `i32` = help: the following other types implement trait `Sum`: - `i32` implements `Sum<&'a i32>` + `i32` implements `Sum<&i32>` `i32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/invalid-iterator-chain-fixable.rs:27:38 diff --git a/tests/ui/iterators/invalid-iterator-chain-with-int-infer.stderr b/tests/ui/iterators/invalid-iterator-chain-with-int-infer.stderr index 189f089ba51a7..1f1f7c99e5610 100644 --- a/tests/ui/iterators/invalid-iterator-chain-with-int-infer.stderr +++ b/tests/ui/iterators/invalid-iterator-chain-with-int-infer.stderr @@ -8,7 +8,7 @@ LL | let x = Some(()).iter().map(|()| 1).sum::(); | = help: the trait `Sum<{integer}>` is not implemented for `f32` = help: the following other types implement trait `Sum`: - `f32` implements `Sum<&'a f32>` + `f32` implements `Sum<&f32>` `f32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/invalid-iterator-chain-with-int-infer.rs:2:29 diff --git a/tests/ui/iterators/invalid-iterator-chain.stderr b/tests/ui/iterators/invalid-iterator-chain.stderr index f72a9f702dcec..bc35fcd489df5 100644 --- a/tests/ui/iterators/invalid-iterator-chain.stderr +++ b/tests/ui/iterators/invalid-iterator-chain.stderr @@ -33,7 +33,7 @@ LL | println!("{}", scores.sum::()); | = help: the trait `Sum<()>` is not implemented for `i32` = help: the following other types implement trait `Sum`: - `i32` implements `Sum<&'a i32>` + `i32` implements `Sum<&i32>` `i32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/invalid-iterator-chain.rs:12:10 @@ -65,7 +65,7 @@ LL | .sum::(), | = help: the trait `Sum<()>` is not implemented for `i32` = help: the following other types implement trait `Sum`: - `i32` implements `Sum<&'a i32>` + `i32` implements `Sum<&i32>` `i32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/invalid-iterator-chain.rs:25:14 @@ -104,7 +104,7 @@ LL | .sum::(), | = help: the trait `Sum` is not implemented for `i32` = help: the following other types implement trait `Sum`: - `i32` implements `Sum<&'a i32>` + `i32` implements `Sum<&i32>` `i32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/invalid-iterator-chain.rs:33:14 @@ -134,7 +134,7 @@ LL | println!("{}", vec![0, 1].iter().map(|x| { x; }).sum::()); | = help: the trait `Sum<()>` is not implemented for `i32` = help: the following other types implement trait `Sum`: - `i32` implements `Sum<&'a i32>` + `i32` implements `Sum<&i32>` `i32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/invalid-iterator-chain.rs:38:38 @@ -162,7 +162,7 @@ LL | println!("{}", vec![(), ()].iter().sum::()); | = help: the trait `Sum<&()>` is not implemented for `i32` = help: the following other types implement trait `Sum`: - `i32` implements `Sum<&'a i32>` + `i32` implements `Sum<&i32>` `i32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/invalid-iterator-chain.rs:39:33 diff --git a/tests/ui/kindck/kindck-impl-type-params.stderr b/tests/ui/kindck/kindck-impl-type-params.stderr index aad020e4ec97a..5892596dc6adc 100644 --- a/tests/ui/kindck/kindck-impl-type-params.stderr +++ b/tests/ui/kindck/kindck-impl-type-params.stderr @@ -112,13 +112,13 @@ LL | struct Foo; // does not impl Copy | error: lifetime may not live long enough - --> $DIR/kindck-impl-type-params.rs:30:13 + --> $DIR/kindck-impl-type-params.rs:30:19 | LL | fn foo<'a>() { | -- lifetime `'a` defined here LL | let t: S<&'a isize> = S(marker::PhantomData); LL | let a = &t as &dyn Gettable<&'a isize>; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` + | ^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` error: aborting due to 7 previous errors diff --git a/tests/ui/lazy-type-alias/trailing-where-clause.stderr b/tests/ui/lazy-type-alias/trailing-where-clause.stderr index 9fabbe91d25a4..93cd3145928b7 100644 --- a/tests/ui/lazy-type-alias/trailing-where-clause.stderr +++ b/tests/ui/lazy-type-alias/trailing-where-clause.stderr @@ -9,7 +9,7 @@ LL | let _: Alias<()>; `String` implements `From<&mut str>` `String` implements `From<&str>` `String` implements `From>` - `String` implements `From>` + `String` implements `From>` `String` implements `From` note: required by a bound in `Alias` --> $DIR/trailing-where-clause.rs:8:13 diff --git a/tests/ui/lifetimes/issue-90600-expected-return-static-indirect.stderr b/tests/ui/lifetimes/issue-90600-expected-return-static-indirect.stderr index 598f142419137..e4cd54ac33741 100644 --- a/tests/ui/lifetimes/issue-90600-expected-return-static-indirect.stderr +++ b/tests/ui/lifetimes/issue-90600-expected-return-static-indirect.stderr @@ -7,7 +7,7 @@ LL | let refcell = RefCell::new(&mut foo); | ^^^^^^^^ borrowed value does not live long enough LL | LL | let read = &refcell as &RefCell; - | -------- cast requires that `foo` is borrowed for `'static` + | ------------------------------ cast requires that `foo` is borrowed for `'static` ... LL | } | - `foo` dropped here while still borrowed @@ -19,7 +19,7 @@ LL | fn inner(mut foo: &[u8]) { | - let's call the lifetime of this reference `'1` ... LL | let read = &refcell as &RefCell; - | ^^^^^^^^ cast requires that `'1` must outlive `'static` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cast requires that `'1` must outlive `'static` error: aborting due to 2 previous errors diff --git a/tests/ui/lint/extern-C-fnptr-lints-slices.rs b/tests/ui/lint/extern-C-fnptr-lints-slices.rs new file mode 100644 index 0000000000000..0c35eb37a4890 --- /dev/null +++ b/tests/ui/lint/extern-C-fnptr-lints-slices.rs @@ -0,0 +1,9 @@ +#[deny(improper_ctypes_definitions)] + +// It's an improper ctype (a slice) arg in an extern "C" fnptr. + +pub type F = extern "C" fn(&[u8]); +//~^ ERROR: `extern` fn uses type `[u8]`, which is not FFI-safe + + +fn main() {} diff --git a/tests/ui/lint/extern-C-fnptr-lints-slices.stderr b/tests/ui/lint/extern-C-fnptr-lints-slices.stderr new file mode 100644 index 0000000000000..d13f93ca96f22 --- /dev/null +++ b/tests/ui/lint/extern-C-fnptr-lints-slices.stderr @@ -0,0 +1,16 @@ +error: `extern` fn uses type `[u8]`, which is not FFI-safe + --> $DIR/extern-C-fnptr-lints-slices.rs:5:14 + | +LL | pub type F = extern "C" fn(&[u8]); + | ^^^^^^^^^^^^^^^^^^^^ not FFI-safe + | + = help: consider using a raw pointer instead + = note: slices have no C equivalent +note: the lint level is defined here + --> $DIR/extern-C-fnptr-lints-slices.rs:1:8 + | +LL | #[deny(improper_ctypes_definitions)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/lint/improper-types-stack-overflow-130310.rs b/tests/ui/lint/improper-types-stack-overflow-130310.rs deleted file mode 100644 index 60eb873981756..0000000000000 --- a/tests/ui/lint/improper-types-stack-overflow-130310.rs +++ /dev/null @@ -1,20 +0,0 @@ -// Regression test for #130310 -// Tests that we do not fall into infinite -// recursion while checking FFI safety of -// recursive types like `A` below - -//@ build-pass -use std::marker::PhantomData; - -#[repr(C)] -struct A { - a: *const A>, // Recursive because of this field - p: PhantomData, -} - -extern "C" { - fn f(a: *const A<()>); - //~^ WARN `extern` block uses type `*const A<()>`, which is not FFI-safe -} - -fn main() {} diff --git a/tests/ui/lint/improper-types-stack-overflow-130310.stderr b/tests/ui/lint/improper-types-stack-overflow-130310.stderr deleted file mode 100644 index 6981bb2575542..0000000000000 --- a/tests/ui/lint/improper-types-stack-overflow-130310.stderr +++ /dev/null @@ -1,11 +0,0 @@ -warning: `extern` block uses type `*const A<()>`, which is not FFI-safe - --> $DIR/improper-types-stack-overflow-130310.rs:16:13 - | -LL | fn f(a: *const A<()>); - | ^^^^^^^^^^^^ not FFI-safe - | - = note: type is infinitely recursive - = note: `#[warn(improper_ctypes)]` on by default - -warning: 1 warning emitted - diff --git a/tests/ui/lint/lint-ctypes-non-recursion-limit.rs b/tests/ui/lint/lint-ctypes-non-recursion-limit.rs new file mode 100644 index 0000000000000..61e95dc5a464c --- /dev/null +++ b/tests/ui/lint/lint-ctypes-non-recursion-limit.rs @@ -0,0 +1,32 @@ +//@ check-pass + +#![recursion_limit = "5"] +#![allow(unused)] +#![deny(improper_ctypes)] + +#[repr(C)] +struct F1(*const ()); +#[repr(C)] +struct F2(*const ()); +#[repr(C)] +struct F3(*const ()); +#[repr(C)] +struct F4(*const ()); +#[repr(C)] +struct F5(*const ()); +#[repr(C)] +struct F6(*const ()); + +#[repr(C)] +struct B { + f1: F1, + f2: F2, + f3: F3, + f4: F4, + f5: F5, + f6: F6, +} + +extern "C" fn foo(_: B) {} + +fn main() {} diff --git a/tests/ui/lint/non-local-defs/cargo-update.rs b/tests/ui/lint/non-local-defs/cargo-update.rs index 3c62a655a9f61..8b8c15795d376 100644 --- a/tests/ui/lint/non-local-defs/cargo-update.rs +++ b/tests/ui/lint/non-local-defs/cargo-update.rs @@ -10,8 +10,6 @@ // of the `cargo update` suggestion we assert it here. //@ error-pattern: `cargo update -p non_local_macro` -#![warn(non_local_definitions)] - extern crate non_local_macro; struct LocalStruct; diff --git a/tests/ui/lint/non-local-defs/cargo-update.stderr b/tests/ui/lint/non-local-defs/cargo-update.stderr index 4dd41519455c6..77ee28b48cc7f 100644 --- a/tests/ui/lint/non-local-defs/cargo-update.stderr +++ b/tests/ui/lint/non-local-defs/cargo-update.stderr @@ -1,5 +1,5 @@ warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/cargo-update.rs:19:1 + --> $DIR/cargo-update.rs:17:1 | LL | non_local_macro::non_local_impl!(LocalStruct); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -10,15 +10,10 @@ LL | non_local_macro::non_local_impl!(LocalStruct); | = note: the macro `non_local_macro::non_local_impl` defines the non-local `impl`, and may need to be changed = note: the macro `non_local_macro::non_local_impl` may come from an old version of the `non_local_macro` crate, try updating your dependency with `cargo update -p non_local_macro` - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: items in an anonymous const item (`const _: () = { ... }`) are treated as in the same scope as the anonymous const's declaration for the purpose of this lint = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/cargo-update.rs:13:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(non_local_definitions)]` on by default = note: this warning originates in the macro `non_local_macro::non_local_impl` (in Nightly builds, run with -Z macro-backtrace for more info) warning: 1 warning emitted diff --git a/tests/ui/lint/non-local-defs/consts.rs b/tests/ui/lint/non-local-defs/consts.rs index e7ee611529b96..d8a497e43e502 100644 --- a/tests/ui/lint/non-local-defs/consts.rs +++ b/tests/ui/lint/non-local-defs/consts.rs @@ -2,8 +2,6 @@ //@ edition:2021 //@ rustc-env:CARGO_CRATE_NAME=non_local_def -#![warn(non_local_definitions)] - struct Test; trait Uto {} diff --git a/tests/ui/lint/non-local-defs/consts.stderr b/tests/ui/lint/non-local-defs/consts.stderr index ed7bd56fe4a54..7f76056c0210c 100644 --- a/tests/ui/lint/non-local-defs/consts.stderr +++ b/tests/ui/lint/non-local-defs/consts.stderr @@ -1,5 +1,5 @@ warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/consts.rs:15:5 + --> $DIR/consts.rs:13:5 | LL | const Z: () = { | ----------- @@ -8,23 +8,18 @@ LL | const Z: () = { | move the `impl` block outside of this constant `Z` ... LL | impl Uto for &Test {} - | ^^^^^---^^^^^----- - | | | - | | `&'_ Test` is not local + | ^^^^^---^^^^^^---- + | | | + | | `Test` is not local | `Uto` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: items in an anonymous const item (`const _: () = { ... }`) are treated as in the same scope as the anonymous const's declaration for the purpose of this lint = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/consts.rs:5:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(non_local_definitions)]` on by default warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/consts.rs:26:5 + --> $DIR/consts.rs:24:5 | LL | static A: u32 = { | ------------- move the `impl` block outside of this static `A` @@ -34,13 +29,12 @@ LL | impl Uto2 for Test {} | | `Test` is not local | `Uto2` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: items in an anonymous const item (`const _: () = { ... }`) are treated as in the same scope as the anonymous const's declaration for the purpose of this lint = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/consts.rs:34:5 + --> $DIR/consts.rs:32:5 | LL | const B: u32 = { | ------------ move the `impl` block outside of this constant `B` @@ -50,13 +44,12 @@ LL | impl Uto3 for Test {} | | `Test` is not local | `Uto3` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: items in an anonymous const item (`const _: () = { ... }`) are treated as in the same scope as the anonymous const's declaration for the purpose of this lint = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/consts.rs:45:5 + --> $DIR/consts.rs:43:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` @@ -65,11 +58,11 @@ LL | impl Test { | | | `Test` is not local | - = note: methods and associated constants are still usable outside the current expression, only `impl Local` and `impl dyn Local` can ever be private, and only if the type is nested in the same item as the `impl` + = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/consts.rs:52:9 + --> $DIR/consts.rs:50:9 | LL | const { | ___________- @@ -84,11 +77,11 @@ LL | | 1 LL | | }; | |_____- move the `impl` block outside of this inline constant `` and up 2 bodies | - = note: methods and associated constants are still usable outside the current expression, only `impl Local` and `impl dyn Local` can ever be private, and only if the type is nested in the same item as the `impl` + = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/consts.rs:61:9 + --> $DIR/consts.rs:59:9 | LL | const _: u32 = { | ------------ move the `impl` block outside of this constant `_` and up 2 bodies @@ -97,12 +90,12 @@ LL | impl Test { | | | `Test` is not local | - = note: methods and associated constants are still usable outside the current expression, only `impl Local` and `impl dyn Local` can ever be private, and only if the type is nested in the same item as the `impl` + = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: items in an anonymous const item (`const _: () = { ... }`) are treated as in the same scope as the anonymous const's declaration for the purpose of this lint = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/consts.rs:74:9 + --> $DIR/consts.rs:72:9 | LL | let _a = || { | -- move the `impl` block outside of this closure `` and up 2 bodies @@ -112,12 +105,11 @@ LL | impl Uto9 for Test {} | | `Test` is not local | `Uto9` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/consts.rs:81:9 + --> $DIR/consts.rs:79:9 | LL | type A = [u32; { | ____________________- @@ -131,7 +123,6 @@ LL | | LL | | }]; | |_____- move the `impl` block outside of this constant expression `` and up 2 bodies | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue diff --git a/tests/ui/lint/non-local-defs/exhaustive-trait.rs b/tests/ui/lint/non-local-defs/exhaustive-trait.rs index 79f8cc4620b97..40d2314460f86 100644 --- a/tests/ui/lint/non-local-defs/exhaustive-trait.rs +++ b/tests/ui/lint/non-local-defs/exhaustive-trait.rs @@ -1,8 +1,6 @@ //@ check-pass //@ edition:2021 -#![warn(non_local_definitions)] - struct Dog; fn main() { diff --git a/tests/ui/lint/non-local-defs/exhaustive-trait.stderr b/tests/ui/lint/non-local-defs/exhaustive-trait.stderr index 24c9a6b4f01e2..c58ec12aaacaa 100644 --- a/tests/ui/lint/non-local-defs/exhaustive-trait.stderr +++ b/tests/ui/lint/non-local-defs/exhaustive-trait.stderr @@ -1,5 +1,5 @@ warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive-trait.rs:9:5 + --> $DIR/exhaustive-trait.rs:7:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` @@ -9,92 +9,84 @@ LL | impl PartialEq<()> for Dog { | | `Dog` is not local | `PartialEq` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/exhaustive-trait.rs:4:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(non_local_definitions)]` on by default warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive-trait.rs:16:5 + --> $DIR/exhaustive-trait.rs:14:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl PartialEq<()> for &Dog { - | ^^^^^---------^^^^^^^^^---- - | | | - | | `&'_ Dog` is not local + | ^^^^^---------^^^^^^^^^^--- + | | | + | | `Dog` is not local | `PartialEq` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive-trait.rs:23:5 + --> $DIR/exhaustive-trait.rs:21:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl PartialEq for () { - | ^^^^^---------^^^^^^^^^^-- - | | | - | | `()` is not local + | ^^^^^---------^---^^^^^^^^ + | | | + | | `Dog` is not local | `PartialEq` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive-trait.rs:30:5 + --> $DIR/exhaustive-trait.rs:28:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl PartialEq<&Dog> for () { - | ^^^^^---------^^^^^^^^^^^-- - | | | - | | `()` is not local + | ^^^^^---------^^---^^^^^^^^ + | | | + | | `Dog` is not local | `PartialEq` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive-trait.rs:37:5 + --> $DIR/exhaustive-trait.rs:35:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl PartialEq for &Dog { - | ^^^^^---------^^^^^^^^^^---- - | | | - | | `&'_ Dog` is not local + | ^^^^^---------^---^^^^^^^--- + | | | | + | | | `Dog` is not local + | | `Dog` is not local | `PartialEq` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive-trait.rs:44:5 + --> $DIR/exhaustive-trait.rs:42:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl PartialEq<&Dog> for &Dog { - | ^^^^^---------^^^^^^^^^^^---- - | | | - | | `&'_ Dog` is not local + | ^^^^^---------^^---^^^^^^^--- + | | | | + | | | `Dog` is not local + | | `Dog` is not local | `PartialEq` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue diff --git a/tests/ui/lint/non-local-defs/exhaustive.rs b/tests/ui/lint/non-local-defs/exhaustive.rs index f59a85c7ed94f..5036e427060fc 100644 --- a/tests/ui/lint/non-local-defs/exhaustive.rs +++ b/tests/ui/lint/non-local-defs/exhaustive.rs @@ -1,8 +1,6 @@ //@ check-pass //@ edition:2021 -#![warn(non_local_definitions)] - use std::fmt::Display; trait Trait {} @@ -57,18 +55,13 @@ fn main() { struct InsideMain; + impl Trait for &InsideMain {} impl Trait for *mut InsideMain {} - //~^ WARN non-local `impl` definition impl Trait for *mut [InsideMain] {} - //~^ WARN non-local `impl` definition impl Trait for [InsideMain; 8] {} - //~^ WARN non-local `impl` definition impl Trait for (InsideMain,) {} - //~^ WARN non-local `impl` definition impl Trait for fn(InsideMain) -> () {} - //~^ WARN non-local `impl` definition impl Trait for fn() -> InsideMain {} - //~^ WARN non-local `impl` definition fn inside_inside() { impl Display for InsideMain { diff --git a/tests/ui/lint/non-local-defs/exhaustive.stderr b/tests/ui/lint/non-local-defs/exhaustive.stderr index 6d8c2ec0bc7cf..dd41b2206d842 100644 --- a/tests/ui/lint/non-local-defs/exhaustive.stderr +++ b/tests/ui/lint/non-local-defs/exhaustive.stderr @@ -1,5 +1,5 @@ warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:12:5 + --> $DIR/exhaustive.rs:10:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` @@ -8,16 +8,12 @@ LL | impl Test { | | | `Test` is not local | - = note: methods and associated constants are still usable outside the current expression, only `impl Local` and `impl dyn Local` can ever be private, and only if the type is nested in the same item as the `impl` + = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/exhaustive.rs:4:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(non_local_definitions)]` on by default warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:17:5 + --> $DIR/exhaustive.rs:15:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` @@ -28,12 +24,11 @@ LL | impl Display for Test { | | `Test` is not local | `Display` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:24:5 + --> $DIR/exhaustive.rs:22:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` @@ -43,11 +38,11 @@ LL | impl dyn Trait {} | | | `Trait` is not local | - = note: methods and associated constants are still usable outside the current expression, only `impl Local` and `impl dyn Local` can ever be private, and only if the type is nested in the same item as the `impl` + = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:27:5 + --> $DIR/exhaustive.rs:25:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` @@ -58,124 +53,116 @@ LL | impl Trait for Vec { } | | `Vec` is not local | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:30:5 + --> $DIR/exhaustive.rs:28:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl Trait for &dyn Trait {} - | ^^^^^-----^^^^^---------- - | | | - | | `&'_ dyn Trait` is not local + | ^^^^^-----^^^^^^^^^^----- + | | | + | | `Trait` is not local | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:33:5 + --> $DIR/exhaustive.rs:31:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl Trait for *mut Test {} - | ^^^^^-----^^^^^--------- - | | | - | | `*mut Test` is not local + | ^^^^^-----^^^^^^^^^^---- + | | | + | | `Test` is not local | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:36:5 + --> $DIR/exhaustive.rs:34:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl Trait for *mut [Test] {} - | ^^^^^-----^^^^^----------- - | | | - | | `*mut [Test]` is not local + | ^^^^^-----^^^^^^^^^^^----^ + | | | + | | `Test` is not local | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:39:5 + --> $DIR/exhaustive.rs:37:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl Trait for [Test; 8] {} - | ^^^^^-----^^^^^--------- - | | | - | | `[Test; 8]` is not local + | ^^^^^-----^^^^^^----^^^^ + | | | + | | `Test` is not local | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:42:5 + --> $DIR/exhaustive.rs:40:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl Trait for (Test,) {} - | ^^^^^-----^^^^^------- - | | | - | | `(Test,)` is not local + | ^^^^^-----^^^^^^----^^ + | | | + | | `Test` is not local | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:45:5 + --> $DIR/exhaustive.rs:43:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl Trait for fn(Test) -> () {} - | ^^^^^-----^^^^^-------------- - | | | - | | `fn(: Test) -> ()` is not local + | ^^^^^-----^^^^^^^^----^^^^^^^ + | | | + | | `Test` is not local | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:48:5 + --> $DIR/exhaustive.rs:46:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` ... LL | impl Trait for fn() -> Test {} - | ^^^^^-----^^^^^------------ - | | | - | | `fn() -> Test` is not local + | ^^^^^-----^^^^^^^^^^^^^---- + | | | + | | `Test` is not local | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:52:9 + --> $DIR/exhaustive.rs:50:9 | LL | let _a = || { | -- move the `impl` block outside of this closure `` and up 2 bodies @@ -185,139 +172,11 @@ LL | impl Trait for Test {} | | `Test` is not local | `Trait` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:60:5 - | -LL | impl Trait for *mut InsideMain {} - | ^^^^^-----^^^^^--------------- - | | | - | | `*mut InsideMain` is not local - | | help: remove `*mut ` to make the `impl` local - | `Trait` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/exhaustive.rs:11:1 - | -LL | fn main() { - | ^^^^^^^^^ -... -LL | struct InsideMain; - | ----------------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:62:5 - | -LL | impl Trait for *mut [InsideMain] {} - | ^^^^^-----^^^^^----------------- - | | | - | | `*mut [InsideMain]` is not local - | `Trait` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/exhaustive.rs:11:1 - | -LL | fn main() { - | ^^^^^^^^^ -... -LL | struct InsideMain; - | ----------------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:64:5 - | -LL | impl Trait for [InsideMain; 8] {} - | ^^^^^-----^^^^^--------------- - | | | - | | `[InsideMain; 8]` is not local - | `Trait` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/exhaustive.rs:11:1 - | -LL | fn main() { - | ^^^^^^^^^ -... -LL | struct InsideMain; - | ----------------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:66:5 - | -LL | impl Trait for (InsideMain,) {} - | ^^^^^-----^^^^^------------- - | | | - | | `(InsideMain,)` is not local - | `Trait` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/exhaustive.rs:11:1 - | -LL | fn main() { - | ^^^^^^^^^ -... -LL | struct InsideMain; - | ----------------- may need to be moved as well = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:68:5 - | -LL | impl Trait for fn(InsideMain) -> () {} - | ^^^^^-----^^^^^-------------------- - | | | - | | `fn(: InsideMain) -> ()` is not local - | `Trait` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/exhaustive.rs:11:1 - | -LL | fn main() { - | ^^^^^^^^^ -... -LL | struct InsideMain; - | ----------------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:70:5 - | -LL | impl Trait for fn() -> InsideMain {} - | ^^^^^-----^^^^^------------------ - | | | - | | `fn() -> InsideMain` is not local - | `Trait` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/exhaustive.rs:11:1 - | -LL | fn main() { - | ^^^^^^^^^ -... -LL | struct InsideMain; - | ----------------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:74:9 + --> $DIR/exhaustive.rs:67:9 | LL | fn inside_inside() { | ------------------ move the `impl` block outside of this function `inside_inside` and up 2 bodies @@ -327,12 +186,11 @@ LL | impl Display for InsideMain { | | `InsideMain` is not local | `Display` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/exhaustive.rs:81:9 + --> $DIR/exhaustive.rs:74:9 | LL | fn inside_inside() { | ------------------ move the `impl` block outside of this function `inside_inside` and up 2 bodies @@ -342,8 +200,8 @@ LL | impl InsideMain { | | | `InsideMain` is not local | - = note: methods and associated constants are still usable outside the current expression, only `impl Local` and `impl dyn Local` can ever be private, and only if the type is nested in the same item as the `impl` + = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -warning: 20 warnings emitted +warning: 14 warnings emitted diff --git a/tests/ui/lint/non-local-defs/from-local-for-global.rs b/tests/ui/lint/non-local-defs/from-local-for-global.rs index 1d8f4845c2860..6654fcc4f23d7 100644 --- a/tests/ui/lint/non-local-defs/from-local-for-global.rs +++ b/tests/ui/lint/non-local-defs/from-local-for-global.rs @@ -1,8 +1,6 @@ //@ check-pass //@ edition:2021 -#![warn(non_local_definitions)] - struct Cat; struct Wrap(T); @@ -18,7 +16,6 @@ fn main() { struct Elephant; impl From>> for () { - //~^ WARN non-local `impl` definition fn from(_: Wrap>) -> Self { todo!() } @@ -32,7 +29,6 @@ impl StillNonLocal for &str {} fn only_global() { struct Foo; impl StillNonLocal for &Foo {} - //~^ WARN non-local `impl` definition } struct GlobalSameFunction; @@ -40,7 +36,6 @@ struct GlobalSameFunction; fn same_function() { struct Local1(GlobalSameFunction); impl From for GlobalSameFunction { - //~^ WARN non-local `impl` definition fn from(x: Local1) -> GlobalSameFunction { x.0 } @@ -48,7 +43,6 @@ fn same_function() { struct Local2(GlobalSameFunction); impl From for GlobalSameFunction { - //~^ WARN non-local `impl` definition fn from(x: Local2) -> GlobalSameFunction { x.0 } @@ -61,8 +55,6 @@ fn diff_function_1() { struct Local(GlobalDifferentFunction); impl From for GlobalDifferentFunction { - // FIXME(Urgau): Should warn but doesn't since we currently consider - // the other impl to be "global", but that's not the case for the type-system fn from(x: Local) -> GlobalDifferentFunction { x.0 } @@ -73,8 +65,6 @@ fn diff_function_2() { struct Local(GlobalDifferentFunction); impl From for GlobalDifferentFunction { - // FIXME(Urgau): Should warn but doesn't since we currently consider - // the other impl to be "global", but that's not the case for the type-system fn from(x: Local) -> GlobalDifferentFunction { x.0 } diff --git a/tests/ui/lint/non-local-defs/from-local-for-global.stderr b/tests/ui/lint/non-local-defs/from-local-for-global.stderr index 04eba8435fc04..6839ebd2c8a3e 100644 --- a/tests/ui/lint/non-local-defs/from-local-for-global.stderr +++ b/tests/ui/lint/non-local-defs/from-local-for-global.stderr @@ -1,104 +1,17 @@ warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/from-local-for-global.rs:10:5 + --> $DIR/from-local-for-global.rs:8:5 | LL | fn main() { | --------- move the `impl` block outside of this function `main` LL | impl From for () { - | ^^^^^----^^^^^^^^^^-- - | | | - | | `()` is not local + | ^^^^^----^---^^^^^^^^ + | | | + | | `Cat` is not local | `From` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/from-local-for-global.rs:4:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/from-local-for-global.rs:20:5 - | -LL | impl From>> for () { - | ^^^^^----^^^^^^^^^^^^^^^^^^^^^^^^^^^-- - | | | - | `From` is not local `()` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/from-local-for-global.rs:9:1 - | -LL | fn main() { - | ^^^^^^^^^ -... -LL | struct Elephant; - | --------------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/from-local-for-global.rs:34:5 - | -LL | impl StillNonLocal for &Foo {} - | ^^^^^-------------^^^^^---- - | | | - | | `&'_ Foo` is not local - | | help: remove `&` to make the `impl` local - | `StillNonLocal` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `only_global` - --> $DIR/from-local-for-global.rs:32:1 - | -LL | fn only_global() { - | ^^^^^^^^^^^^^^^^ -LL | struct Foo; - | ---------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/from-local-for-global.rs:42:5 - | -LL | impl From for GlobalSameFunction { - | ^^^^^----^^^^^^^^^^^^^------------------ - | | | - | | `GlobalSameFunction` is not local - | `From` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `same_function` - --> $DIR/from-local-for-global.rs:40:1 - | -LL | fn same_function() { - | ^^^^^^^^^^^^^^^^^^ -LL | struct Local1(GlobalSameFunction); - | ------------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/from-local-for-global.rs:50:5 - | -LL | impl From for GlobalSameFunction { - | ^^^^^----^^^^^^^^^^^^^------------------ - | | | - | | `GlobalSameFunction` is not local - | `From` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `same_function` - --> $DIR/from-local-for-global.rs:40:1 - | -LL | fn same_function() { - | ^^^^^^^^^^^^^^^^^^ -... -LL | struct Local2(GlobalSameFunction); - | ------------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue + = note: `#[warn(non_local_definitions)]` on by default -warning: 5 warnings emitted +warning: 1 warning emitted diff --git a/tests/ui/lint/non-local-defs/generics.rs b/tests/ui/lint/non-local-defs/generics.rs index 13e392c510c64..381b3caacb6b5 100644 --- a/tests/ui/lint/non-local-defs/generics.rs +++ b/tests/ui/lint/non-local-defs/generics.rs @@ -1,8 +1,6 @@ //@ check-pass //@ edition:2021 -#![warn(non_local_definitions)] - trait Global {} fn main() { @@ -32,7 +30,6 @@ fn fun() { #[derive(Debug)] struct OwO; impl Default for UwU { - //~^ WARN non-local `impl` definition fn default() -> Self { UwU(OwO) } @@ -43,7 +40,6 @@ fn meow() { #[derive(Debug)] struct Cat; impl AsRef for () { - //~^ WARN non-local `impl` definition fn as_ref(&self) -> &Cat { &Cat } } } @@ -54,7 +50,6 @@ fn fun2() { #[derive(Debug, Default)] struct B; impl PartialEq for G { - //~^ WARN non-local `impl` definition fn eq(&self, _: &B) -> bool { true } @@ -69,14 +64,12 @@ fn rawr() { struct Lion; impl From>> for () { - //~^ WARN non-local `impl` definition fn from(_: Wrap>) -> Self { todo!() } } impl From<()> for Wrap { - //~^ WARN non-local `impl` definition fn from(_: ()) -> Self { todo!() } diff --git a/tests/ui/lint/non-local-defs/generics.stderr b/tests/ui/lint/non-local-defs/generics.stderr index 35366ed8ecf94..aefe8921fe2c7 100644 --- a/tests/ui/lint/non-local-defs/generics.stderr +++ b/tests/ui/lint/non-local-defs/generics.stderr @@ -1,165 +1,47 @@ warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/generics.rs:11:5 + --> $DIR/generics.rs:9:5 | +LL | fn main() { + | --------- move the `impl` block outside of this function `main` +... LL | impl Global for Vec { } | ^^^^^^^^^^^^^^^------^^^^^---^^^ | | | | | `Vec` is not local | `Global` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/generics.rs:8:1 - | -LL | fn main() { - | ^^^^^^^^^ -LL | trait Local {}; - | ----------- may need to be moved as well = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/generics.rs:4:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(non_local_definitions)]` on by default warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/generics.rs:22:5 + --> $DIR/generics.rs:20:5 | +LL | fn bad() { + | -------- move the `impl` block outside of this function `bad` +LL | struct Local; LL | impl Uto7 for Test where Local: std::any::Any {} | ^^^^^----^^^^^---- | | | | | `Test` is not local | `Uto7` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `bad` - --> $DIR/generics.rs:20:1 - | -LL | fn bad() { - | ^^^^^^^^ -LL | struct Local; - | ------------ may need to be moved as well = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/generics.rs:25:5 + --> $DIR/generics.rs:23:5 | LL | fn bad() { | -------- move the `impl` block outside of this function `bad` ... LL | impl Uto8 for T {} - | ^^^^^^^^----^^^^^- - | | | - | | `T` is not local + | ^^^^^^^^----^^^^^^ + | | | `Uto8` is not local | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/generics.rs:34:5 - | -LL | impl Default for UwU { - | ^^^^^-------^^^^^---^^^^^ - | | | - | | `UwU` is not local - | `Default` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `fun` - --> $DIR/generics.rs:31:1 - | -LL | fn fun() { - | ^^^^^^^^ -LL | #[derive(Debug)] -LL | struct OwO; - | ---------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/generics.rs:45:5 - | -LL | impl AsRef for () { - | ^^^^^-----^^^^^^^^^^-- - | | | - | | `()` is not local - | `AsRef` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `meow` - --> $DIR/generics.rs:42:1 - | -LL | fn meow() { - | ^^^^^^^^^ -LL | #[derive(Debug)] -LL | struct Cat; - | ---------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/generics.rs:56:5 - | -LL | impl PartialEq for G { - | ^^^^^---------^^^^^^^^- - | | | - | | `G` is not local - | `PartialEq` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `fun2` - --> $DIR/generics.rs:53:1 - | -LL | fn fun2() { - | ^^^^^^^^^ -LL | #[derive(Debug, Default)] -LL | struct B; - | -------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/generics.rs:71:5 - | -LL | impl From>> for () { - | ^^^^^----^^^^^^^^^^^^^^^^^^^^^^^-- - | | | - | `From` is not local `()` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `rawr` - --> $DIR/generics.rs:68:1 - | -LL | fn rawr() { - | ^^^^^^^^^ -LL | struct Lion; - | ----------- may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue - -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/generics.rs:78:5 - | -LL | impl From<()> for Wrap { - | ^^^^^----^^^^^^^^^----^^^^^^ - | | | - | | `Wrap` is not local - | `From` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `rawr` - --> $DIR/generics.rs:68:1 - | -LL | fn rawr() { - | ^^^^^^^^^ -LL | struct Lion; - | ----------- may need to be moved as well = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -warning: 8 warnings emitted +warning: 3 warnings emitted diff --git a/tests/ui/lint/non-local-defs/inside-macro_rules.rs b/tests/ui/lint/non-local-defs/inside-macro_rules.rs index 744a1f7a6f1ab..9f21cc89852e2 100644 --- a/tests/ui/lint/non-local-defs/inside-macro_rules.rs +++ b/tests/ui/lint/non-local-defs/inside-macro_rules.rs @@ -1,8 +1,6 @@ //@ check-pass //@ edition:2021 -#![warn(non_local_definitions)] - macro_rules! m { () => { trait MacroTrait {} diff --git a/tests/ui/lint/non-local-defs/inside-macro_rules.stderr b/tests/ui/lint/non-local-defs/inside-macro_rules.stderr index 89835372c8a53..faab6aea2b318 100644 --- a/tests/ui/lint/non-local-defs/inside-macro_rules.stderr +++ b/tests/ui/lint/non-local-defs/inside-macro_rules.stderr @@ -1,5 +1,5 @@ warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/inside-macro_rules.rs:11:13 + --> $DIR/inside-macro_rules.rs:9:13 | LL | fn my_func() { | ------------ move the `impl` block outside of this function `my_func` @@ -13,14 +13,9 @@ LL | m!(); | ---- in this macro invocation | = note: the macro `m` defines the non-local `impl`, and may need to be changed - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/inside-macro_rules.rs:4:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(non_local_definitions)]` on by default = note: this warning originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info) warning: 1 warning emitted diff --git a/tests/ui/lint/non-local-defs/local.rs b/tests/ui/lint/non-local-defs/local.rs index e9dbff1300f28..166ee88c0210c 100644 --- a/tests/ui/lint/non-local-defs/local.rs +++ b/tests/ui/lint/non-local-defs/local.rs @@ -1,8 +1,6 @@ //@ check-pass //@ edition:2021 -#![warn(non_local_definitions)] - use std::fmt::Debug; trait GlobalTrait {} diff --git a/tests/ui/lint/non-local-defs/macro_rules.rs b/tests/ui/lint/non-local-defs/macro_rules.rs index 20672cf0a3225..ed30a24903d01 100644 --- a/tests/ui/lint/non-local-defs/macro_rules.rs +++ b/tests/ui/lint/non-local-defs/macro_rules.rs @@ -3,8 +3,6 @@ //@ aux-build:non_local_macro.rs //@ rustc-env:CARGO_CRATE_NAME=non_local_def -#![warn(non_local_definitions)] - extern crate non_local_macro; const B: u32 = { diff --git a/tests/ui/lint/non-local-defs/macro_rules.stderr b/tests/ui/lint/non-local-defs/macro_rules.stderr index f9995bf82183c..4e86fc7b987e6 100644 --- a/tests/ui/lint/non-local-defs/macro_rules.stderr +++ b/tests/ui/lint/non-local-defs/macro_rules.stderr @@ -1,5 +1,5 @@ warning: non-local `macro_rules!` definition, `#[macro_export]` macro should be written at top level module - --> $DIR/macro_rules.rs:12:5 + --> $DIR/macro_rules.rs:10:5 | LL | macro_rules! m0 { () => { } }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -7,14 +7,10 @@ LL | macro_rules! m0 { () => { } }; = help: remove the `#[macro_export]` or move this `macro_rules!` outside the of the current constant `B` = note: a `macro_rules!` definition is non-local if it is nested inside an item and has a `#[macro_export]` attribute = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/macro_rules.rs:6:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(non_local_definitions)]` on by default warning: non-local `macro_rules!` definition, `#[macro_export]` macro should be written at top level module - --> $DIR/macro_rules.rs:18:1 + --> $DIR/macro_rules.rs:16:1 | LL | non_local_macro::non_local_macro_rules!(my_macro); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -26,7 +22,7 @@ LL | non_local_macro::non_local_macro_rules!(my_macro); = note: this warning originates in the macro `non_local_macro::non_local_macro_rules` (in Nightly builds, run with -Z macro-backtrace for more info) warning: non-local `macro_rules!` definition, `#[macro_export]` macro should be written at top level module - --> $DIR/macro_rules.rs:23:5 + --> $DIR/macro_rules.rs:21:5 | LL | macro_rules! m { () => { } }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ @@ -36,7 +32,7 @@ LL | macro_rules! m { () => { } }; = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `macro_rules!` definition, `#[macro_export]` macro should be written at top level module - --> $DIR/macro_rules.rs:31:13 + --> $DIR/macro_rules.rs:29:13 | LL | macro_rules! m2 { () => { } }; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/tests/ui/lint/non-local-defs/suggest-moving-inner.rs b/tests/ui/lint/non-local-defs/ref-complex.rs similarity index 76% rename from tests/ui/lint/non-local-defs/suggest-moving-inner.rs rename to tests/ui/lint/non-local-defs/ref-complex.rs index 9360ace4d805b..ce4e0a3dc0a19 100644 --- a/tests/ui/lint/non-local-defs/suggest-moving-inner.rs +++ b/tests/ui/lint/non-local-defs/ref-complex.rs @@ -1,7 +1,5 @@ //@ check-pass -#![warn(non_local_definitions)] - trait Trait {} fn main() { @@ -12,7 +10,6 @@ fn main() { trait HasFoo {} impl Trait for &Vec> - //~^ WARN non-local `impl` definition where T: HasFoo {} diff --git a/tests/ui/lint/non-local-defs/suggest-moving-inner.stderr b/tests/ui/lint/non-local-defs/suggest-moving-inner.stderr deleted file mode 100644 index a214415316f84..0000000000000 --- a/tests/ui/lint/non-local-defs/suggest-moving-inner.stderr +++ /dev/null @@ -1,33 +0,0 @@ -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/suggest-moving-inner.rs:14:5 - | -LL | impl Trait for &Vec> - | ^^^^^^^^-----^^^^^^^^^^^^^^^^^---------------------------------- - | | | - | | `&'_ Vec>` is not local - | `Trait` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/suggest-moving-inner.rs:7:1 - | -LL | fn main() { - | ^^^^^^^^^ -LL | mod below { -LL | pub struct Type(T); - | ------------------ may need to be moved as well -LL | } -LL | struct InsideMain; - | ----------------- may need to be moved as well -LL | trait HasFoo {} - | ------------ may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/suggest-moving-inner.rs:3:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ - -warning: 1 warning emitted - diff --git a/tests/ui/lint/non-local-defs/trait-solver-overflow-123573.rs b/tests/ui/lint/non-local-defs/trait-solver-overflow-123573.rs index b726398bf9c9a..6e8014f10f85a 100644 --- a/tests/ui/lint/non-local-defs/trait-solver-overflow-123573.rs +++ b/tests/ui/lint/non-local-defs/trait-solver-overflow-123573.rs @@ -3,8 +3,6 @@ // https://github.com/rust-lang/rust/issues/123573#issue-2229428739 -#![warn(non_local_definitions)] - pub trait Test {} impl<'a, T: 'a> Test for &[T] where &'a T: Test {} @@ -12,5 +10,4 @@ impl<'a, T: 'a> Test for &[T] where &'a T: Test {} fn main() { struct Local {} impl Test for &Local {} - //~^ WARN non-local `impl` definition } diff --git a/tests/ui/lint/non-local-defs/trait-solver-overflow-123573.stderr b/tests/ui/lint/non-local-defs/trait-solver-overflow-123573.stderr deleted file mode 100644 index 2eb71cecacaaf..0000000000000 --- a/tests/ui/lint/non-local-defs/trait-solver-overflow-123573.stderr +++ /dev/null @@ -1,28 +0,0 @@ -warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/trait-solver-overflow-123573.rs:14:5 - | -LL | impl Test for &Local {} - | ^^^^^----^^^^^------ - | | | - | | `&'_ Local` is not local - | | help: remove `&` to make the `impl` local - | `Test` is not local - | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type - = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` -help: move the `impl` block outside of this function `main` - --> $DIR/trait-solver-overflow-123573.rs:12:1 - | -LL | fn main() { - | ^^^^^^^^^ -LL | struct Local {} - | ------------ may need to be moved as well - = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/trait-solver-overflow-123573.rs:6:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ - -warning: 1 warning emitted - diff --git a/tests/ui/lint/non-local-defs/weird-exprs.rs b/tests/ui/lint/non-local-defs/weird-exprs.rs index fbf1fd941eecb..1d9cecea0c971 100644 --- a/tests/ui/lint/non-local-defs/weird-exprs.rs +++ b/tests/ui/lint/non-local-defs/weird-exprs.rs @@ -1,8 +1,6 @@ //@ check-pass //@ edition:2021 -#![warn(non_local_definitions)] - trait Uto {} struct Test; diff --git a/tests/ui/lint/non-local-defs/weird-exprs.stderr b/tests/ui/lint/non-local-defs/weird-exprs.stderr index 49aba904ebb0e..f6ce063929e8f 100644 --- a/tests/ui/lint/non-local-defs/weird-exprs.stderr +++ b/tests/ui/lint/non-local-defs/weird-exprs.stderr @@ -1,29 +1,24 @@ warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/weird-exprs.rs:10:5 + --> $DIR/weird-exprs.rs:8:5 | LL | type A = [u32; { | ________________- LL | | impl Uto for *mut Test {} - | | ^^^^^---^^^^^--------- - | | | | - | | | `*mut Test` is not local + | | ^^^^^---^^^^^^^^^^---- + | | | | + | | | `Test` is not local | | `Uto` is not local LL | | ... | LL | | }]; | |_- move the `impl` block outside of this constant expression `` | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue -note: the lint level is defined here - --> $DIR/weird-exprs.rs:4:9 - | -LL | #![warn(non_local_definitions)] - | ^^^^^^^^^^^^^^^^^^^^^ + = note: `#[warn(non_local_definitions)]` on by default warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/weird-exprs.rs:18:9 + --> $DIR/weird-exprs.rs:16:9 | LL | Discr = { | _____________- @@ -37,12 +32,11 @@ LL | | LL | | } | |_____- move the `impl` block outside of this constant expression `` | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/weird-exprs.rs:27:9 + --> $DIR/weird-exprs.rs:25:9 | LL | let _array = [0i32; { | _________________________- @@ -57,63 +51,61 @@ LL | | 1 LL | | }]; | |_____- move the `impl` block outside of this constant expression `` and up 2 bodies | - = note: methods and associated constants are still usable outside the current expression, only `impl Local` and `impl dyn Local` can ever be private, and only if the type is nested in the same item as the `impl` + = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/weird-exprs.rs:36:9 + --> $DIR/weird-exprs.rs:34:9 | LL | type A = [u32; { | ____________________- LL | | impl Uto for &Test {} - | | ^^^^^---^^^^^----- - | | | | - | | | `&'_ Test` is not local + | | ^^^^^---^^^^^^---- + | | | | + | | | `Test` is not local | | `Uto` is not local LL | | ... | LL | | }]; | |_____- move the `impl` block outside of this constant expression `` and up 2 bodies | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/weird-exprs.rs:43:9 + --> $DIR/weird-exprs.rs:41:9 | LL | fn a(_: [u32; { | ___________________- LL | | impl Uto for &(Test,) {} - | | ^^^^^---^^^^^-------- - | | | | - | | | `&'_ (Test,)` is not local + | | ^^^^^---^^^^^^^----^^ + | | | | + | | | `Test` is not local | | `Uto` is not local LL | | ... | LL | | }]) {} | |_____- move the `impl` block outside of this constant expression `` and up 2 bodies | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue warning: non-local `impl` definition, `impl` blocks should be written at the same level as their item - --> $DIR/weird-exprs.rs:50:9 + --> $DIR/weird-exprs.rs:48:9 | LL | fn b() -> [u32; { | _____________________- LL | | impl Uto for &(Test,Test) {} - | | ^^^^^---^^^^^------------ - | | | | - | | | `&'_ (Test, Test)` is not local + | | ^^^^^---^^^^^^^----^----^ + | | | | | + | | | | `Test` is not local + | | | `Test` is not local | | `Uto` is not local LL | | ... | LL | | }] { todo!() } | |_____- move the `impl` block outside of this constant expression `` and up 2 bodies | - = note: `impl` may be usable in bounds, etc. from outside the expression, which might e.g. make something constructible that previously wasn't, because it's still on a publicly-visible type = note: an `impl` is never scoped, even when it is nested inside an item, as it may impact type checking outside of that item, which can be the case if neither the trait or the self type are at the same nesting level as the `impl` = note: this lint may become deny-by-default in the edition 2024 and higher, see the tracking issue diff --git a/tests/ui/lint/unqualified_local_imports.rs b/tests/ui/lint/unqualified_local_imports.rs new file mode 100644 index 0000000000000..9de71471342dc --- /dev/null +++ b/tests/ui/lint/unqualified_local_imports.rs @@ -0,0 +1,38 @@ +//@compile-flags: --edition 2018 +#![feature(unqualified_local_imports)] +#![deny(unqualified_local_imports)] + +mod localmod { + pub struct S; + pub struct T; +} + +// Not a local import, so no lint. +use std::cell::Cell; + +// Implicitly local import, gets lint. +use localmod::S; //~ERROR: unqualified + +// Explicitly local import, no lint. +use self::localmod::T; + +macro_rules! mymacro { + ($cond:expr) => { + if !$cond { + continue; + } + }; +} +// Macro import: no lint, as there is no other way to write it. +pub(crate) use mymacro; + +#[allow(unused)] +enum LocalEnum { + VarA, + VarB, +} + +fn main() { + // Import in a function, no lint. + use LocalEnum::*; +} diff --git a/tests/ui/lint/unqualified_local_imports.stderr b/tests/ui/lint/unqualified_local_imports.stderr new file mode 100644 index 0000000000000..81d12f55949e3 --- /dev/null +++ b/tests/ui/lint/unqualified_local_imports.stderr @@ -0,0 +1,14 @@ +error: `use` of a local item without leading `self::`, `super::`, or `crate::` + --> $DIR/unqualified_local_imports.rs:14:5 + | +LL | use localmod::S; + | ^^^^^^^^ + | +note: the lint level is defined here + --> $DIR/unqualified_local_imports.rs:3:9 + | +LL | #![deny(unqualified_local_imports)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error: aborting due to 1 previous error + diff --git a/tests/ui/macros/break-last-token-twice.rs b/tests/ui/macros/break-last-token-twice.rs new file mode 100644 index 0000000000000..791f349ab38df --- /dev/null +++ b/tests/ui/macros/break-last-token-twice.rs @@ -0,0 +1,16 @@ +//@ check-pass + +macro_rules! m { + (static $name:ident: $t:ty = $e:expr) => { + let $name: $t = $e; + } +} + +fn main() { + m! { + // Tricky: the trailing `>>=` token here is broken twice: + // - into `>` and `>=` + // - then the `>=` is broken into `>` and `=` + static _x: Vec>= vec![] + } +} diff --git a/tests/ui/mir/early-otherwise-branch-ice.rs b/tests/ui/mir/early-otherwise-branch-ice.rs new file mode 100644 index 0000000000000..c1938eb75077b --- /dev/null +++ b/tests/ui/mir/early-otherwise-branch-ice.rs @@ -0,0 +1,18 @@ +// Changes in https://github.com/rust-lang/rust/pull/129047 lead to several mir-opt ICE regressions, +// this test is added to make sure this does not regress. + +//@ compile-flags: -C opt-level=3 +//@ check-pass + +#![crate_type = "lib"] + +use std::task::Poll; + +pub fn poll(val: Poll>, u8>>) { + match val { + Poll::Ready(Ok(Some(_trailers))) => {} + Poll::Ready(Err(_err)) => {} + Poll::Ready(Ok(None)) => {} + Poll::Pending => {} + } +} diff --git a/tests/ui/mismatched_types/binops.stderr b/tests/ui/mismatched_types/binops.stderr index 92f21a67c3707..c0cac5375230a 100644 --- a/tests/ui/mismatched_types/binops.stderr +++ b/tests/ui/mismatched_types/binops.stderr @@ -6,14 +6,14 @@ LL | 1 + Some(1); | = help: the trait `Add>` is not implemented for `{integer}` = help: the following other types implement trait `Add`: - `&'a f128` implements `Add` - `&'a f16` implements `Add` - `&'a f32` implements `Add` - `&'a f64` implements `Add` - `&'a i128` implements `Add` - `&'a i16` implements `Add` - `&'a i32` implements `Add` - `&'a i64` implements `Add` + `&f128` implements `Add` + `&f128` implements `Add` + `&f16` implements `Add` + `&f16` implements `Add` + `&f32` implements `Add` + `&f32` implements `Add` + `&f64` implements `Add` + `&f64` implements `Add` and 56 others error[E0277]: cannot subtract `Option<{integer}>` from `usize` @@ -24,8 +24,8 @@ LL | 2 as usize - Some(1); | = help: the trait `Sub>` is not implemented for `usize` = help: the following other types implement trait `Sub`: - `&'a usize` implements `Sub` - `&usize` implements `Sub<&usize>` + `&usize` implements `Sub` + `&usize` implements `Sub` `usize` implements `Sub<&usize>` `usize` implements `Sub` @@ -37,14 +37,14 @@ LL | 3 * (); | = help: the trait `Mul<()>` is not implemented for `{integer}` = help: the following other types implement trait `Mul`: - `&'a f128` implements `Mul` - `&'a f16` implements `Mul` - `&'a f32` implements `Mul` - `&'a f64` implements `Mul` - `&'a i128` implements `Mul` - `&'a i16` implements `Mul` - `&'a i32` implements `Mul` - `&'a i64` implements `Mul` + `&f128` implements `Mul` + `&f128` implements `Mul` + `&f16` implements `Mul` + `&f16` implements `Mul` + `&f32` implements `Mul` + `&f32` implements `Mul` + `&f64` implements `Mul` + `&f64` implements `Mul` and 57 others error[E0277]: cannot divide `{integer}` by `&str` @@ -55,14 +55,14 @@ LL | 4 / ""; | = help: the trait `Div<&str>` is not implemented for `{integer}` = help: the following other types implement trait `Div`: - `&'a f128` implements `Div` - `&'a f16` implements `Div` - `&'a f32` implements `Div` - `&'a f64` implements `Div` - `&'a i128` implements `Div` - `&'a i16` implements `Div` - `&'a i32` implements `Div` - `&'a i64` implements `Div` + `&f128` implements `Div` + `&f128` implements `Div` + `&f16` implements `Div` + `&f16` implements `Div` + `&f32` implements `Div` + `&f32` implements `Div` + `&f64` implements `Div` + `&f64` implements `Div` and 62 others error[E0277]: can't compare `{integer}` with `String` diff --git a/tests/ui/mismatched_types/cast-rfc0401.stderr b/tests/ui/mismatched_types/cast-rfc0401.stderr index 142a52aef13d0..3d12ba9899bc5 100644 --- a/tests/ui/mismatched_types/cast-rfc0401.stderr +++ b/tests/ui/mismatched_types/cast-rfc0401.stderr @@ -4,7 +4,7 @@ error[E0606]: casting `*const U` as `*const V` is invalid LL | u as *const V | ^^^^^^^^^^^^^ | - = note: vtable kinds may not match + = note: the pointers may have different metadata error[E0606]: casting `*const U` as `*const str` is invalid --> $DIR/cast-rfc0401.rs:8:5 @@ -12,7 +12,7 @@ error[E0606]: casting `*const U` as `*const str` is invalid LL | u as *const str | ^^^^^^^^^^^^^^^ | - = note: vtable kinds may not match + = note: the pointers may have different metadata error[E0609]: no field `f` on type `fn() {main}` --> $DIR/cast-rfc0401.rs:65:18 @@ -208,7 +208,7 @@ error[E0606]: casting `*const dyn Foo` as `*const [u16]` is invalid LL | let _ = cf as *const [u16]; | ^^^^^^^^^^^^^^^^^^ | - = note: vtable kinds may not match + = note: the pointers have different metadata error[E0606]: casting `*const dyn Foo` as `*const dyn Bar` is invalid --> $DIR/cast-rfc0401.rs:69:13 @@ -216,7 +216,7 @@ error[E0606]: casting `*const dyn Foo` as `*const dyn Bar` is invalid LL | let _ = cf as *const dyn Bar; | ^^^^^^^^^^^^^^^^^^^^ | - = note: vtable kinds may not match + = note: the trait objects may have different vtables error[E0277]: the size for values of type `[u8]` cannot be known at compilation time --> $DIR/cast-rfc0401.rs:53:13 diff --git a/tests/ui/never_type/issue-13352.stderr b/tests/ui/never_type/issue-13352.stderr index 7134e4d40a6a7..6818fa860051d 100644 --- a/tests/ui/never_type/issue-13352.stderr +++ b/tests/ui/never_type/issue-13352.stderr @@ -6,8 +6,8 @@ LL | 2_usize + (loop {}); | = help: the trait `Add<()>` is not implemented for `usize` = help: the following other types implement trait `Add`: - `&'a usize` implements `Add` - `&usize` implements `Add<&usize>` + `&usize` implements `Add` + `&usize` implements `Add` `usize` implements `Add<&usize>` `usize` implements `Add` diff --git a/tests/ui/nll/issue-54779-anon-static-lifetime.stderr b/tests/ui/nll/issue-54779-anon-static-lifetime.stderr index 92298c6617ff5..a454ed265685c 100644 --- a/tests/ui/nll/issue-54779-anon-static-lifetime.stderr +++ b/tests/ui/nll/issue-54779-anon-static-lifetime.stderr @@ -5,7 +5,7 @@ LL | cx: &dyn DebugContext, | - let's call the lifetime of this reference `'1` ... LL | bar.debug_with(cx); - | ^^ cast requires that `'1` must outlive `'static` + | ^^ coercion requires that `'1` must outlive `'static` error: aborting due to 1 previous error diff --git a/tests/ui/nll/user-annotations/cast_static_lifetime.stderr b/tests/ui/nll/user-annotations/cast_static_lifetime.stderr index 35eec233ed5c0..efd14fe875dbe 100644 --- a/tests/ui/nll/user-annotations/cast_static_lifetime.stderr +++ b/tests/ui/nll/user-annotations/cast_static_lifetime.stderr @@ -4,10 +4,9 @@ error[E0597]: `x` does not live long enough LL | let x = 22_u32; | - binding `x` declared here LL | let y: &u32 = (&x) as &'static u32; - | ^^^^---------------- + | ^^^^ ------------ type annotation requires that `x` is borrowed for `'static` | | | borrowed value does not live long enough - | type annotation requires that `x` is borrowed for `'static` LL | } | - `x` dropped here while still borrowed diff --git a/tests/ui/nll/user-annotations/type_ascription_static_lifetime.stderr b/tests/ui/nll/user-annotations/type_ascription_static_lifetime.stderr index 3e2706309b342..2ed0fadc06557 100644 --- a/tests/ui/nll/user-annotations/type_ascription_static_lifetime.stderr +++ b/tests/ui/nll/user-annotations/type_ascription_static_lifetime.stderr @@ -4,10 +4,9 @@ error[E0597]: `x` does not live long enough LL | let x = 22_u32; | - binding `x` declared here LL | let y: &u32 = type_ascribe!(&x, &'static u32); - | --------------^^--------------- - | | | - | | borrowed value does not live long enough - | type annotation requires that `x` is borrowed for `'static` + | ^^ ------------ type annotation requires that `x` is borrowed for `'static` + | | + | borrowed value does not live long enough LL | } | - `x` dropped here while still borrowed diff --git a/tests/ui/numbers-arithmetic/not-suggest-float-literal.stderr b/tests/ui/numbers-arithmetic/not-suggest-float-literal.stderr index a910666bd56ce..ec560fc5ed5c5 100644 --- a/tests/ui/numbers-arithmetic/not-suggest-float-literal.stderr +++ b/tests/ui/numbers-arithmetic/not-suggest-float-literal.stderr @@ -6,8 +6,8 @@ LL | x + 100.0 | = help: the trait `Add<{float}>` is not implemented for `u8` = help: the following other types implement trait `Add`: - `&'a u8` implements `Add` - `&u8` implements `Add<&u8>` + `&u8` implements `Add` + `&u8` implements `Add` `u8` implements `Add<&u8>` `u8` implements `Add` @@ -19,8 +19,8 @@ LL | x + "foo" | = help: the trait `Add<&str>` is not implemented for `f64` = help: the following other types implement trait `Add`: - `&'a f64` implements `Add` - `&f64` implements `Add<&f64>` + `&f64` implements `Add` + `&f64` implements `Add` `f64` implements `Add<&f64>` `f64` implements `Add` @@ -32,8 +32,8 @@ LL | x + y | = help: the trait `Add<{integer}>` is not implemented for `f64` = help: the following other types implement trait `Add`: - `&'a f64` implements `Add` - `&f64` implements `Add<&f64>` + `&f64` implements `Add` + `&f64` implements `Add` `f64` implements `Add<&f64>` `f64` implements `Add` @@ -45,8 +45,8 @@ LL | x - 100.0 | = help: the trait `Sub<{float}>` is not implemented for `u8` = help: the following other types implement trait `Sub`: - `&'a u8` implements `Sub` - `&u8` implements `Sub<&u8>` + `&u8` implements `Sub` + `&u8` implements `Sub` `u8` implements `Sub<&u8>` `u8` implements `Sub` @@ -58,8 +58,8 @@ LL | x - "foo" | = help: the trait `Sub<&str>` is not implemented for `f64` = help: the following other types implement trait `Sub`: - `&'a f64` implements `Sub` - `&f64` implements `Sub<&f64>` + `&f64` implements `Sub` + `&f64` implements `Sub` `f64` implements `Sub<&f64>` `f64` implements `Sub` @@ -71,8 +71,8 @@ LL | x - y | = help: the trait `Sub<{integer}>` is not implemented for `f64` = help: the following other types implement trait `Sub`: - `&'a f64` implements `Sub` - `&f64` implements `Sub<&f64>` + `&f64` implements `Sub` + `&f64` implements `Sub` `f64` implements `Sub<&f64>` `f64` implements `Sub` @@ -84,8 +84,8 @@ LL | x * 100.0 | = help: the trait `Mul<{float}>` is not implemented for `u8` = help: the following other types implement trait `Mul`: - `&'a u8` implements `Mul` - `&u8` implements `Mul<&u8>` + `&u8` implements `Mul` + `&u8` implements `Mul` `u8` implements `Mul<&u8>` `u8` implements `Mul` @@ -97,8 +97,8 @@ LL | x * "foo" | = help: the trait `Mul<&str>` is not implemented for `f64` = help: the following other types implement trait `Mul`: - `&'a f64` implements `Mul` - `&f64` implements `Mul<&f64>` + `&f64` implements `Mul` + `&f64` implements `Mul` `f64` implements `Mul<&f64>` `f64` implements `Mul` @@ -110,8 +110,8 @@ LL | x * y | = help: the trait `Mul<{integer}>` is not implemented for `f64` = help: the following other types implement trait `Mul`: - `&'a f64` implements `Mul` - `&f64` implements `Mul<&f64>` + `&f64` implements `Mul` + `&f64` implements `Mul` `f64` implements `Mul<&f64>` `f64` implements `Mul` @@ -123,8 +123,8 @@ LL | x / 100.0 | = help: the trait `Div<{float}>` is not implemented for `u8` = help: the following other types implement trait `Div`: - `&'a u8` implements `Div` - `&u8` implements `Div<&u8>` + `&u8` implements `Div` + `&u8` implements `Div` `u8` implements `Div<&u8>` `u8` implements `Div>` `u8` implements `Div` @@ -137,8 +137,8 @@ LL | x / "foo" | = help: the trait `Div<&str>` is not implemented for `f64` = help: the following other types implement trait `Div`: - `&'a f64` implements `Div` - `&f64` implements `Div<&f64>` + `&f64` implements `Div` + `&f64` implements `Div` `f64` implements `Div<&f64>` `f64` implements `Div` @@ -150,8 +150,8 @@ LL | x / y | = help: the trait `Div<{integer}>` is not implemented for `f64` = help: the following other types implement trait `Div`: - `&'a f64` implements `Div` - `&f64` implements `Div<&f64>` + `&f64` implements `Div` + `&f64` implements `Div` `f64` implements `Div<&f64>` `f64` implements `Div` diff --git a/tests/ui/numbers-arithmetic/suggest-float-literal.stderr b/tests/ui/numbers-arithmetic/suggest-float-literal.stderr index 8585ac485dbb2..d8bff8614a4e5 100644 --- a/tests/ui/numbers-arithmetic/suggest-float-literal.stderr +++ b/tests/ui/numbers-arithmetic/suggest-float-literal.stderr @@ -6,8 +6,8 @@ LL | x + 100 | = help: the trait `Add<{integer}>` is not implemented for `f32` = help: the following other types implement trait `Add`: - `&'a f32` implements `Add` - `&f32` implements `Add<&f32>` + `&f32` implements `Add` + `&f32` implements `Add` `f32` implements `Add<&f32>` `f32` implements `Add` help: consider using a floating-point literal by writing it with `.0` @@ -23,8 +23,8 @@ LL | x + 100 | = help: the trait `Add<{integer}>` is not implemented for `f64` = help: the following other types implement trait `Add`: - `&'a f64` implements `Add` - `&f64` implements `Add<&f64>` + `&f64` implements `Add` + `&f64` implements `Add` `f64` implements `Add<&f64>` `f64` implements `Add` help: consider using a floating-point literal by writing it with `.0` @@ -40,8 +40,8 @@ LL | x - 100 | = help: the trait `Sub<{integer}>` is not implemented for `f32` = help: the following other types implement trait `Sub`: - `&'a f32` implements `Sub` - `&f32` implements `Sub<&f32>` + `&f32` implements `Sub` + `&f32` implements `Sub` `f32` implements `Sub<&f32>` `f32` implements `Sub` help: consider using a floating-point literal by writing it with `.0` @@ -57,8 +57,8 @@ LL | x - 100 | = help: the trait `Sub<{integer}>` is not implemented for `f64` = help: the following other types implement trait `Sub`: - `&'a f64` implements `Sub` - `&f64` implements `Sub<&f64>` + `&f64` implements `Sub` + `&f64` implements `Sub` `f64` implements `Sub<&f64>` `f64` implements `Sub` help: consider using a floating-point literal by writing it with `.0` @@ -74,8 +74,8 @@ LL | x * 100 | = help: the trait `Mul<{integer}>` is not implemented for `f32` = help: the following other types implement trait `Mul`: - `&'a f32` implements `Mul` - `&f32` implements `Mul<&f32>` + `&f32` implements `Mul` + `&f32` implements `Mul` `f32` implements `Mul<&f32>` `f32` implements `Mul` help: consider using a floating-point literal by writing it with `.0` @@ -91,8 +91,8 @@ LL | x * 100 | = help: the trait `Mul<{integer}>` is not implemented for `f64` = help: the following other types implement trait `Mul`: - `&'a f64` implements `Mul` - `&f64` implements `Mul<&f64>` + `&f64` implements `Mul` + `&f64` implements `Mul` `f64` implements `Mul<&f64>` `f64` implements `Mul` help: consider using a floating-point literal by writing it with `.0` @@ -108,8 +108,8 @@ LL | x / 100 | = help: the trait `Div<{integer}>` is not implemented for `f32` = help: the following other types implement trait `Div`: - `&'a f32` implements `Div` - `&f32` implements `Div<&f32>` + `&f32` implements `Div` + `&f32` implements `Div` `f32` implements `Div<&f32>` `f32` implements `Div` help: consider using a floating-point literal by writing it with `.0` @@ -125,8 +125,8 @@ LL | x / 100 | = help: the trait `Div<{integer}>` is not implemented for `f64` = help: the following other types implement trait `Div`: - `&'a f64` implements `Div` - `&f64` implements `Div<&f64>` + `&f64` implements `Div` + `&f64` implements `Div` `f64` implements `Div<&f64>` `f64` implements `Div` help: consider using a floating-point literal by writing it with `.0` diff --git a/tests/ui/on-unimplemented/sum.stderr b/tests/ui/on-unimplemented/sum.stderr index f8e266a872782..d89cc2f7bf3b9 100644 --- a/tests/ui/on-unimplemented/sum.stderr +++ b/tests/ui/on-unimplemented/sum.stderr @@ -8,7 +8,7 @@ LL | vec![(), ()].iter().sum::(); | = help: the trait `Sum<&()>` is not implemented for `i32` = help: the following other types implement trait `Sum`: - `i32` implements `Sum<&'a i32>` + `i32` implements `Sum<&i32>` `i32` implements `Sum` note: the method call chain might not have had the expected associated types --> $DIR/sum.rs:4:18 @@ -30,7 +30,7 @@ LL | vec![(), ()].iter().product::(); | = help: the trait `Product<&()>` is not implemented for `i32` = help: the following other types implement trait `Product`: - `i32` implements `Product<&'a i32>` + `i32` implements `Product<&i32>` `i32` implements `Product` note: the method call chain might not have had the expected associated types --> $DIR/sum.rs:7:18 diff --git a/tests/ui/parser/block-no-opening-brace.rs b/tests/ui/parser/block-no-opening-brace.rs index e90a34104e8f5..2fde37ce6acef 100644 --- a/tests/ui/parser/block-no-opening-brace.rs +++ b/tests/ui/parser/block-no-opening-brace.rs @@ -4,28 +4,46 @@ fn main() {} -fn f1() { +fn in_loop() { loop let x = 0; //~ ERROR expected `{`, found keyword `let` drop(0); - } +} -fn f2() { +fn in_while() { while true let x = 0; //~ ERROR expected `{`, found keyword `let` - } +} -fn f3() { +fn in_for() { for x in 0..1 let x = 0; //~ ERROR expected `{`, found keyword `let` - } +} + -fn f4() { +// FIXME +fn in_try() { try //~ ERROR expected expression, found reserved keyword `try` let x = 0; - } +} -fn f5() { +// FIXME(#80931) +fn in_async() { async let x = 0; //~ ERROR expected one of `move`, `|`, or `||`, found keyword `let` +} + +// FIXME(#78168) +fn in_const() { + let x = const 2; //~ ERROR expected expression, found keyword `const` +} + +// FIXME(#78168) +fn in_const_in_match() { + let x = 2; + match x { + const 2 => {} + //~^ ERROR expected identifier, found keyword `const` + //~| ERROR expected one of `=>`, `if`, or `|`, found `2` } +} diff --git a/tests/ui/parser/block-no-opening-brace.stderr b/tests/ui/parser/block-no-opening-brace.stderr index f232f480ce9c2..83360944ed560 100644 --- a/tests/ui/parser/block-no-opening-brace.stderr +++ b/tests/ui/parser/block-no-opening-brace.stderr @@ -38,18 +38,36 @@ LL | { let x = 0; } | + + error: expected expression, found reserved keyword `try` - --> $DIR/block-no-opening-brace.rs:24:5 + --> $DIR/block-no-opening-brace.rs:26:5 | LL | try | ^^^ expected expression error: expected one of `move`, `|`, or `||`, found keyword `let` - --> $DIR/block-no-opening-brace.rs:30:9 + --> $DIR/block-no-opening-brace.rs:33:9 | LL | async | - expected one of `move`, `|`, or `||` LL | let x = 0; | ^^^ unexpected token -error: aborting due to 5 previous errors +error: expected expression, found keyword `const` + --> $DIR/block-no-opening-brace.rs:38:13 + | +LL | let x = const 2; + | ^^^^^ expected expression + +error: expected identifier, found keyword `const` + --> $DIR/block-no-opening-brace.rs:45:9 + | +LL | const 2 => {} + | ^^^^^ expected identifier, found keyword + +error: expected one of `=>`, `if`, or `|`, found `2` + --> $DIR/block-no-opening-brace.rs:45:15 + | +LL | const 2 => {} + | ^ expected one of `=>`, `if`, or `|` + +error: aborting due to 8 previous errors diff --git a/tests/ui/regions/regions-close-object-into-object-4.stderr b/tests/ui/regions/regions-close-object-into-object-4.stderr index b8b414b7e125e..f6a79be09477c 100644 --- a/tests/ui/regions/regions-close-object-into-object-4.stderr +++ b/tests/ui/regions/regions-close-object-into-object-4.stderr @@ -30,12 +30,11 @@ error[E0310]: the parameter type `U` may not live long enough --> $DIR/regions-close-object-into-object-4.rs:9:5 | LL | Box::new(B(&*v)) as Box - | ^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | the parameter type `U` must be valid for the static lifetime... | ...so that the type `U` will meet its required lifetime bounds | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` help: consider adding an explicit lifetime bound | LL | fn i<'a, T, U: 'static>(v: Box+'a>) -> Box { diff --git a/tests/ui/regions/regions-close-object-into-object-5.stderr b/tests/ui/regions/regions-close-object-into-object-5.stderr index 4a2f4f847a308..881d9e03cdfab 100644 --- a/tests/ui/regions/regions-close-object-into-object-5.stderr +++ b/tests/ui/regions/regions-close-object-into-object-5.stderr @@ -30,12 +30,11 @@ error[E0310]: the parameter type `T` may not live long enough --> $DIR/regions-close-object-into-object-5.rs:17:5 | LL | Box::new(B(&*v)) as Box - | ^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | the parameter type `T` must be valid for the static lifetime... | ...so that the type `T` will meet its required lifetime bounds | - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` help: consider adding an explicit lifetime bound | LL | fn f<'a, T: 'static, U>(v: Box + 'static>) -> Box { diff --git a/tests/ui/regions/regions-close-over-type-parameter-1.stderr b/tests/ui/regions/regions-close-over-type-parameter-1.stderr index 1cd5b7f225079..7c8c5fe5cf68b 100644 --- a/tests/ui/regions/regions-close-over-type-parameter-1.stderr +++ b/tests/ui/regions/regions-close-over-type-parameter-1.stderr @@ -2,7 +2,7 @@ error[E0310]: the parameter type `A` may not live long enough --> $DIR/regions-close-over-type-parameter-1.rs:11:5 | LL | Box::new(v) as Box - | ^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | the parameter type `A` must be valid for the static lifetime... | ...so that the type `A` will meet its required lifetime bounds @@ -18,7 +18,7 @@ error[E0309]: the parameter type `A` may not live long enough LL | fn make_object3<'a, 'b, A: SomeTrait + 'a>(v: A) -> Box { | -- the parameter type `A` must be valid for the lifetime `'b` as defined here... LL | Box::new(v) as Box - | ^^^^^^^^^^^ ...so that the type `A` will meet its required lifetime bounds + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...so that the type `A` will meet its required lifetime bounds | help: consider adding an explicit lifetime bound | diff --git a/tests/ui/span/multiline-span-simple.stderr b/tests/ui/span/multiline-span-simple.stderr index 2454769863b9c..d815f141fa090 100644 --- a/tests/ui/span/multiline-span-simple.stderr +++ b/tests/ui/span/multiline-span-simple.stderr @@ -6,8 +6,8 @@ LL | foo(1 as u32 + | = help: the trait `Add<()>` is not implemented for `u32` = help: the following other types implement trait `Add`: - `&'a u32` implements `Add` - `&u32` implements `Add<&u32>` + `&u32` implements `Add` + `&u32` implements `Add` `u32` implements `Add<&u32>` `u32` implements `Add` diff --git a/tests/ui/suggestions/imm-ref-trait-object-literal-bound-regions.stderr b/tests/ui/suggestions/imm-ref-trait-object-literal-bound-regions.stderr index 2733bbff36b54..530d868163b8d 100644 --- a/tests/ui/suggestions/imm-ref-trait-object-literal-bound-regions.stderr +++ b/tests/ui/suggestions/imm-ref-trait-object-literal-bound-regions.stderr @@ -6,7 +6,7 @@ LL | foo::(s); | | | required by a bound introduced by this call | - = help: the trait `Trait` is implemented for `&'a mut S` + = help: the trait `Trait` is implemented for `&mut S` = note: `for<'b> Trait` is implemented for `&'b mut S`, but not for `&'b S` note: required by a bound in `foo` --> $DIR/imm-ref-trait-object-literal-bound-regions.rs:11:20 diff --git a/tests/ui/suggestions/imm-ref-trait-object-literal.stderr b/tests/ui/suggestions/imm-ref-trait-object-literal.stderr index e01102e3864ea..79fa468dc4947 100644 --- a/tests/ui/suggestions/imm-ref-trait-object-literal.stderr +++ b/tests/ui/suggestions/imm-ref-trait-object-literal.stderr @@ -6,7 +6,7 @@ LL | foo(&s); | | | required by a bound introduced by this call | - = help: the trait `Trait` is implemented for `&'a mut S` + = help: the trait `Trait` is implemented for `&mut S` note: required by a bound in `foo` --> $DIR/imm-ref-trait-object-literal.rs:7:11 | diff --git a/tests/ui/suggestions/into-str.stderr b/tests/ui/suggestions/into-str.stderr index 6c1e1ec428fe7..ac6e531fee2b7 100644 --- a/tests/ui/suggestions/into-str.stderr +++ b/tests/ui/suggestions/into-str.stderr @@ -12,7 +12,7 @@ LL | foo(String::new()); `String` implements `From<&mut str>` `String` implements `From<&str>` `String` implements `From>` - `String` implements `From>` + `String` implements `From>` `String` implements `From` = note: required for `String` to implement `Into<&str>` note: required by a bound in `foo` diff --git a/tests/ui/suggestions/lifetimes/suggest-using-tick-underscore-lifetime-in-return-trait-object.stderr b/tests/ui/suggestions/lifetimes/suggest-using-tick-underscore-lifetime-in-return-trait-object.stderr index 73fa5ddb146e7..fa203150444c8 100644 --- a/tests/ui/suggestions/lifetimes/suggest-using-tick-underscore-lifetime-in-return-trait-object.stderr +++ b/tests/ui/suggestions/lifetimes/suggest-using-tick-underscore-lifetime-in-return-trait-object.stderr @@ -4,7 +4,7 @@ error: lifetime may not live long enough LL | fn foo(value: &T) -> Box { | - let's call the lifetime of this reference `'1` LL | Box::new(value) as Box - | ^^^^^^^^^^^^^^^ cast requires that `'1` must outlive `'static` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cast requires that `'1` must outlive `'static` | help: to declare that the trait object captures data from argument `value`, you can add an explicit `'_` lifetime bound | diff --git a/tests/ui/suggestions/remove-as_str.rs b/tests/ui/suggestions/remove-as_str.rs deleted file mode 100644 index 289a784ba6af3..0000000000000 --- a/tests/ui/suggestions/remove-as_str.rs +++ /dev/null @@ -1,21 +0,0 @@ -fn foo1(s: &str) { - s.as_str(); - //~^ ERROR no method named `as_str` found -} - -fn foo2<'a>(s: &'a str) { - s.as_str(); - //~^ ERROR no method named `as_str` found -} - -fn foo3(s: &mut str) { - s.as_str(); - //~^ ERROR no method named `as_str` found -} - -fn foo4(s: &&str) { - s.as_str(); - //~^ ERROR no method named `as_str` found -} - -fn main() {} diff --git a/tests/ui/suggestions/remove-as_str.stderr b/tests/ui/suggestions/remove-as_str.stderr deleted file mode 100644 index 534c497780a95..0000000000000 --- a/tests/ui/suggestions/remove-as_str.stderr +++ /dev/null @@ -1,27 +0,0 @@ -error[E0599]: no method named `as_str` found for reference `&str` in the current scope - --> $DIR/remove-as_str.rs:2:7 - | -LL | s.as_str(); - | -^^^^^^-- help: remove this method call - -error[E0599]: no method named `as_str` found for reference `&'a str` in the current scope - --> $DIR/remove-as_str.rs:7:7 - | -LL | s.as_str(); - | -^^^^^^-- help: remove this method call - -error[E0599]: no method named `as_str` found for mutable reference `&mut str` in the current scope - --> $DIR/remove-as_str.rs:12:7 - | -LL | s.as_str(); - | -^^^^^^-- help: remove this method call - -error[E0599]: no method named `as_str` found for reference `&&str` in the current scope - --> $DIR/remove-as_str.rs:17:7 - | -LL | s.as_str(); - | -^^^^^^-- help: remove this method call - -error: aborting due to 4 previous errors - -For more information about this error, try `rustc --explain E0599`. diff --git a/tests/ui/traits/incoherent-impl-ambiguity.rs b/tests/ui/traits/incoherent-impl-ambiguity.rs new file mode 100644 index 0000000000000..b5fed95e11c44 --- /dev/null +++ b/tests/ui/traits/incoherent-impl-ambiguity.rs @@ -0,0 +1,14 @@ +// Make sure that an invalid inherent impl doesn't totally clobber all of the +// other inherent impls, which lead to mysterious method/assoc-item probing errors. + +impl () {} +//~^ ERROR cannot define inherent `impl` for primitive types + +struct W; +impl W { + const CONST: u32 = 0; +} + +fn main() { + let _ = W::CONST; +} diff --git a/tests/ui/traits/incoherent-impl-ambiguity.stderr b/tests/ui/traits/incoherent-impl-ambiguity.stderr new file mode 100644 index 0000000000000..9c050a7295581 --- /dev/null +++ b/tests/ui/traits/incoherent-impl-ambiguity.stderr @@ -0,0 +1,11 @@ +error[E0390]: cannot define inherent `impl` for primitive types + --> $DIR/incoherent-impl-ambiguity.rs:4:1 + | +LL | impl () {} + | ^^^^^^^ + | + = help: consider using an extension trait instead + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0390`. diff --git a/tests/ui/traits/question-mark-result-err-mismatch.stderr b/tests/ui/traits/question-mark-result-err-mismatch.stderr index 66276bcbe3bb0..0e0ae6d59901f 100644 --- a/tests/ui/traits/question-mark-result-err-mismatch.stderr +++ b/tests/ui/traits/question-mark-result-err-mismatch.stderr @@ -35,7 +35,7 @@ LL | .map_err(|_| ())?; `String` implements `From<&mut str>` `String` implements `From<&str>` `String` implements `From>` - `String` implements `From>` + `String` implements `From>` `String` implements `From` = note: required for `Result<(), String>` to implement `FromResidual>` diff --git a/tests/ui/traits/suggest-dereferences/invalid-suggest-deref-issue-127590.stderr b/tests/ui/traits/suggest-dereferences/invalid-suggest-deref-issue-127590.stderr index a3ed51ace0880..85d6cdf779b44 100644 --- a/tests/ui/traits/suggest-dereferences/invalid-suggest-deref-issue-127590.stderr +++ b/tests/ui/traits/suggest-dereferences/invalid-suggest-deref-issue-127590.stderr @@ -23,7 +23,7 @@ LL | for (src, dest) in std::iter::zip(fields.iter(), &variant.iter()) { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&std::slice::Iter<'_, {integer}>` is not an iterator | = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>`, which is required by `Zip, &std::slice::Iter<'_, {integer}>>: IntoIterator` - = help: the trait `Iterator` is implemented for `std::slice::Iter<'a, T>` + = help: the trait `Iterator` is implemented for `std::slice::Iter<'_, T>` = note: required for `Zip, &std::slice::Iter<'_, {integer}>>` to implement `Iterator` = note: required for `Zip, &std::slice::Iter<'_, {integer}>>` to implement `IntoIterator` @@ -52,7 +52,7 @@ LL | for (src, dest) in std::iter::zip(fields.iter(), &variant.iter().clone( | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&std::slice::Iter<'_, {integer}>` is not an iterator | = help: the trait `Iterator` is not implemented for `&std::slice::Iter<'_, {integer}>`, which is required by `Zip, &std::slice::Iter<'_, {integer}>>: IntoIterator` - = help: the trait `Iterator` is implemented for `std::slice::Iter<'a, T>` + = help: the trait `Iterator` is implemented for `std::slice::Iter<'_, T>` = note: required for `Zip, &std::slice::Iter<'_, {integer}>>` to implement `Iterator` = note: required for `Zip, &std::slice::Iter<'_, {integer}>>` to implement `IntoIterator` diff --git a/tests/ui/traits/trait-object-lifetime-default-note.rs b/tests/ui/traits/trait-object-lifetime-default-note.rs index 31e3eb4ba4155..275411ff61c85 100644 --- a/tests/ui/traits/trait-object-lifetime-default-note.rs +++ b/tests/ui/traits/trait-object-lifetime-default-note.rs @@ -8,7 +8,7 @@ fn main() { //~| NOTE borrowed value does not live long enough //~| NOTE due to object lifetime defaults, `Box` actually means `Box<(dyn A + 'static)>` require_box(Box::new(r)); - //~^ NOTE cast requires that `local` is borrowed for `'static` + //~^ NOTE coercion requires that `local` is borrowed for `'static` let _ = 0; } //~ NOTE `local` dropped here while still borrowed diff --git a/tests/ui/traits/trait-object-lifetime-default-note.stderr b/tests/ui/traits/trait-object-lifetime-default-note.stderr index 4244e34873ad1..8cb9bc0d80072 100644 --- a/tests/ui/traits/trait-object-lifetime-default-note.stderr +++ b/tests/ui/traits/trait-object-lifetime-default-note.stderr @@ -7,7 +7,7 @@ LL | let r = &local; | ^^^^^^ borrowed value does not live long enough ... LL | require_box(Box::new(r)); - | ----------- cast requires that `local` is borrowed for `'static` + | ----------- coercion requires that `local` is borrowed for `'static` ... LL | } | - `local` dropped here while still borrowed diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-3.stderr b/tests/ui/traits/trait-upcasting/type-checking-test-3.stderr index e6cb6a753998f..0a969b611e9d3 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-3.stderr +++ b/tests/ui/traits/trait-upcasting/type-checking-test-3.stderr @@ -1,18 +1,18 @@ error: lifetime may not live long enough - --> $DIR/type-checking-test-3.rs:11:13 + --> $DIR/type-checking-test-3.rs:11:18 | LL | fn test_wrong1<'a>(x: &dyn Foo<'static>, y: &'a u32) { | -- lifetime `'a` defined here LL | let _ = x as &dyn Bar<'a>; // Error - | ^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` + | ^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` error: lifetime may not live long enough - --> $DIR/type-checking-test-3.rs:16:13 + --> $DIR/type-checking-test-3.rs:16:18 | LL | fn test_wrong2<'a>(x: &dyn Foo<'a>) { | -- lifetime `'a` defined here LL | let _ = x as &dyn Bar<'static>; // Error - | ^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` + | ^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` error: aborting due to 2 previous errors diff --git a/tests/ui/traits/trait-upcasting/type-checking-test-4.stderr b/tests/ui/traits/trait-upcasting/type-checking-test-4.stderr index ccced5875778d..090120a2327a8 100644 --- a/tests/ui/traits/trait-upcasting/type-checking-test-4.stderr +++ b/tests/ui/traits/trait-upcasting/type-checking-test-4.stderr @@ -1,18 +1,18 @@ error: lifetime may not live long enough - --> $DIR/type-checking-test-4.rs:19:13 + --> $DIR/type-checking-test-4.rs:19:18 | LL | fn test_wrong1<'a>(x: &dyn Foo<'static>, y: &'a u32) { | -- lifetime `'a` defined here LL | let _ = x as &dyn Bar<'static, 'a>; // Error - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` + | ^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` error: lifetime may not live long enough - --> $DIR/type-checking-test-4.rs:24:13 + --> $DIR/type-checking-test-4.rs:24:18 | LL | fn test_wrong2<'a>(x: &dyn Foo<'static>, y: &'a u32) { | -- lifetime `'a` defined here LL | let _ = x as &dyn Bar<'a, 'static>; // Error - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` + | ^^^^^^^^^^^^^^^^^^^^^ type annotation requires that `'a` must outlive `'static` error: lifetime may not live long enough --> $DIR/type-checking-test-4.rs:30:5 diff --git a/tests/ui/traits/upcast_soundness_bug.rs b/tests/ui/traits/upcast_soundness_bug.rs index 5eaa58f7efe7f..0ddae1d1417c7 100644 --- a/tests/ui/traits/upcast_soundness_bug.rs +++ b/tests/ui/traits/upcast_soundness_bug.rs @@ -57,7 +57,7 @@ pub fn user2() -> &'static dyn Trait { fn main() { let p: *const dyn Trait = &(); let p = p as *const dyn Trait; // <- this is bad! - //~^ error: mismatched types + //~^ error: casting `*const dyn Trait` as `*const dyn Trait` is invalid let p = p as *const dyn Super; // <- this upcast accesses improper vtable entry // accessing from L__unnamed_2 the position for the 'Super vtable (pointer)', // thus reading 'null pointer for missing_method' diff --git a/tests/ui/traits/upcast_soundness_bug.stderr b/tests/ui/traits/upcast_soundness_bug.stderr index 5864abcdb41f5..19d1a5e5926e0 100644 --- a/tests/ui/traits/upcast_soundness_bug.stderr +++ b/tests/ui/traits/upcast_soundness_bug.stderr @@ -1,13 +1,11 @@ -error[E0308]: mismatched types +error[E0606]: casting `*const dyn Trait` as `*const dyn Trait` is invalid --> $DIR/upcast_soundness_bug.rs:59:13 | LL | let p = p as *const dyn Trait; // <- this is bad! - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `u8`, found `u16` + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | - = note: expected trait object `dyn Trait` - found trait object `dyn Trait` - = help: `dyn Trait` implements `Trait` so you could box the found value and coerce it to the trait object `Box`, you will have to change the expected type as well + = note: the trait objects may have different vtables error: aborting due to 1 previous error -For more information about this error, try `rustc --explain E0308`. +For more information about this error, try `rustc --explain E0606`. diff --git a/tests/ui/type/type-check-defaults.stderr b/tests/ui/type/type-check-defaults.stderr index 499e8142cc8f4..9c48250612971 100644 --- a/tests/ui/type/type-check-defaults.stderr +++ b/tests/ui/type/type-check-defaults.stderr @@ -66,8 +66,8 @@ LL | trait ProjectionPred> where T::Item : Add {} | = help: the trait `Add` is not implemented for `i32` = help: the following other types implement trait `Add`: - `&'a i32` implements `Add` - `&i32` implements `Add<&i32>` + `&i32` implements `Add` + `&i32` implements `Add` `i32` implements `Add<&i32>` `i32` implements `Add` diff --git a/tests/ui/typeck/issue-81293.stderr b/tests/ui/typeck/issue-81293.stderr index 3c48db335b5f0..82661fc717233 100644 --- a/tests/ui/typeck/issue-81293.stderr +++ b/tests/ui/typeck/issue-81293.stderr @@ -21,8 +21,8 @@ LL | a = c + b * 5; | = help: the trait `Add` is not implemented for `usize` = help: the following other types implement trait `Add`: - `&'a usize` implements `Add` - `&usize` implements `Add<&usize>` + `&usize` implements `Add` + `&usize` implements `Add` `usize` implements `Add<&usize>` `usize` implements `Add` diff --git a/tests/ui/typeck/issue-90101.stderr b/tests/ui/typeck/issue-90101.stderr index d6832d1b34ffc..796e904a43829 100644 --- a/tests/ui/typeck/issue-90101.stderr +++ b/tests/ui/typeck/issue-90101.stderr @@ -9,7 +9,7 @@ LL | func(Path::new("hello").to_path_buf().to_string_lossy(), "world") = help: the following other types implement trait `From`: `PathBuf` implements `From<&T>` `PathBuf` implements `From>` - `PathBuf` implements `From>` + `PathBuf` implements `From>` `PathBuf` implements `From` `PathBuf` implements `From` = note: required for `Cow<'_, str>` to implement `Into` diff --git a/tests/ui/ufcs/ufcs-qpath-self-mismatch.stderr b/tests/ui/ufcs/ufcs-qpath-self-mismatch.stderr index a0430240dc43b..f8be11a24e3da 100644 --- a/tests/ui/ufcs/ufcs-qpath-self-mismatch.stderr +++ b/tests/ui/ufcs/ufcs-qpath-self-mismatch.stderr @@ -6,8 +6,8 @@ LL | >::add(1, 2); | = help: the trait `Add` is not implemented for `i32` = help: the following other types implement trait `Add`: - `&'a i32` implements `Add` - `&i32` implements `Add<&i32>` + `&i32` implements `Add` + `&i32` implements `Add` `i32` implements `Add<&i32>` `i32` implements `Add` @@ -63,8 +63,8 @@ LL | >::add(1, 2); | = help: the trait `Add` is not implemented for `i32` = help: the following other types implement trait `Add`: - `&'a i32` implements `Add` - `&i32` implements `Add<&i32>` + `&i32` implements `Add` + `&i32` implements `Add` `i32` implements `Add<&i32>` `i32` implements `Add` diff --git a/triagebot.toml b/triagebot.toml index a6a0b02d7b710..5d80b9e656ea0 100644 --- a/triagebot.toml +++ b/triagebot.toml @@ -923,10 +923,8 @@ contributing_url = "https://rustc-dev-guide.rust-lang.org/getting-started.html" users_on_vacation = [ "fmease", "jhpratt", - "joboet", "jyn514", "oli-obk", - "tgross35", ] [assign.adhoc_groups]