From b7424e992da9469bae8c5e3d86d757a3bc15f64a Mon Sep 17 00:00:00 2001 From: TechnoPorg Date: Tue, 27 Oct 2026 08:16:03 -0400 Subject: [PATCH 01/39] Parse TPDE compiler flag --- compiler/rustc_interface/src/tests.rs | 10 ++++++---- compiler/rustc_session/src/config.rs | 11 ++++++++++- compiler/rustc_session/src/options.rs | 11 +++++++++++ .../unstable-book/src/compiler-flags/llvm-tpde.md | 12 ++++++++++++ 4 files changed, 39 insertions(+), 5 deletions(-) create mode 100644 src/doc/unstable-book/src/compiler-flags/llvm-tpde.md diff --git a/compiler/rustc_interface/src/tests.rs b/compiler/rustc_interface/src/tests.rs index fd54da09bdca6..a2ae6f8399360 100644 --- a/compiler/rustc_interface/src/tests.rs +++ b/compiler/rustc_interface/src/tests.rs @@ -14,10 +14,10 @@ use rustc_session::config::{ CoverageOptions, DebugInfo, DumpMonoStatsFormat, ErrorOutputType, ExternEntry, ExternLocation, Externs, FmtDebug, FunctionReturn, IncrementalStateAssertion, InliningThreshold, Input, InstrumentCoverage, InstrumentMcount, InstrumentMcountOpts, InstrumentXRay, LinkSelfContained, - LinkerPluginLto, LocationDetail, LtoCli, MirIncludeSpans, NextSolverConfig, Offload, Options, - OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, PatchableFunctionEntry, - Polonius, ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion, - WasiExecModel, build_session_options, rustc_optgroups, + LinkerPluginLto, LlvmTpde, LocationDetail, LtoCli, MirIncludeSpans, NextSolverConfig, Offload, + Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, + PatchableFunctionEntry, Polonius, ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, + SymbolManglingVersion, WasiExecModel, build_session_options, rustc_optgroups, }; use rustc_session::search_paths::SearchPath; use rustc_session::utils::{CanonicalizedPath, NativeLib}; @@ -846,6 +846,8 @@ fn test_unstable_options_tracking_hash() { tracked!(lint_llvm_ir, true); tracked!(llvm_module_flag, vec![("bar".to_string(), 123, "max".to_string())]); tracked!(llvm_plugins, vec![String::from("plugin_name")]); + tracked!(llvm_tpde, Some(LlvmTpde::Only)); + tracked!(llvm_tpde, Some(LlvmTpde::Try)); tracked!(llvm_writable, true); tracked!(location_detail, LocationDetail { file: true, line: false, column: false }); tracked!(maximal_hir_to_mir_coverage, true); diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 2665cb92fc8d0..ac4c542b1285a 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -3429,6 +3429,14 @@ impl PpMode { } } +#[derive(Clone, Hash, PartialEq, Eq, Debug)] +pub enum LlvmTpde { + /// Attempt to compile with TPDE-LLVM, but fall back to LLVM if unsupported LLVM IR is encountered + Try, + /// Attempt to compile with TPDE-LLVM, and bail if unsupported LLVM IR is encountered + Only, +} + #[derive(Clone, Hash, PartialEq, Eq, Debug)] pub enum WasiExecModel { Command, @@ -3479,7 +3487,7 @@ pub(crate) mod dep_tracking { AnnotateMoves, AutoDiff, BranchProtection, CFGuard, CFProtection, CodegenRetagOptions, CoverageOptions, CrateType, DebugInfo, DebugInfoCompression, ErrorOutputType, FmtDebug, FunctionReturn, InliningThreshold, InstrumentCoverage, InstrumentMcount, - InstrumentMcountOpts, InstrumentXRay, LinkerPluginLto, LocationDetail, LtoCli, + InstrumentMcountOpts, InstrumentXRay, LinkerPluginLto, LlvmTpde, LocationDetail, LtoCli, MirStripDebugInfo, NextSolverConfig, Offload, OptLevel, OutFileName, OutputType, OutputTypes, PatchableFunctionEntry, PointerAuthOption, Polonius, ResolveDocLinks, SourceFileHashAlgorithm, SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion, @@ -3552,6 +3560,7 @@ pub(crate) mod dep_tracking { InstrumentXRay, LanguageIdentifier, LinkerPluginLto, + LlvmTpde, LocationDetail, LtoCli, MergeFunctions, diff --git a/compiler/rustc_session/src/options.rs b/compiler/rustc_session/src/options.rs index ef503a627a40f..1237ea342b462 100644 --- a/compiler/rustc_session/src/options.rs +++ b/compiler/rustc_session/src/options.rs @@ -932,6 +932,7 @@ mod desc { pub(crate) const parse_target_feature: &str = parse_string; pub(crate) const parse_terminal_url: &str = "either a boolean (`yes`, `no`, `on`, `off`, etc), or `auto`"; + pub(crate) const parse_llvm_tpde: &str = "either no value or one of: `try` (default), `only`"; pub(crate) const parse_wasi_exec_model: &str = "either `command` or `reactor`"; pub(crate) const parse_split_debuginfo: &str = "one of supported split-debuginfo modes (`off`, `packed`, or `unpacked`)"; @@ -1929,6 +1930,15 @@ pub mod parse { true } + pub(crate) fn parse_llvm_tpde(slot: &mut Option, v: Option<&str>) -> bool { + *slot = match v { + Some("try") | None => Some(LlvmTpde::Try), + Some("only") => Some(LlvmTpde::Only), + _ => return false, + }; + true + } + pub(crate) fn parse_symbol_mangling_version( slot: &mut Option, v: Option<&str>, @@ -2982,6 +2992,7 @@ written to standard error output)"), #[rustc_lint_opt_deny_field_access("use `Session::tls_model` instead of this field")] tls_model: Option = (None, parse_tls_model, [TRACKED], "choose the TLS model to use (`rustc --print tls-models` for details)"), + llvm_tpde: Option = (None, parse_llvm_tpde, [TRACKED], "enable the experimental TPDE-LLVM codegen backend for debug builds"), trace_macros: bool = (false, parse_bool, [UNTRACKED], "for every macro invocation, print its name and arguments (default: no)"), track_diagnostics: bool = (false, parse_bool, [UNTRACKED], diff --git a/src/doc/unstable-book/src/compiler-flags/llvm-tpde.md b/src/doc/unstable-book/src/compiler-flags/llvm-tpde.md new file mode 100644 index 0000000000000..24b8eeef6585c --- /dev/null +++ b/src/doc/unstable-book/src/compiler-flags/llvm-tpde.md @@ -0,0 +1,12 @@ +# `llvm-tpde` + +The tracking issue for this feature is: None. + +--- + +The `-Zllvm-tpde[=VALUE]` compiler flag controls whether TPDE-LLVM is used as the codegen backend for debug builds instead of LLVM. If not set, LLVM is used. + +Possible values are: + +- `try` (default): attempt to compile with TPDE-LLVM, but fall back to LLVM if unsupported IR is encountered +- `only`: attempt to compile with TPDE-LLVM, and bail if unsupported IR is encountered From e04949913097bed6c9137eda3c7199240f87a4d0 Mon Sep 17 00:00:00 2001 From: TechnoPorg Date: Tue, 27 Oct 2026 08:17:29 -0400 Subject: [PATCH 02/39] Implement TPDE backend in rustc_codegen_llvm --- .../src/back/llvm_backend.rs | 41 +++++- compiler/rustc_codegen_llvm/src/back/write.rs | 5 +- .../rustc_codegen_llvm/src/diagnostics.rs | 27 ++++ compiler/rustc_codegen_llvm/src/llvm/ffi.rs | 4 +- compiler/rustc_codegen_llvm/src/llvm/mod.rs | 2 + .../rustc_codegen_llvm/src/llvm/tpde_ffi.rs | 125 ++++++++++++++++++ .../rustc_llvm/llvm-wrapper/PassWrapper.cpp | 38 +++++- .../rustc_macros/src/diagnostics/message.rs | 1 + 8 files changed, 233 insertions(+), 10 deletions(-) create mode 100644 compiler/rustc_codegen_llvm/src/llvm/tpde_ffi.rs diff --git a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs index 7864d0cc81491..a9d152ec48a61 100644 --- a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs +++ b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs @@ -22,12 +22,12 @@ use rustc_errors::{DiagCtxt, DiagCtxtHandle}; use rustc_metadata::EncodedMetadata; use rustc_middle::dep_graph::{WorkProduct, WorkProductMap}; use rustc_middle::ty::TyCtxt; -use rustc_session::config::{OutputFilenames, PrintKind, PrintRequest}; +use rustc_session::config::{LtoCli, OptLevel, OutputFilenames, PrintKind, PrintRequest}; use rustc_session::{ BorrowedIncrCompSession, CodegenBackendInit, EarlySession, IncrCompSession, Session, }; use rustc_span::{Symbol, sym}; -use rustc_target::spec::{RelocModel, TlsModel}; +use rustc_target::spec::{RelocModel, SplitDebuginfo, TlsModel}; use crate::back::owned_target_machine::OwnedTargetMachine; use crate::back::write::{create_informational_target_machine, create_target_machine}; @@ -209,6 +209,43 @@ impl CodegenBackend for LlvmCodegenBackend { } } + // -Zllvm-tpde requires the TPDE pass plugin, which may not be available. If TPDE is used but not available, + // we emit an early error here and abort compilation. + { + match llvm::TpdeWrapper::get_or_init( + &sess.opts.sysroot, + &sess.opts.unstable_opts.llvm_tpde, + ) { + Ok(_) => {} + Err(llvm::TpdeLibraryError::NotFound { err }) => { + sess.dcx().emit_fatal(crate::diagnostics::TpdeComponentMissing { err }); + } + Err(llvm::TpdeLibraryError::LoadFailed { err }) => { + sess.dcx().emit_fatal(crate::diagnostics::TpdeComponentUnavailable { err }); + } + } + + if sess.opts.unstable_opts.llvm_tpde.is_some() { + if !matches!(sess.opts.optimize, OptLevel::No | OptLevel::Less) { + sess.dcx().emit_warn(crate::diagnostics::TpdeHighOptLevel); + } + + if sess.target.requires_lto + || !matches!(sess.early_lto(), LtoCli::No | LtoCli::Unspecified) + { + sess.dcx().emit_fatal(crate::diagnostics::TpdeLtoUsed); + } + + // JUSTIFICATION: the session doesn't exist at this point. + #[allow(rustc::bad_opt_access)] + if sess.opts.cg.split_debuginfo.unwrap_or(sess.target.split_debuginfo) + != SplitDebuginfo::Off + { + sess.dcx().emit_fatal(crate::diagnostics::TpdeSplitDebugInfoUsed); + } + } + } + // Intrinsics whose fallback body will not be used by the LLVM backend. let replaced_intrinsics = { #[rustfmt::skip] diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 4e1a3f998a265..91b5e756e4400 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -38,7 +38,7 @@ use crate::diagnostics::{ UnsupportedCompression, WithLlvmError, WriteBytecode, }; use crate::llvm::diagnostic::OptimizationDiagnosticKind::*; -use crate::llvm::{self, DiagnosticInfo, TypeKind}; +use crate::llvm::{self, DiagnosticInfo, TpdeWrapper, TypeKind}; use crate::type_::llvm_type_ptr; use crate::{LlvmCodegenBackend, ModuleLlvm, attributes, base, common, llvm_util}; @@ -69,6 +69,8 @@ fn write_output_file<'ll>( } else { std::ptr::null() }; + + let tpde = TpdeWrapper::get_instance(); let result = unsafe { llvm::LLVMRustWriteOutputFile( target, @@ -78,6 +80,7 @@ fn write_output_file<'ll>( file_type, verify_llvm_ir, no_builtins, + tpde.options().clone(), ) }; diff --git a/compiler/rustc_codegen_llvm/src/diagnostics.rs b/compiler/rustc_codegen_llvm/src/diagnostics.rs index 19b2f68107e6c..7d24dec502dbb 100644 --- a/compiler/rustc_codegen_llvm/src/diagnostics.rs +++ b/compiler/rustc_codegen_llvm/src/diagnostics.rs @@ -109,6 +109,33 @@ pub(crate) struct LtoBitcodeFromRlib { pub err: String, } +#[derive(Diagnostic)] +#[diag("failed to load the TPDE backend: {$err}")] +pub(crate) struct TpdeComponentUnavailable { + pub err: String, +} + +#[derive(Diagnostic)] +#[diag("TPDE backend not found in the sysroot: {$err}")] +pub(crate) struct TpdeComponentMissing { + pub err: String, +} + +#[derive(Diagnostic)] +#[diag("using -Zllvm-tpde with optimization levels higher than 1 is not recommended")] +#[note( + "compilation with TPDE at higher opt levels is more likely to fail, and to have worse runtime performance than LLVM even if it succeeds" +)] +pub(crate) struct TpdeHighOptLevel; + +#[derive(Diagnostic)] +#[diag("using -Zllvm-tpde with LTO enabled is not supported")] +pub(crate) struct TpdeLtoUsed; + +#[derive(Diagnostic)] +#[diag("using -Zllvm-tpde with split debuginfo is not supported")] +pub(crate) struct TpdeSplitDebugInfoUsed; + #[derive(Diagnostic)] pub(crate) enum LlvmError<'a> { #[diag("could not write output to {$path}")] diff --git a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs index 11b276f565d4b..3262ffa7e2491 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/ffi.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/ffi.rs @@ -28,8 +28,7 @@ use super::debuginfo::{ DIArray, DIBuilder, DIDerivedType, DIDescriptor, DIFile, DIFlags, DILocation, DISPFlags, DIScope, DISubprogram, DITemplateTypeParameter, DIType, DebugEmissionKind, DebugNameTableKind, }; -use crate::llvm; -use crate::llvm::MetadataKindId; +use crate::llvm::{self, LLVMRustTpdeOptions, MetadataKindId}; use crate::macros::TryFromU32; mod branded; @@ -2488,6 +2487,7 @@ unsafe extern "C" { FileType: FileType, VerifyIR: bool, DisableSimplifyLibCalls: bool, + TpdeOptions: LLVMRustTpdeOptions, ) -> LLVMRustResult; pub(crate) fn LLVMRustOptimize<'ll>( M: Module<'ll>, diff --git a/compiler/rustc_codegen_llvm/src/llvm/mod.rs b/compiler/rustc_codegen_llvm/src/llvm/mod.rs index 168cc40ee579c..79116e9d295a0 100644 --- a/compiler/rustc_codegen_llvm/src/llvm/mod.rs +++ b/compiler/rustc_codegen_llvm/src/llvm/mod.rs @@ -20,9 +20,11 @@ pub(crate) mod enzyme_ffi; mod ffi; mod metadata_kind; pub(crate) mod offload_ffi; +pub(crate) mod tpde_ffi; pub(crate) use self::enzyme_ffi::*; pub(crate) use self::offload_ffi::*; +pub(crate) use self::tpde_ffi::*; impl LLVMRustResult { pub(crate) fn into_result(self) -> Result<(), ()> { diff --git a/compiler/rustc_codegen_llvm/src/llvm/tpde_ffi.rs b/compiler/rustc_codegen_llvm/src/llvm/tpde_ffi.rs new file mode 100644 index 0000000000000..5beeaa8a9df0a --- /dev/null +++ b/compiler/rustc_codegen_llvm/src/llvm/tpde_ffi.rs @@ -0,0 +1,125 @@ +use std::path::PathBuf; +use std::sync::OnceLock; + +use rustc_session::config::{self, Sysroot, host_tuple}; +use rustc_session::filesearch; + +unsafe extern "C" { + type LLVMPassPluginLibraryInfo; +} + +type LLVMGetPassPluginInfoFn = unsafe extern "C" fn() -> LLVMPassPluginLibraryInfo; + +/// LLVMRustTpdeMode +#[repr(C)] +#[derive(Clone)] +pub(crate) enum LLVMRustTpdeMode { + None, + Only, + Try, +} + +/// LLVMRustTpdeOptions +#[repr(C)] +#[derive(Clone)] +pub(crate) struct LLVMRustTpdeOptions { + mode: LLVMRustTpdeMode, + // `None` if mode is `LLVMRustTpdeMode::None` + plugin: Option, +} + +pub(crate) struct TpdeWrapper { + options: LLVMRustTpdeOptions, + // Keep the dynamic library loaded while the function pointers are used. + _lib: Option, +} + +static TPDE_INSTANCE: OnceLock = OnceLock::new(); + +#[derive(Debug)] +pub(crate) enum TpdeLibraryError { + NotFound { err: String }, + LoadFailed { err: String }, +} + +impl From for TpdeLibraryError { + fn from(err: libloading::Error) -> Self { + Self::LoadFailed { err: format!("{err:?}") } + } +} + +impl TpdeWrapper { + /// Initialize TpdeWrapper with the given sysroot and mode if not already initialized. + /// Safe to call multiple times - subsequent calls are no-ops due to OnceLock. + pub(crate) fn get_or_init( + sysroot: &rustc_session::config::Sysroot, + mode: &Option, + ) -> Result<&'static Self, TpdeLibraryError> { + let wrapper = TPDE_INSTANCE.get_or_try_init(|| { + let w = match mode { + Some(mode) => Self::call_dynamic(sysroot, mode)?, + None => Self { + options: LLVMRustTpdeOptions { mode: LLVMRustTpdeMode::None, plugin: None }, + _lib: None, + }, + }; + Ok::<_, TpdeLibraryError>(w) + })?; + + Ok(wrapper) + } + + /// Get the TpdeWrapper instance. Panics if not initialized. + pub(crate) fn get_instance() -> &'static Self { + TPDE_INSTANCE + .get() + .expect("TpdeWrapper not initialized. Call get_or_init with sysroot first.") + } + + pub(crate) fn options(&self) -> &LLVMRustTpdeOptions { + &self.options + } + + fn call_dynamic( + sysroot: &rustc_session::config::Sysroot, + mode: &config::LlvmTpde, + ) -> Result { + let mode = match mode { + config::LlvmTpde::Only => LLVMRustTpdeMode::Only, + config::LlvmTpde::Try => LLVMRustTpdeMode::Try, + }; + let tpde_path = Self::get_tpde_path(sysroot)?; + let lib = unsafe { libloading::Library::new(tpde_path)? }; + let llvm_get_pass_plugin_info = + *unsafe { lib.get::(b"llvmGetPassPluginInfo\0")? }; + let options = LLVMRustTpdeOptions { mode, plugin: Some(llvm_get_pass_plugin_info) }; + Ok(Self { options, _lib: Some(lib) }) + } + + fn get_tpde_path(sysroot: &Sysroot) -> Result { + let path_buf = sysroot + .all_paths() + .map(|sysroot_path| { + filesearch::make_target_lib_path(sysroot_path, host_tuple()) + .join("lib") + .with_file_name("tpde-plugin") + .with_extension(std::env::consts::DLL_EXTENSION) + }) + .find(|f| f.exists()) + .ok_or_else(|| { + let candidates = sysroot + .all_paths() + .map(|p| p.join("lib").display().to_string()) + .collect::>() + .join("\n* "); + TpdeLibraryError::NotFound { + err: format!( + "failed to find the `tpde-plugin` shared library \ + in the sysroot candidates:\n* {candidates}" + ), + } + })?; + + Ok(path_buf) + } +} diff --git a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp index 53b77729a7425..596b49365fe90 100644 --- a/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp +++ b/compiler/rustc_llvm/llvm-wrapper/PassWrapper.cpp @@ -479,11 +479,23 @@ static CodeGenFileType fromRust(LLVMRustFileType Type) { } } -extern "C" LLVMRustResult -LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMModuleRef M, - const char *Path, const char *DwoPath, - LLVMRustFileType RustFileType, bool VerifyIR, - bool DisableSimplifyLibCalls) { +extern "C" typedef llvm::PassPluginLibraryInfo (*LLVMGetPassPluginInfo)(); + +enum class LLVMRustTpdeMode { + None, + Only, + Try, +}; + +struct LLVMRustTpdeOptions { + LLVMRustTpdeMode mode; + LLVMGetPassPluginInfo plugin; +}; + +extern "C" LLVMRustResult LLVMRustWriteOutputFile( + LLVMTargetMachineRef Target, LLVMModuleRef M, const char *Path, + const char *DwoPath, LLVMRustFileType RustFileType, bool VerifyIR, + bool DisableSimplifyLibCalls, LLVMRustTpdeOptions TpdeOptions) { auto FileType = fromRust(RustFileType); std::string ErrorInfo; @@ -499,6 +511,22 @@ LLVMRustWriteOutputFile(LLVMTargetMachineRef Target, LLVMModuleRef M, std::unique_ptr DwoOS = nullptr; std::unique_ptr BDwoOS = nullptr; auto BOS = buffer_ostream(OS); + + if (TpdeOptions.mode != LLVMRustTpdeMode::None) { + assert( + TpdeOptions.plugin && + "rustc_codegen_llvm must set TpdeOptions.plugin if using -Zllvm-tpde"); + llvm::PassPluginLibraryInfo plugin = TpdeOptions.plugin(); + if (plugin.PreCodeGenCallback(*unwrap(M), *unwrap(Target), FileType, BOS)) { + return LLVMRustResult::Success; + } else if (TpdeOptions.mode == LLVMRustTpdeMode::Only) { + std::string error = "Failed to compile module " + + unwrap(M)->getModuleIdentifier() + " with TPDE"; + LLVMRustSetLastError(error.c_str()); + return LLVMRustResult::Failure; + } + } + if (DwoPath) { DwoOS = std::make_unique(DwoPath, EC, sys::fs::OF_None); if (EC) { diff --git a/compiler/rustc_macros/src/diagnostics/message.rs b/compiler/rustc_macros/src/diagnostics/message.rs index 404404bbc1cd0..3f6d89ba9ad8c 100644 --- a/compiler/rustc_macros/src/diagnostics/message.rs +++ b/compiler/rustc_macros/src/diagnostics/message.rs @@ -138,6 +138,7 @@ const ALLOWED_CAPITALIZED_WORDS: &[&str] = &[ "NaNs", "OK", "Rust", + "TPDE", "ThinLTO", "Unicode", "VS", From 5b32ad84a5d42d5845f638e4d5e967619e1fca38 Mon Sep 17 00:00:00 2001 From: TechnoPorg Date: Sat, 10 Oct 2026 07:39:13 -0400 Subject: [PATCH 03/39] Add tests for TPDE backend --- src/bootstrap/src/core/build_steps/test.rs | 4 ++++ .../rustc-dev-guide/src/tests/directives.md | 1 + src/tools/compiletest/src/cli.rs | 3 +++ src/tools/compiletest/src/common.rs | 3 +++ .../src/directives/directive_names.rs | 1 + src/tools/compiletest/src/directives/needs.rs | 5 +++++ src/tools/compiletest/src/rustdoc_gui_test.rs | 1 + tests/ui/README.md | 4 ++++ tests/ui/tpde/check_option.invalid.stderr | 2 ++ tests/ui/tpde/check_option.rs | 16 ++++++++++++++ tests/ui/tpde/llvm_fallback.only.stderr | 4 ++++ tests/ui/tpde/llvm_fallback.rs | 22 +++++++++++++++++++ tests/ui/tpde/no_lto.fat.stderr | 2 ++ tests/ui/tpde/no_lto.rs | 16 ++++++++++++++ tests/ui/tpde/no_lto.thin.stderr | 2 ++ .../ui/tpde/no_split_debuginfo.packed.stderr | 2 ++ tests/ui/tpde/no_split_debuginfo.rs | 16 ++++++++++++++ .../tpde/no_split_debuginfo.unpacked.stderr | 2 ++ tests/ui/tpde/opt_level.rs | 14 ++++++++++++ tests/ui/tpde/opt_level.three.stderr | 6 +++++ tests/ui/tpde/opt_level.two.stderr | 6 +++++ 21 files changed, 132 insertions(+) create mode 100644 tests/ui/tpde/check_option.invalid.stderr create mode 100644 tests/ui/tpde/check_option.rs create mode 100644 tests/ui/tpde/llvm_fallback.only.stderr create mode 100644 tests/ui/tpde/llvm_fallback.rs create mode 100644 tests/ui/tpde/no_lto.fat.stderr create mode 100644 tests/ui/tpde/no_lto.rs create mode 100644 tests/ui/tpde/no_lto.thin.stderr create mode 100644 tests/ui/tpde/no_split_debuginfo.packed.stderr create mode 100644 tests/ui/tpde/no_split_debuginfo.rs create mode 100644 tests/ui/tpde/no_split_debuginfo.unpacked.stderr create mode 100644 tests/ui/tpde/opt_level.rs create mode 100644 tests/ui/tpde/opt_level.three.stderr create mode 100644 tests/ui/tpde/opt_level.two.stderr diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index cbd8420b396bd..9c930c201b20d 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -2625,6 +2625,10 @@ Please disable assertions with `rust.debug-assertions = false`. cmd.arg("--has-offload"); } + if builder.sess.config.llvm_tpde { + cmd.arg("--has-tpde"); + } + if builder.config.cmd.bless() { cmd.arg("--bless"); } diff --git a/src/doc/rustc-dev-guide/src/tests/directives.md b/src/doc/rustc-dev-guide/src/tests/directives.md index 7d8fc182ba453..baa0bcb123217 100644 --- a/src/doc/rustc-dev-guide/src/tests/directives.md +++ b/src/doc/rustc-dev-guide/src/tests/directives.md @@ -212,6 +212,7 @@ The following directives will check rustc build settings and target settings: - `needs-backends` — only runs the test if current codegen backend is listed. - `needs-offload` — ignores if our LLVM backend was not built with offload support. - `needs-enzyme` — ignores if our Enzyme submodule was not built. +- `needs-tpde` — ignores if the TPDE-LLVM codegen backend was not built The following directives will check LLVM support: diff --git a/src/tools/compiletest/src/cli.rs b/src/tools/compiletest/src/cli.rs index 893f5b76724b8..778d53f1d8d4f 100644 --- a/src/tools/compiletest/src/cli.rs +++ b/src/tools/compiletest/src/cli.rs @@ -239,6 +239,8 @@ struct Args { /// Run tests that require offload. #[arg(long)] has_offload: bool, + #[arg(long)] + has_tpde: bool, /// Whether rustc was built with debug assertions. #[arg(long)] with_rustc_debug_assertions: bool, @@ -455,6 +457,7 @@ pub(crate) fn parse_config(args: Vec) -> Config { has_enzyme: args.has_enzyme, has_offload: args.has_offload, + has_tpde: args.has_tpde, host: args.host, host_compile_lib_path: make_absolute(args.compile_lib_path), host_linker: args.host_linker, diff --git a/src/tools/compiletest/src/common.rs b/src/tools/compiletest/src/common.rs index a60b657e96ab5..c25fe8e0a2f8b 100644 --- a/src/tools/compiletest/src/common.rs +++ b/src/tools/compiletest/src/common.rs @@ -682,6 +682,9 @@ pub(crate) struct Config { /// Whether to run `offload` autodiff tests. pub(crate) has_offload: bool, + /// Whether to run tests with the `tpde` LLVM backend + pub(crate) has_tpde: bool, + /// The current Rust channel info. /// /// FIXME: treat this more carefully; "stable", "beta" and "nightly" are definitely valid, but diff --git a/src/tools/compiletest/src/directives/directive_names.rs b/src/tools/compiletest/src/directives/directive_names.rs index 7af285775380c..e86e23a9505dd 100644 --- a/src/tools/compiletest/src/directives/directive_names.rs +++ b/src/tools/compiletest/src/directives/directive_names.rs @@ -208,6 +208,7 @@ pub(crate) const KNOWN_DIRECTIVE_NAMES: &[&str] = &[ "needs-target-has-atomic", "needs-target-std", "needs-threads", + "needs-tpde", "needs-unwind", "needs-wasmtime", "needs-xray", diff --git a/src/tools/compiletest/src/directives/needs.rs b/src/tools/compiletest/src/directives/needs.rs index ce67b11fba211..6275b7ca2879c 100644 --- a/src/tools/compiletest/src/directives/needs.rs +++ b/src/tools/compiletest/src/directives/needs.rs @@ -239,6 +239,11 @@ pub(crate) fn prepare_needs_conditions(config: &Config) -> PreparedNeedsConditio condition: config.has_offload && config.default_codegen_backend.is_llvm(), ignore_reason: "ignored when LLVM Offload is disabled or LLVM is not the default codegen backend", }, + Need { + name: "needs-tpde", + condition: config.has_tpde && config.default_codegen_backend.is_llvm(), + ignore_reason: "ignored when TPDE-LLVM is disabled or LLVM is not the default codegen backend", + }, Need { name: "needs-run-enabled", condition: config.run_enabled(), diff --git a/src/tools/compiletest/src/rustdoc_gui_test.rs b/src/tools/compiletest/src/rustdoc_gui_test.rs index c0f31984834e1..03bc48b340f4b 100644 --- a/src/tools/compiletest/src/rustdoc_gui_test.rs +++ b/src/tools/compiletest/src/rustdoc_gui_test.rs @@ -119,6 +119,7 @@ fn incomplete_config_for_rustdoc_gui_test() -> Config { rustfix_coverage: Default::default(), has_enzyme: Default::default(), has_offload: Default::default(), + has_tpde: Default::default(), channel: Default::default(), git_hash: Default::default(), cc: Default::default(), diff --git a/tests/ui/README.md b/tests/ui/README.md index cdebbea240dbf..ea21967cf2e50 100644 --- a/tests/ui/README.md +++ b/tests/ui/README.md @@ -1414,6 +1414,10 @@ Broad category for parallelism and multi-threaded tests, including attempting to Exercises [tool attributes](https://doc.rust-lang.org/reference/attributes.html#tool-attributes). +## `tests/ui/tpde` + +Exercises the experimental TPDE-LLVM codegen backend. + ## `tests/ui/track-diagnostics/` Exercises `#[track_caller]` and `-Z track-diagnostics`. diff --git a/tests/ui/tpde/check_option.invalid.stderr b/tests/ui/tpde/check_option.invalid.stderr new file mode 100644 index 0000000000000..2419c47071422 --- /dev/null +++ b/tests/ui/tpde/check_option.invalid.stderr @@ -0,0 +1,2 @@ +error: incorrect value `invalid` for unstable option `llvm-tpde` - either no value or one of: `try` (default), `only` was expected + diff --git a/tests/ui/tpde/check_option.rs b/tests/ui/tpde/check_option.rs new file mode 100644 index 0000000000000..cf4c8360e73c8 --- /dev/null +++ b/tests/ui/tpde/check_option.rs @@ -0,0 +1,16 @@ +//@ revisions: implicit try only invalid +//@ needs-tpde +// +//@[implicit] build-pass +//@[try] build-pass +//@[only] build-pass +//@[invalid] check-fail +// +//@[implicit] compile-flags: -Zllvm-tpde +//@[try] compile-flags: -Zllvm-tpde=try +//@[only] compile-flags: -Zllvm-tpde=only +//@[invalid] compile-flags: -Zllvm-tpde=invalid + +//[invalid]~? ERROR: incorrect value `invalid` for unstable option `llvm-tpde` - either no value or one of: `try` (default), `only` was expected + +fn main() {} diff --git a/tests/ui/tpde/llvm_fallback.only.stderr b/tests/ui/tpde/llvm_fallback.only.stderr new file mode 100644 index 0000000000000..d64dc59ee159f --- /dev/null +++ b/tests/ui/tpde/llvm_fallback.only.stderr @@ -0,0 +1,4 @@ +error: could not write output to $TEST_BUILD_DIR/llvm_fallback.llvm_fallback.bef9b9dab1dfd663-cgu.0.rcgu.o: Failed to compile module llvm_fallback.bef9b9dab1dfd663-cgu.0 with TPDE + +error: aborting due to 1 previous error + diff --git a/tests/ui/tpde/llvm_fallback.rs b/tests/ui/tpde/llvm_fallback.rs new file mode 100644 index 0000000000000..7a071db2c26e3 --- /dev/null +++ b/tests/ui/tpde/llvm_fallback.rs @@ -0,0 +1,22 @@ +//@ revisions: try only +//@ needs-tpde +// +//@[try] build-pass +//@[only] build-fail +// +//@[try] compile-flags: -Zllvm-tpde +//@[only] compile-flags: -Zllvm-tpde=only + +//[only]~? ERROR: could not write output to $TEST_BUILD_DIR/llvm_fallback.llvm_fallback.bef9b9dab1dfd663-cgu.0.rcgu.o: Failed to compile module llvm_fallback.bef9b9dab1dfd663-cgu.0 with TPDE + +// NOTE: if TPDE gains f16 support, this test will need to be adjusted + +#![feature(f16)] + +fn main() { + if std::hint::black_box(0f16) == std::hint::black_box(7f16) { + println!("same"); + } else { + println!("different"); + } +} diff --git a/tests/ui/tpde/no_lto.fat.stderr b/tests/ui/tpde/no_lto.fat.stderr new file mode 100644 index 0000000000000..748f266213ba4 --- /dev/null +++ b/tests/ui/tpde/no_lto.fat.stderr @@ -0,0 +1,2 @@ +error: using -Zllvm-tpde with LTO enabled is not supported + diff --git a/tests/ui/tpde/no_lto.rs b/tests/ui/tpde/no_lto.rs new file mode 100644 index 0000000000000..ad0323bf5a8fa --- /dev/null +++ b/tests/ui/tpde/no_lto.rs @@ -0,0 +1,16 @@ +//@ revisions: no unspecified thin fat +//@ needs-tpde +//@ compile-flags: -Zllvm-tpde +// +//@[no] build-pass +//@[unspecified] build-pass +//@[thin] check-fail +//@[fat] check-fail +// +//@[no] compile-flags: -Clto=no +//@[thin] compile-flags: -Clto=thin +//@[fat] compile-flags: -Clto=fat + +//[thin,fat]~? ERROR: using -Zllvm-tpde with LTO enabled is not supported + +fn main() {} diff --git a/tests/ui/tpde/no_lto.thin.stderr b/tests/ui/tpde/no_lto.thin.stderr new file mode 100644 index 0000000000000..748f266213ba4 --- /dev/null +++ b/tests/ui/tpde/no_lto.thin.stderr @@ -0,0 +1,2 @@ +error: using -Zllvm-tpde with LTO enabled is not supported + diff --git a/tests/ui/tpde/no_split_debuginfo.packed.stderr b/tests/ui/tpde/no_split_debuginfo.packed.stderr new file mode 100644 index 0000000000000..42b6f8bae9aaa --- /dev/null +++ b/tests/ui/tpde/no_split_debuginfo.packed.stderr @@ -0,0 +1,2 @@ +error: using -Zllvm-tpde with split debuginfo is not supported + diff --git a/tests/ui/tpde/no_split_debuginfo.rs b/tests/ui/tpde/no_split_debuginfo.rs new file mode 100644 index 0000000000000..a2cc9c45773aa --- /dev/null +++ b/tests/ui/tpde/no_split_debuginfo.rs @@ -0,0 +1,16 @@ +//@ revisions: off unspecified packed unpacked +//@ needs-tpde +//@ compile-flags: -Zllvm-tpde +// +//@[off] build-pass +//@[unspecified] build-pass +//@[packed] check-fail +//@[unpacked] check-fail +// +//@[off] compile-flags: -Csplit-debuginfo=off +//@[packed] compile-flags: -Csplit-debuginfo=packed +//@[unpacked] compile-flags: -Csplit-debuginfo=unpacked + +//[packed,unpacked]~? ERROR: using -Zllvm-tpde with split debuginfo is not supported + +fn main() {} diff --git a/tests/ui/tpde/no_split_debuginfo.unpacked.stderr b/tests/ui/tpde/no_split_debuginfo.unpacked.stderr new file mode 100644 index 0000000000000..42b6f8bae9aaa --- /dev/null +++ b/tests/ui/tpde/no_split_debuginfo.unpacked.stderr @@ -0,0 +1,2 @@ +error: using -Zllvm-tpde with split debuginfo is not supported + diff --git a/tests/ui/tpde/opt_level.rs b/tests/ui/tpde/opt_level.rs new file mode 100644 index 0000000000000..d8fdb15e4d1a2 --- /dev/null +++ b/tests/ui/tpde/opt_level.rs @@ -0,0 +1,14 @@ +//@ revisions: zero one two three +//@ needs-tpde +//@ build-pass +//@ compile-flags: -Zllvm-tpde +// +//@[zero] compile-flags: -Copt-level=0 +//@[one] compile-flags: -Copt-level=1 +//@[two] compile-flags: -Copt-level=2 +//@[three] compile-flags: -Copt-level=3 + +//[two,three]~? WARN: using -Zllvm-tpde with optimization levels higher than 1 is not recommended +//[two,three]~? NOTE: compilation with TPDE at higher opt levels is more likely to fail, and to have worse runtime performance than LLVM even if it succeeds + +fn main() {} diff --git a/tests/ui/tpde/opt_level.three.stderr b/tests/ui/tpde/opt_level.three.stderr new file mode 100644 index 0000000000000..98295286f38d5 --- /dev/null +++ b/tests/ui/tpde/opt_level.three.stderr @@ -0,0 +1,6 @@ +warning: using -Zllvm-tpde with optimization levels higher than 1 is not recommended + | + = note: compilation with TPDE at higher opt levels is more likely to fail, and to have worse runtime performance than LLVM even if it succeeds + +warning: 1 warning emitted + diff --git a/tests/ui/tpde/opt_level.two.stderr b/tests/ui/tpde/opt_level.two.stderr new file mode 100644 index 0000000000000..98295286f38d5 --- /dev/null +++ b/tests/ui/tpde/opt_level.two.stderr @@ -0,0 +1,6 @@ +warning: using -Zllvm-tpde with optimization levels higher than 1 is not recommended + | + = note: compilation with TPDE at higher opt levels is more likely to fail, and to have worse runtime performance than LLVM even if it succeeds + +warning: 1 warning emitted + From 6b2b12902aac962aff95406933e75f13421effbc Mon Sep 17 00:00:00 2001 From: Marcus Perryman Date: Wed, 21 Oct 2026 15:34:34 +0100 Subject: [PATCH 04/39] My changes for the LLVM fix --- src/bootstrap/src/core/build_steps/test.rs | 1 + .../builder/cli_paths/snapshots/x_test.snap | 1 + .../snapshots/x_test_skip_coverage.snap | 1 + .../snapshots/x_test_skip_coverage_map.snap | 1 + .../snapshots/x_test_skip_coverage_run.snap | 1 + .../snapshots/x_test_skip_tests.snap | 1 + .../snapshots/x_test_skip_tests_coverage.snap | 1 + .../snapshots/x_test_skip_tests_etc.snap | 1 + src/bootstrap/src/core/builder/tests.rs | 2 + src/tools/opt-dist/src/exec.rs | 18 ++++++-- src/tools/opt-dist/src/exec/tests.rs | 45 +++++++++++++++++++ src/tools/opt-dist/src/main.rs | 5 +-- 12 files changed, 71 insertions(+), 7 deletions(-) create mode 100644 src/tools/opt-dist/src/exec/tests.rs diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index cbd8420b396bd..5aebf2143ad2f 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -86,6 +86,7 @@ impl CommandLineStep for CrateBootstrap { // By default, it will test all of them, but requesting specific tools on the command-line // (e.g. `./x test src/tools/coverage-dump`) will test only the specified tools. run.path("src/tools/jsondoclint") + .path("src/tools/opt-dist") .path("src/tools/replace-version-placeholder") .path("src/tools/coverage-dump") // We want `./x test tidy` to _run_ the tidy tool, not its tests. diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap index 1fe97ca766c81..5e1703753a06d 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap @@ -160,6 +160,7 @@ expression: test targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) + - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap index f112cdafa81b3..4cd0702d85b77 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap @@ -157,6 +157,7 @@ expression: test --skip=coverage targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) + - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap index 401cdc8432d2f..06033b4ff0fdf 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap @@ -160,6 +160,7 @@ expression: test --skip=coverage-map targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) + - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap index 01d5b362e928f..141cbeaf9b38b 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap @@ -160,6 +160,7 @@ expression: test --skip=coverage-run targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) + - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap index b936eeefe8805..aa82b679623dc 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap @@ -118,6 +118,7 @@ expression: test --skip=tests targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) + - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap index c7ea1c663a030..d7c1f7821ca13 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap @@ -157,6 +157,7 @@ expression: test --skip=tests/coverage targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) + - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap index 98b39e619fad8..4b29a86d483e8 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap @@ -102,6 +102,7 @@ expression: test --skip=tests --skip=library --skip=tidyselftest targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) + - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) [Test] test::RemoteTestClientTests targets: [x86_64-unknown-linux-gnu] diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 544c47602136a..7f9b0e2174a1c 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1738,6 +1738,7 @@ mod snapshot { [build] rustc 1 -> rustc 2 [test] crate-bootstrap src/tools/coverage-dump [test] crate-bootstrap src/tools/jsondoclint + [test] crate-bootstrap src/tools/opt-dist [test] crate-bootstrap src/tools/replace-version-placeholder [test] crate-bootstrap tidyselftest [build] rustc 0 -> UnstableBookGen 1 @@ -1936,6 +1937,7 @@ mod snapshot { [test] rustc 1 -> CrateLibrustc 2 [test] crate-bootstrap src/tools/coverage-dump [test] crate-bootstrap src/tools/jsondoclint + [test] crate-bootstrap src/tools/opt-dist [test] crate-bootstrap src/tools/replace-version-placeholder [test] crate-bootstrap tidyselftest [build] rustc 0 -> UnstableBookGen 1 diff --git a/src/tools/opt-dist/src/exec.rs b/src/tools/opt-dist/src/exec.rs index 5fb3e13a78604..84a51b3fc035c 100644 --- a/src/tools/opt-dist/src/exec.rs +++ b/src/tools/opt-dist/src/exec.rs @@ -155,12 +155,21 @@ impl Bootstrap { Self { cmd, metrics_path } } - pub fn llvm_pgo_instrument(mut self, profile_dir: &Utf8Path) -> Self { - self.cmd = self.cmd.arg("--set").arg(format!( + pub fn llvm_pgo_instrument( + env: &Environment, + profile_dir: &Utf8Path, + rustc_profile: &RustcPGOProfile, + ) -> Self { + let mut builder = Self::build(env); + builder.cmd = builder.cmd.arg("--set").arg(format!( r#"pgo.llvm.generate="{}""#, normalize_path(&profile_dir.join("prof-%p")).as_str() )); - self + if env.supports_shared_llvm() { + builder.avoid_rustc_rebuild() + } else { + builder.rustc_pgo_optimize(rustc_profile).rustc_rebuild() + } } pub fn llvm_pgo_optimize(mut self, profile: Option<&LlvmPGOProfile>) -> Self { @@ -317,3 +326,6 @@ fn add_shared_x_flags(env: &Environment, cmd: CmdBuilder) -> CmdBuilder { cmd } } + +#[cfg(test)] +mod tests; diff --git a/src/tools/opt-dist/src/exec/tests.rs b/src/tools/opt-dist/src/exec/tests.rs new file mode 100644 index 0000000000000..a2f190efacfeb --- /dev/null +++ b/src/tools/opt-dist/src/exec/tests.rs @@ -0,0 +1,45 @@ +use super::*; +use crate::environment::EnvironmentBuilder; + +#[test] +fn llvm_training_rebuilds_only_static_rustc() { + for (host, shared) in [ + ("x86_64-unknown-linux-gnu", true), + ("aarch64-unknown-linux-gnu", true), + ("x86_64-pc-windows-msvc", false), + ("aarch64-pc-windows-msvc", false), + ] { + for fast_try_build in [false, true] { + let env = EnvironmentBuilder::default() + .host_tuple(host.to_owned()) + .python_binary("python".to_owned()) + .checkout_dir(Utf8PathBuf::from("checkout")) + .build_dir(Utf8PathBuf::from("build")) + .artifact_dir(Utf8PathBuf::from("profiles")) + .host_llvm_dir(Utf8PathBuf::from("clang")) + .skipped_tests(vec![]) + .use_bolt(false) + .shared_llvm(shared) + .run_tests(true) + .fast_try_build(fast_try_build) + .build_llvm(true) + .build() + .unwrap(); + let profile = RustcPGOProfile(Utf8PathBuf::from("profiles/rustc.profdata")); + let bootstrap = + Bootstrap::llvm_pgo_instrument(&env, Utf8Path::new("profiles/llvm"), &profile); + let mut expected = Bootstrap::build(&env).cmd.args; + expected + .extend(["--set".into(), r#"pgo.llvm.generate="profiles/llvm/prof-%p""#.into()]); + if !shared { + expected + .extend(["--set".into(), r#"pgo.rustc.use="profiles/rustc.profdata""#.into()]); + } + expected.extend(["--keep-stage".into(), "0".into()]); + if shared { + expected.extend(["--keep-stage".into(), "1".into()]); + } + assert_eq!(bootstrap.cmd.args, expected, "{host}, fast_try_build={fast_try_build}"); + } + } +} diff --git a/src/tools/opt-dist/src/main.rs b/src/tools/opt-dist/src/main.rs index 484ad09c58f8f..58c4b19a52c5f 100644 --- a/src/tools/opt-dist/src/main.rs +++ b/src/tools/opt-dist/src/main.rs @@ -381,7 +381,6 @@ fn execute_pipeline( })?; // Stage 2: Gather LLVM PGO profiles - // Here we build a PGO-instrumented LLVM, reusing the previously PGO-optimized rustc. // Then we use the instrumented LLVM to gather LLVM PGO profiles. let llvm_pgo_profile = if env.build_llvm() { timer.section("Stage 2 (LLVM PGO)", |stage| { @@ -391,9 +390,7 @@ fn execute_pipeline( let llvm_profile_dir_root = env.artifact_dir().join("llvm-pgo"); stage.section("Build PGO-instrumented LLVM", |section| { - Bootstrap::build(env) - .llvm_pgo_instrument(&llvm_profile_dir_root) - .avoid_rustc_rebuild() + Bootstrap::llvm_pgo_instrument(env, &llvm_profile_dir_root, &rustc_pgo_profile) .run(section) })?; From fd43992ebf564985268257078d311352b1484905 Mon Sep 17 00:00:00 2001 From: Marcus Perryman Date: Sat, 24 Oct 2026 22:45:04 +0100 Subject: [PATCH 05/39] Remove the tests - review feedback --- src/bootstrap/src/core/build_steps/test.rs | 1 - .../builder/cli_paths/snapshots/x_test.snap | 1 - .../snapshots/x_test_skip_coverage.snap | 1 - .../snapshots/x_test_skip_coverage_map.snap | 1 - .../snapshots/x_test_skip_coverage_run.snap | 1 - .../snapshots/x_test_skip_tests.snap | 1 - .../snapshots/x_test_skip_tests_coverage.snap | 1 - .../snapshots/x_test_skip_tests_etc.snap | 1 - src/bootstrap/src/core/builder/tests.rs | 2 - src/tools/opt-dist/src/exec.rs | 2 - src/tools/opt-dist/src/tests.rs | 180 ------------------ 11 files changed, 192 deletions(-) delete mode 100644 src/tools/opt-dist/src/tests.rs diff --git a/src/bootstrap/src/core/build_steps/test.rs b/src/bootstrap/src/core/build_steps/test.rs index 5aebf2143ad2f..cbd8420b396bd 100644 --- a/src/bootstrap/src/core/build_steps/test.rs +++ b/src/bootstrap/src/core/build_steps/test.rs @@ -86,7 +86,6 @@ impl CommandLineStep for CrateBootstrap { // By default, it will test all of them, but requesting specific tools on the command-line // (e.g. `./x test src/tools/coverage-dump`) will test only the specified tools. run.path("src/tools/jsondoclint") - .path("src/tools/opt-dist") .path("src/tools/replace-version-placeholder") .path("src/tools/coverage-dump") // We want `./x test tidy` to _run_ the tidy tool, not its tests. diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap index 5e1703753a06d..1fe97ca766c81 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test.snap @@ -160,7 +160,6 @@ expression: test targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) - - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap index 4cd0702d85b77..f112cdafa81b3 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage.snap @@ -157,7 +157,6 @@ expression: test --skip=coverage targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) - - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap index 06033b4ff0fdf..401cdc8432d2f 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_map.snap @@ -160,7 +160,6 @@ expression: test --skip=coverage-map targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) - - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap index 141cbeaf9b38b..01d5b362e928f 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_coverage_run.snap @@ -160,7 +160,6 @@ expression: test --skip=coverage-run targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) - - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap index aa82b679623dc..b936eeefe8805 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests.snap @@ -118,7 +118,6 @@ expression: test --skip=tests targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) - - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap index d7c1f7821ca13..c7ea1c663a030 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_coverage.snap @@ -157,7 +157,6 @@ expression: test --skip=tests/coverage targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) - - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) - Set({tidyselftest}) [Test] test::RemoteTestClientTests diff --git a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap index 4b29a86d483e8..98b39e619fad8 100644 --- a/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap +++ b/src/bootstrap/src/core/builder/cli_paths/snapshots/x_test_skip_tests_etc.snap @@ -102,7 +102,6 @@ expression: test --skip=tests --skip=library --skip=tidyselftest targets: [x86_64-unknown-linux-gnu] - Set({src/tools/coverage-dump}) - Set({src/tools/jsondoclint}) - - Set({src/tools/opt-dist}) - Set({src/tools/replace-version-placeholder}) [Test] test::RemoteTestClientTests targets: [x86_64-unknown-linux-gnu] diff --git a/src/bootstrap/src/core/builder/tests.rs b/src/bootstrap/src/core/builder/tests.rs index 7f9b0e2174a1c..544c47602136a 100644 --- a/src/bootstrap/src/core/builder/tests.rs +++ b/src/bootstrap/src/core/builder/tests.rs @@ -1738,7 +1738,6 @@ mod snapshot { [build] rustc 1 -> rustc 2 [test] crate-bootstrap src/tools/coverage-dump [test] crate-bootstrap src/tools/jsondoclint - [test] crate-bootstrap src/tools/opt-dist [test] crate-bootstrap src/tools/replace-version-placeholder [test] crate-bootstrap tidyselftest [build] rustc 0 -> UnstableBookGen 1 @@ -1937,7 +1936,6 @@ mod snapshot { [test] rustc 1 -> CrateLibrustc 2 [test] crate-bootstrap src/tools/coverage-dump [test] crate-bootstrap src/tools/jsondoclint - [test] crate-bootstrap src/tools/opt-dist [test] crate-bootstrap src/tools/replace-version-placeholder [test] crate-bootstrap tidyselftest [build] rustc 0 -> UnstableBookGen 1 diff --git a/src/tools/opt-dist/src/exec.rs b/src/tools/opt-dist/src/exec.rs index 84a51b3fc035c..6b808c4d028af 100644 --- a/src/tools/opt-dist/src/exec.rs +++ b/src/tools/opt-dist/src/exec.rs @@ -327,5 +327,3 @@ fn add_shared_x_flags(env: &Environment, cmd: CmdBuilder) -> CmdBuilder { } } -#[cfg(test)] -mod tests; diff --git a/src/tools/opt-dist/src/tests.rs b/src/tools/opt-dist/src/tests.rs deleted file mode 100644 index e0e2c487db4c5..0000000000000 --- a/src/tools/opt-dist/src/tests.rs +++ /dev/null @@ -1,180 +0,0 @@ -use std::path::Path; - -use anyhow::Context; -use camino::{Utf8Path, Utf8PathBuf}; - -use crate::environment::{Environment, executable_extension}; -use crate::exec::cmd; -use crate::utils::io::{copy_directory, find_file_in_dir, normalize_path, unpack_archive}; - -/// Run tests on optimized dist artifacts. -pub fn run_tests(env: &Environment) -> anyhow::Result<()> { - // After `dist` is executed, we extract its archived components into a sysroot directory, - // and then use that extracted rustc as a stage0 compiler. - // Then we run a subset of tests using that compiler, to have a basic smoke test which checks - // whether the optimization pipeline hasn't broken something. - let build_dir = env.build_root(); - let dist_dir = build_dir.join("dist"); - let unpacked_dist_dir = build_dir.join("unpacked-dist"); - std::fs::create_dir_all(&unpacked_dist_dir)?; - - let extract_dist_dir = |name: &str| -> anyhow::Result { - unpack_archive(&dist_dir.join(format!("{name}.tar.xz")), &unpacked_dist_dir)?; - let extracted_path = unpacked_dist_dir.join(name); - assert!(extracted_path.is_dir()); - Ok(extracted_path) - }; - let host_triple = env.host_tuple(); - let version = find_dist_version(&dist_dir)?; - - let channel = version_to_channel(&version); - - // Extract rustc, libstd, cargo and src archives to create the optimized sysroot - let rustc_dir = extract_dist_dir(&format!("rustc-{version}-{host_triple}"))?.join("rustc"); - let libstd_dir = extract_dist_dir(&format!("rust-std-{version}-{host_triple}"))? - .join(format!("rust-std-{host_triple}")); - let cargo_dir = extract_dist_dir(&format!("cargo-{version}-{host_triple}"))?.join("cargo"); - let extracted_src_dir = extract_dist_dir(&format!("rust-src-{version}"))?.join("rust-src"); - - // If we have a Cranelift archive, copy it to the rustc sysroot - if let Ok(_) = find_file_in_dir(&dist_dir, "rustc-codegen-cranelift-", ".tar.xz") { - let extracted_codegen_dir = - extract_dist_dir(&format!("rustc-codegen-cranelift-{version}-{host_triple}"))? - .join("rustc-codegen-cranelift-preview"); - let rel_path = - Utf8Path::new("lib").join("rustlib").join(host_triple).join("codegen-backends"); - copy_directory(&extracted_codegen_dir.join(&rel_path), &rustc_dir.join(&rel_path))?; - } - - // We need to manually copy libstd to the extracted rustc sysroot - copy_directory( - &libstd_dir.join("lib").join("rustlib").join(host_triple).join("lib"), - &rustc_dir.join("lib").join("rustlib").join(host_triple).join("lib"), - )?; - - // Extract sources - they aren't in the `rustc-nightly-{host}` tarball, so we need to manually copy libstd - // sources to the extracted sysroot. We need sources available so that `-Zsimulate-remapped-rust-src-base` - // works correctly. - copy_directory( - &extracted_src_dir.join("lib").join("rustlib").join("src"), - &rustc_dir.join("lib").join("rustlib").join("src"), - )?; - - let rustc_path = rustc_dir.join("bin").join(format!("rustc{}", executable_extension())); - assert!(rustc_path.is_file()); - let cargo_path = cargo_dir.join("bin").join(format!("cargo{}", executable_extension())); - assert!(cargo_path.is_file()); - - // Specify path to a LLVM config so that LLVM is not rebuilt. - // It doesn't really matter which LLVM config we choose, because no sysroot will be compiled. - let llvm_config = env - .build_artifacts() - .join("llvm") - .join("bin") - .join(format!("llvm-config{}", executable_extension())); - assert!(llvm_config.is_file()); - - let config_content = format!( - r#" -profile = "user" -change-id = 115898 - -[rust] -channel = "{channel}" -verbose-tests = true -# rust-lld cannot be combined with an external LLVM -lld = false - -[build] -rustc = "{rustc}" -cargo = "{cargo}" -local-rebuild = true -compiletest-allow-stage0=true - -[target.{host_triple}] -llvm-config = "{llvm_config}" -"#, - rustc = normalize_path(&rustc_path), - cargo = normalize_path(&cargo_path), - llvm_config = normalize_path(&llvm_config) - ); - log::info!("Using following `bootstrap.toml` for running tests:\n{config_content}"); - - // Simulate a stage 0 compiler with the extracted optimized dist artifacts. - with_backed_up_file(Path::new("bootstrap.toml"), &config_content, || { - let x_py = env.checkout_path().join("x.py"); - let mut args = vec![ - env.python_binary(), - x_py.as_str(), - "test", - "--build", - env.host_tuple(), - "--stage", - "0", - "tests/assembly-llvm", - "tests/codegen-llvm", - "tests/codegen-units", - "tests/incremental", - "tests/mir-opt", - "tests/pretty", - // Make sure that we don't use too new GLIBC symbols on x64 - "tests/run-make/glibc-symbols-x86_64-unknown-linux-gnu", - // Make sure that we use LLD by default on x64 - "tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist", - "tests/ui", - "tests/crashes", - "tests/rustdoc-html", - ]; - for test_path in env.skipped_tests() { - args.extend(["--skip", test_path]); - } - cmd(&args) - // Also run dist-only tests - .env("COMPILETEST_ENABLE_DIST_TESTS", "1") - .run() - .context("Cannot execute tests") - }) -} - -/// Backup `path` (if it exists), then write `contents` into it, and then restore the original -/// contents of the file. -fn with_backed_up_file(path: &Path, contents: &str, func: F) -> anyhow::Result<()> -where - F: FnOnce() -> anyhow::Result<()>, -{ - let original_contents = - if path.is_file() { Some(std::fs::read_to_string(path)?) } else { None }; - - // Overwrite it with new contents - std::fs::write(path, contents)?; - - let ret = func(); - - if let Some(original_contents) = original_contents { - std::fs::write(path, original_contents)?; - } - - ret -} - -/// Tries to find the version of the dist artifacts (either nightly, beta, or 1.XY.Z). -fn find_dist_version(directory: &Utf8Path) -> anyhow::Result { - // Lookup a known file with a unique prefix and extract the version from its filename - let archive = find_file_in_dir(directory, "reproducible-artifacts-", ".tar.xz")? - .file_name() - .unwrap() - .to_string(); - let (version, _) = - archive.strip_prefix("reproducible-artifacts-").unwrap().split_once('-').unwrap(); - Ok(version.to_string()) -} - -/// Roughly convert a version string (`nightly`, `beta`, or `1.XY.Z`) to channel string (`nightly`, -/// `beta` or `stable`). -fn version_to_channel(version_str: &str) -> &'static str { - match version_str { - "nightly" => "nightly", - "beta" => "beta", - _ => "stable", - } -} From c0847283eec6c03c6ebd8bacbad3d856813b22a9 Mon Sep 17 00:00:00 2001 From: Marcus Perryman Date: Sat, 24 Oct 2026 23:28:08 +0100 Subject: [PATCH 06/39] Implement review feedback --- src/tools/opt-dist/src/environment.rs | 2 +- src/tools/opt-dist/src/exec.rs | 16 +-- src/tools/opt-dist/src/exec/tests.rs | 45 ------- src/tools/opt-dist/src/main.rs | 13 +- src/tools/opt-dist/src/tests.rs | 180 ++++++++++++++++++++++++++ 5 files changed, 193 insertions(+), 63 deletions(-) delete mode 100644 src/tools/opt-dist/src/exec/tests.rs create mode 100644 src/tools/opt-dist/src/tests.rs diff --git a/src/tools/opt-dist/src/environment.rs b/src/tools/opt-dist/src/environment.rs index 5aeae30e0e3d8..fb5a8d0f31e06 100644 --- a/src/tools/opt-dist/src/environment.rs +++ b/src/tools/opt-dist/src/environment.rs @@ -119,7 +119,7 @@ impl Environment { self.use_bolt } - pub fn supports_shared_llvm(&self) -> bool { + pub fn link_llvm_dynamically(&self) -> bool { self.shared_llvm } diff --git a/src/tools/opt-dist/src/exec.rs b/src/tools/opt-dist/src/exec.rs index 6b808c4d028af..5fb3e13a78604 100644 --- a/src/tools/opt-dist/src/exec.rs +++ b/src/tools/opt-dist/src/exec.rs @@ -155,21 +155,12 @@ impl Bootstrap { Self { cmd, metrics_path } } - pub fn llvm_pgo_instrument( - env: &Environment, - profile_dir: &Utf8Path, - rustc_profile: &RustcPGOProfile, - ) -> Self { - let mut builder = Self::build(env); - builder.cmd = builder.cmd.arg("--set").arg(format!( + pub fn llvm_pgo_instrument(mut self, profile_dir: &Utf8Path) -> Self { + self.cmd = self.cmd.arg("--set").arg(format!( r#"pgo.llvm.generate="{}""#, normalize_path(&profile_dir.join("prof-%p")).as_str() )); - if env.supports_shared_llvm() { - builder.avoid_rustc_rebuild() - } else { - builder.rustc_pgo_optimize(rustc_profile).rustc_rebuild() - } + self } pub fn llvm_pgo_optimize(mut self, profile: Option<&LlvmPGOProfile>) -> Self { @@ -326,4 +317,3 @@ fn add_shared_x_flags(env: &Environment, cmd: CmdBuilder) -> CmdBuilder { cmd } } - diff --git a/src/tools/opt-dist/src/exec/tests.rs b/src/tools/opt-dist/src/exec/tests.rs deleted file mode 100644 index a2f190efacfeb..0000000000000 --- a/src/tools/opt-dist/src/exec/tests.rs +++ /dev/null @@ -1,45 +0,0 @@ -use super::*; -use crate::environment::EnvironmentBuilder; - -#[test] -fn llvm_training_rebuilds_only_static_rustc() { - for (host, shared) in [ - ("x86_64-unknown-linux-gnu", true), - ("aarch64-unknown-linux-gnu", true), - ("x86_64-pc-windows-msvc", false), - ("aarch64-pc-windows-msvc", false), - ] { - for fast_try_build in [false, true] { - let env = EnvironmentBuilder::default() - .host_tuple(host.to_owned()) - .python_binary("python".to_owned()) - .checkout_dir(Utf8PathBuf::from("checkout")) - .build_dir(Utf8PathBuf::from("build")) - .artifact_dir(Utf8PathBuf::from("profiles")) - .host_llvm_dir(Utf8PathBuf::from("clang")) - .skipped_tests(vec![]) - .use_bolt(false) - .shared_llvm(shared) - .run_tests(true) - .fast_try_build(fast_try_build) - .build_llvm(true) - .build() - .unwrap(); - let profile = RustcPGOProfile(Utf8PathBuf::from("profiles/rustc.profdata")); - let bootstrap = - Bootstrap::llvm_pgo_instrument(&env, Utf8Path::new("profiles/llvm"), &profile); - let mut expected = Bootstrap::build(&env).cmd.args; - expected - .extend(["--set".into(), r#"pgo.llvm.generate="profiles/llvm/prof-%p""#.into()]); - if !shared { - expected - .extend(["--set".into(), r#"pgo.rustc.use="profiles/rustc.profdata""#.into()]); - } - expected.extend(["--keep-stage".into(), "0".into()]); - if shared { - expected.extend(["--keep-stage".into(), "1".into()]); - } - assert_eq!(bootstrap.cmd.args, expected, "{host}, fast_try_build={fast_try_build}"); - } - } -} diff --git a/src/tools/opt-dist/src/main.rs b/src/tools/opt-dist/src/main.rs index 58c4b19a52c5f..adc537b79ba58 100644 --- a/src/tools/opt-dist/src/main.rs +++ b/src/tools/opt-dist/src/main.rs @@ -309,7 +309,7 @@ fn execute_pipeline( builder.with_cranelift().cranelift_pgo_instrument(&rustc_profile_dir_root); } - if env.supports_shared_llvm() { + if env.link_llvm_dynamically() { // This first LLVM that we build will be thrown away after this stage, and it // doesn't really need LTO. Without LTO, it builds in ~1 minute thanks to sccache, // with LTO it takes almost 10 minutes. It makes the followup Rustc PGO @@ -390,8 +390,13 @@ fn execute_pipeline( let llvm_profile_dir_root = env.artifact_dir().join("llvm-pgo"); stage.section("Build PGO-instrumented LLVM", |section| { - Bootstrap::llvm_pgo_instrument(env, &llvm_profile_dir_root, &rustc_pgo_profile) - .run(section) + let builder = Bootstrap::build(env).llvm_pgo_instrument(&llvm_profile_dir_root); + let builder = if env.link_llvm_dynamically() { + builder.avoid_rustc_rebuild() + } else { + builder.rustc_pgo_optimize(&rustc_pgo_profile).rustc_rebuild() + }; + builder.run(section) })?; let profile = stage.section("Gather profiles", |_| { @@ -522,7 +527,7 @@ fn execute_pipeline( } // if LLVM is not built we'll have PGO-optimized rustc - dist = if env.supports_shared_llvm() || !env.build_llvm() { + dist = if env.link_llvm_dynamically() || !env.build_llvm() { dist.avoid_rustc_rebuild() } else { dist.rustc_rebuild() diff --git a/src/tools/opt-dist/src/tests.rs b/src/tools/opt-dist/src/tests.rs new file mode 100644 index 0000000000000..e0e2c487db4c5 --- /dev/null +++ b/src/tools/opt-dist/src/tests.rs @@ -0,0 +1,180 @@ +use std::path::Path; + +use anyhow::Context; +use camino::{Utf8Path, Utf8PathBuf}; + +use crate::environment::{Environment, executable_extension}; +use crate::exec::cmd; +use crate::utils::io::{copy_directory, find_file_in_dir, normalize_path, unpack_archive}; + +/// Run tests on optimized dist artifacts. +pub fn run_tests(env: &Environment) -> anyhow::Result<()> { + // After `dist` is executed, we extract its archived components into a sysroot directory, + // and then use that extracted rustc as a stage0 compiler. + // Then we run a subset of tests using that compiler, to have a basic smoke test which checks + // whether the optimization pipeline hasn't broken something. + let build_dir = env.build_root(); + let dist_dir = build_dir.join("dist"); + let unpacked_dist_dir = build_dir.join("unpacked-dist"); + std::fs::create_dir_all(&unpacked_dist_dir)?; + + let extract_dist_dir = |name: &str| -> anyhow::Result { + unpack_archive(&dist_dir.join(format!("{name}.tar.xz")), &unpacked_dist_dir)?; + let extracted_path = unpacked_dist_dir.join(name); + assert!(extracted_path.is_dir()); + Ok(extracted_path) + }; + let host_triple = env.host_tuple(); + let version = find_dist_version(&dist_dir)?; + + let channel = version_to_channel(&version); + + // Extract rustc, libstd, cargo and src archives to create the optimized sysroot + let rustc_dir = extract_dist_dir(&format!("rustc-{version}-{host_triple}"))?.join("rustc"); + let libstd_dir = extract_dist_dir(&format!("rust-std-{version}-{host_triple}"))? + .join(format!("rust-std-{host_triple}")); + let cargo_dir = extract_dist_dir(&format!("cargo-{version}-{host_triple}"))?.join("cargo"); + let extracted_src_dir = extract_dist_dir(&format!("rust-src-{version}"))?.join("rust-src"); + + // If we have a Cranelift archive, copy it to the rustc sysroot + if let Ok(_) = find_file_in_dir(&dist_dir, "rustc-codegen-cranelift-", ".tar.xz") { + let extracted_codegen_dir = + extract_dist_dir(&format!("rustc-codegen-cranelift-{version}-{host_triple}"))? + .join("rustc-codegen-cranelift-preview"); + let rel_path = + Utf8Path::new("lib").join("rustlib").join(host_triple).join("codegen-backends"); + copy_directory(&extracted_codegen_dir.join(&rel_path), &rustc_dir.join(&rel_path))?; + } + + // We need to manually copy libstd to the extracted rustc sysroot + copy_directory( + &libstd_dir.join("lib").join("rustlib").join(host_triple).join("lib"), + &rustc_dir.join("lib").join("rustlib").join(host_triple).join("lib"), + )?; + + // Extract sources - they aren't in the `rustc-nightly-{host}` tarball, so we need to manually copy libstd + // sources to the extracted sysroot. We need sources available so that `-Zsimulate-remapped-rust-src-base` + // works correctly. + copy_directory( + &extracted_src_dir.join("lib").join("rustlib").join("src"), + &rustc_dir.join("lib").join("rustlib").join("src"), + )?; + + let rustc_path = rustc_dir.join("bin").join(format!("rustc{}", executable_extension())); + assert!(rustc_path.is_file()); + let cargo_path = cargo_dir.join("bin").join(format!("cargo{}", executable_extension())); + assert!(cargo_path.is_file()); + + // Specify path to a LLVM config so that LLVM is not rebuilt. + // It doesn't really matter which LLVM config we choose, because no sysroot will be compiled. + let llvm_config = env + .build_artifacts() + .join("llvm") + .join("bin") + .join(format!("llvm-config{}", executable_extension())); + assert!(llvm_config.is_file()); + + let config_content = format!( + r#" +profile = "user" +change-id = 115898 + +[rust] +channel = "{channel}" +verbose-tests = true +# rust-lld cannot be combined with an external LLVM +lld = false + +[build] +rustc = "{rustc}" +cargo = "{cargo}" +local-rebuild = true +compiletest-allow-stage0=true + +[target.{host_triple}] +llvm-config = "{llvm_config}" +"#, + rustc = normalize_path(&rustc_path), + cargo = normalize_path(&cargo_path), + llvm_config = normalize_path(&llvm_config) + ); + log::info!("Using following `bootstrap.toml` for running tests:\n{config_content}"); + + // Simulate a stage 0 compiler with the extracted optimized dist artifacts. + with_backed_up_file(Path::new("bootstrap.toml"), &config_content, || { + let x_py = env.checkout_path().join("x.py"); + let mut args = vec![ + env.python_binary(), + x_py.as_str(), + "test", + "--build", + env.host_tuple(), + "--stage", + "0", + "tests/assembly-llvm", + "tests/codegen-llvm", + "tests/codegen-units", + "tests/incremental", + "tests/mir-opt", + "tests/pretty", + // Make sure that we don't use too new GLIBC symbols on x64 + "tests/run-make/glibc-symbols-x86_64-unknown-linux-gnu", + // Make sure that we use LLD by default on x64 + "tests/run-make/rust-lld-x86_64-unknown-linux-gnu-dist", + "tests/ui", + "tests/crashes", + "tests/rustdoc-html", + ]; + for test_path in env.skipped_tests() { + args.extend(["--skip", test_path]); + } + cmd(&args) + // Also run dist-only tests + .env("COMPILETEST_ENABLE_DIST_TESTS", "1") + .run() + .context("Cannot execute tests") + }) +} + +/// Backup `path` (if it exists), then write `contents` into it, and then restore the original +/// contents of the file. +fn with_backed_up_file(path: &Path, contents: &str, func: F) -> anyhow::Result<()> +where + F: FnOnce() -> anyhow::Result<()>, +{ + let original_contents = + if path.is_file() { Some(std::fs::read_to_string(path)?) } else { None }; + + // Overwrite it with new contents + std::fs::write(path, contents)?; + + let ret = func(); + + if let Some(original_contents) = original_contents { + std::fs::write(path, original_contents)?; + } + + ret +} + +/// Tries to find the version of the dist artifacts (either nightly, beta, or 1.XY.Z). +fn find_dist_version(directory: &Utf8Path) -> anyhow::Result { + // Lookup a known file with a unique prefix and extract the version from its filename + let archive = find_file_in_dir(directory, "reproducible-artifacts-", ".tar.xz")? + .file_name() + .unwrap() + .to_string(); + let (version, _) = + archive.strip_prefix("reproducible-artifacts-").unwrap().split_once('-').unwrap(); + Ok(version.to_string()) +} + +/// Roughly convert a version string (`nightly`, `beta`, or `1.XY.Z`) to channel string (`nightly`, +/// `beta` or `stable`). +fn version_to_channel(version_str: &str) -> &'static str { + match version_str { + "nightly" => "nightly", + "beta" => "beta", + _ => "stable", + } +} From 66162cb9663ad492e5b3bbf40d32408e3d9c1dcd Mon Sep 17 00:00:00 2001 From: Marcus Perryman Date: Sun, 25 Oct 2026 07:10:05 +0000 Subject: [PATCH 07/39] apply missed fix for the dry run panic. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebuilding rustc against statically linked LLVM now reaches the code that locates clang’s profiling runtime that was previously skipped. Bootstrap checks during dry-run mode also need to discover clang-cl, so this change means now run_in_dry_run() adds clang-cl during the planning pass and avoids the panic check later. --- src/bootstrap/src/utils/helpers.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/bootstrap/src/utils/helpers.rs b/src/bootstrap/src/utils/helpers.rs index 7fecfe14cc578..6aa5fc0bf36a9 100644 --- a/src/bootstrap/src/utils/helpers.rs +++ b/src/bootstrap/src/utils/helpers.rs @@ -368,6 +368,7 @@ pub fn get_clang_cl_resource_dir(builder: &Builder<'_>, clang_cl_path: &str) -> // - we ask `clang-cl` to locate the `clang_rt.builtins` lib. let mut builtins_locator = command(clang_cl_path); builtins_locator.args(["/clang:-print-libgcc-file-name", "/clang:--rtlib=compiler-rt"]); + builtins_locator.run_in_dry_run(); let clang_rt_builtins = builtins_locator.run_capture_stdout(builder).stdout(); let clang_rt_builtins = Path::new(clang_rt_builtins.trim()); From 17ddd528aba3d5111f65a1ea61a90652e23007b0 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Wed, 11 Nov 2026 18:10:03 -0500 Subject: [PATCH 08/39] Tell Miri about the alignment handling on Windows --- library/std/src/sys/alloc/windows.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/library/std/src/sys/alloc/windows.rs b/library/std/src/sys/alloc/windows.rs index 1d75cbd9d54f1..a62a634857d1e 100644 --- a/library/std/src/sys/alloc/windows.rs +++ b/library/std/src/sys/alloc/windows.rs @@ -145,7 +145,13 @@ unsafe fn allocate(layout: Layout, zeroed: bool) -> *mut u8 { // Create a correctly aligned pointer offset from the start of the allocated block, // and write a header before it. - let offset = layout.align() - (ptr.addr() & (layout.align() - 1)); + // SAFETY: Guaranteed by Layout::align. + // This hint is technically redundant, but currently LLVM needs this explicit hint to + // optimize out a panic path inside align_offset. + unsafe { + core::hint::assert_unchecked(layout.align().is_power_of_two()); + } + let offset = ptr.wrapping_add(1).align_offset(layout.align()) + 1; // SAFETY: `MIN_ALIGN` <= `offset` <= `layout.align()` and the size of the allocated // block is `layout.align() + layout.size()`. `aligned` will thus be a correctly aligned // pointer inside the allocated block with at least `layout.size()` bytes after it and at From d0c53d4af204b1cedd1d9bd493ac6a51822f0b04 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 6 Nov 2026 12:46:17 +0100 Subject: [PATCH 09/39] view-types: don't pass view types by value in tests after some discussion, we decided we want view types to be `!Sized`, at least at the beginning. this commit updates the test suite so that view types are not passed by value anymore. --- tests/ui/view-types/hygiene.rs | 2 +- tests/ui/view-types/must-restrict.rs | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/ui/view-types/hygiene.rs b/tests/ui/view-types/hygiene.rs index 20d184e184697..b0c8c9f29250f 100644 --- a/tests/ui/view-types/hygiene.rs +++ b/tests/ui/view-types/hygiene.rs @@ -26,7 +26,7 @@ struct Bar { } impl Bar { - fn f(self: hygiene::view_bar!()) {} + fn f(self: &hygiene::view_bar!()) {} } fn main() {} diff --git a/tests/ui/view-types/must-restrict.rs b/tests/ui/view-types/must-restrict.rs index a523f07e9aadd..85e4d7343f520 100644 --- a/tests/ui/view-types/must-restrict.rs +++ b/tests/ui/view-types/must-restrict.rs @@ -12,8 +12,8 @@ struct S { } // The outermost fields are supersets of the innermost views, we expect this to trigger an error. -fn f(_: view_type!(view_type!(S.{}).{ foo })) {} -fn g(_: view_type!(view_type!(S.{ foo }).{ bar })) {} -fn h(_: view_type!(view_type!(view_type!(S.{ foo }).{}).{ foo })) {} +fn f(_: &view_type!(view_type!(S.{}).{ foo })) {} +fn g(_: &view_type!(view_type!(S.{ foo }).{ bar })) {} +fn h(_: &view_type!(view_type!(view_type!(S.{ foo }).{}).{ foo })) {} fn main() {} From 94add9677e2de57a2e414350bedcd13f07426a5e Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 6 Nov 2026 12:46:17 +0100 Subject: [PATCH 10/39] view-types: add `View` variant to `TyKind` this commit is quite big because we want to always exhaustively match on all the `TyKind` variants. none of the `unimplemented!()` is reachable because we don't *actually* lower view types (yet!). --- compiler/rustc_borrowck/src/lib.rs | 6 ++++++ .../src/debuginfo/metadata.rs | 3 +++ .../src/debuginfo/type_names.rs | 3 +++ .../src/const_eval/type_info.rs | 6 ++++++ .../src/const_eval/valtrees.rs | 6 ++++++ .../src/interpret/intrinsics.rs | 3 +++ .../rustc_const_eval/src/interpret/stack.rs | 3 +++ .../src/interpret/validity.rs | 3 +++ .../rustc_const_eval/src/util/type_name.rs | 3 +++ .../src/coherence/inherent_impls.rs | 3 +++ .../src/coherence/orphan.rs | 3 +++ .../src/hir_ty_lowering/mod.rs | 3 +++ .../src/variance/constraints.rs | 3 +++ compiler/rustc_hir_typeck/src/cast.rs | 3 +++ compiler/rustc_hir_typeck/src/method/probe.rs | 3 +++ .../src/infer/canonical/canonicalizer.rs | 3 +++ compiler/rustc_lint/src/reference_casting.rs | 3 +++ .../rustc_lint/src/types/improper_ctypes.rs | 3 +++ compiler/rustc_middle/src/query/keys.rs | 3 +++ compiler/rustc_middle/src/ty/context.rs | 3 ++- compiler/rustc_middle/src/ty/error.rs | 3 +++ .../rustc_middle/src/ty/inhabitedness/mod.rs | 3 +++ compiler/rustc_middle/src/ty/layout.rs | 3 +++ compiler/rustc_middle/src/ty/offload_meta.rs | 3 +++ compiler/rustc_middle/src/ty/print/mod.rs | 3 +++ compiler/rustc_middle/src/ty/print/pretty.rs | 3 +++ .../src/ty/significant_drop_order.rs | 3 +++ .../rustc_middle/src/ty/structural_impls.rs | 9 ++++++++ compiler/rustc_middle/src/ty/sty.rs | 14 +++++++++++++ compiler/rustc_middle/src/ty/trait_def.rs | 3 +++ compiler/rustc_middle/src/ty/util.rs | 15 +++++++++++++ .../src/move_paths/builder.rs | 6 ++++++ .../src/dataflow_const_prop.rs | 3 +++ compiler/rustc_mir_transform/src/gvn.rs | 3 +++ .../src/canonical/canonicalizer.rs | 3 +++ .../rustc_next_trait_solver/src/coherence.rs | 3 +++ .../src/solve/assembly/mod.rs | 6 ++++++ .../src/solve/assembly/structural_traits.rs | 21 +++++++++++++++++++ .../src/solve/eval_ctxt/mod.rs | 3 +++ .../src/solve/normalizes_to.rs | 6 ++++++ .../src/solve/trait_goals.rs | 6 ++++++ compiler/rustc_passes/src/check_export.rs | 3 +++ compiler/rustc_pattern_analysis/src/rustc.rs | 3 +++ compiler/rustc_privacy/src/lib.rs | 3 +++ .../src/unstable/convert/stable/ty.rs | 3 +++ .../src/cfi/typeid/itanium_cxx_abi/encode.rs | 6 ++++++ .../cfi/typeid/itanium_cxx_abi/transform.rs | 3 +++ compiler/rustc_symbol_mangling/src/export.rs | 3 +++ compiler/rustc_symbol_mangling/src/v0.rs | 3 +++ .../traits/fulfillment_errors.rs | 3 +++ .../src/traits/effects.rs | 6 ++++++ .../src/traits/project.rs | 6 ++++++ .../src/traits/query/dropck_outlives.rs | 6 ++++++ .../src/traits/select/candidate_assembly.rs | 21 +++++++++++++++++++ .../src/traits/select/confirmation.rs | 3 +++ .../src/traits/select/mod.rs | 9 ++++++++ .../rustc_trait_selection/src/traits/wf.rs | 3 +++ compiler/rustc_ty_utils/src/layout.rs | 3 +++ compiler/rustc_ty_utils/src/needs_drop.rs | 3 +++ compiler/rustc_ty_utils/src/ty.rs | 6 ++++++ compiler/rustc_type_ir/src/fast_reject.rs | 9 ++++++++ compiler/rustc_type_ir/src/flags.rs | 3 +++ compiler/rustc_type_ir/src/inherent.rs | 3 +++ compiler/rustc_type_ir/src/outlives.rs | 3 +++ compiler/rustc_type_ir/src/ty_kind.rs | 13 ++++++++++++ compiler/rustc_type_ir/src/walk.rs | 3 +++ src/librustdoc/clean/mod.rs | 3 +++ src/librustdoc/clean/types.rs | 3 +++ .../passes/collect_intra_doc_links.rs | 3 +++ src/librustdoc/passes/collect_trait_impls.rs | 3 +++ .../clippy/clippy_lints/src/dereference.rs | 3 +++ 71 files changed, 335 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index a6e11d65fb577..9d1cae8e79642 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -1948,6 +1948,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> { | ty::Placeholder(_) => { bug!("When Place is Deref it's type shouldn't be {place_ty:#?}") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }, ProjectionElem::Field(_, _) => match place_ty.ty.kind() { ty::Adt(adt, _) => { @@ -1990,6 +1993,9 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, '_, 'tcx> { | ty::Placeholder(_) => bug!( "When Place contains ProjectionElem::Field it's type shouldn't be {place_ty:#?}" ), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }, ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => { match place_ty.ty.kind() { diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index ff0b924f5701e..0fafc6261ac48 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -501,6 +501,9 @@ pub(crate) fn spanned_type_di_node<'ll, 'tcx>( | ty::Error(_) => { bug!("debuginfo: unexpected type in type_di_node(): {:?}", t) } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; { diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 1034a0f417120..40c507ee75e8b 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -459,6 +459,9 @@ fn push_debuginfo_type_name<'tcx>( t ); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } /// MSVC names enums differently than other platforms so that the debugging visualization diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index fc32787fa8703..a52ee086f540c 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -159,6 +159,9 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { | ty::Placeholder(_) | ty::Infer(..) | ty::Error(_) => self.project_downcast_named(&field_dest, sym::Other)?.0, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; self.write_discriminant(variant_index, &field_dest)? } @@ -263,6 +266,9 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { ty::Closure(_, args) => ty::Binder::dummy(args), ty::CoroutineClosure(_, args) => ty::Binder::dummy(args), ty::Coroutine(_, args) => ty::Binder::dummy(args), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; // FIXME(type_info): also provide the late bound vars to reflection diff --git a/compiler/rustc_const_eval/src/const_eval/valtrees.rs b/compiler/rustc_const_eval/src/const_eval/valtrees.rs index de8dd989c6a00..b75d42f91aa99 100644 --- a/compiler/rustc_const_eval/src/const_eval/valtrees.rs +++ b/compiler/rustc_const_eval/src/const_eval/valtrees.rs @@ -208,6 +208,9 @@ fn const_to_valtree_inner<'tcx>( | ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::UnsafeBinder(_) => Err(ValTreeCreationError::NonSupportedType(ty)), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; visited.remove(place); @@ -382,6 +385,9 @@ pub fn valtree_to_const_value<'tcx>( | ty::UnsafeBinder(_) => { bug!("no ValTree should have been created for type {:?}", cv.ty.kind()) } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index a5f02b4a5d157..cb98672df7838 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -286,6 +286,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { | ty::Never | ty::Tuple(_) | ty::Error(_) => ConstValue::from_target_usize(0u64, &tcx), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; let val = self.const_val_to_op(val, dest.layout.ty, Some(dest.layout))?; self.copy_op(&val, dest)?; diff --git a/compiler/rustc_const_eval/src/interpret/stack.rs b/compiler/rustc_const_eval/src/interpret/stack.rs index 19a1dfe3e567b..d9171b806f743 100644 --- a/compiler/rustc_const_eval/src/interpret/stack.rs +++ b/compiler/rustc_const_eval/src/interpret/stack.rs @@ -555,6 +555,9 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("`is_very_trivially_sized` applied to unexpected type: {}", ty) } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 43a05b617cfb9..da40d54f262e1 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -1006,6 +1006,9 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { | ty::Param(..) | ty::Alias(..) | ty::CoroutineWitness(..) => bug!("Encountered invalid type {:?}", ty), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index ec56b053144c4..38fc0a24c32e3 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -71,6 +71,9 @@ impl<'tcx> Printer<'tcx> for TypeNamePrinter<'tcx> { bug!("type_name: unexpected inherent projection") } ty::CoroutineWitness(..) => bug!("type_name: unexpected `CoroutineWitness`"), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs index 591ff35becf81..e2393e8e2011c 100644 --- a/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs +++ b/compiler/rustc_hir_analysis/src/coherence/inherent_impls.rs @@ -225,6 +225,9 @@ impl<'tcx> InherentCollect<'tcx> { } // We could bail out here, but that will silence other useful errors. ty::Error(_) => Ok(()), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } diff --git a/compiler/rustc_hir_analysis/src/coherence/orphan.rs b/compiler/rustc_hir_analysis/src/coherence/orphan.rs index 43607f199b375..e5a3f1a245bdf 100644 --- a/compiler/rustc_hir_analysis/src/coherence/orphan.rs +++ b/compiler/rustc_hir_analysis/src/coherence/orphan.rs @@ -250,6 +250,9 @@ pub(crate) fn orphan_check_impl( } ty::Error(..) => (LocalImpl::Allow, NonlocalImpl::Allow), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; if trait_def_id.is_local() { 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 f15b8c81c51d2..62fb178d41951 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -3665,6 +3665,9 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { tcx, dcx.span_err(ty_span, format!("type `{ty}` is not yet supported in `field_of!`")), ), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index 114b7a5cf453d..59e2454be9c19 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -321,6 +321,9 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { ty::Placeholder(..) | ty::CoroutineWitness(..) | ty::Bound(..) | ty::Infer(..) => { bug!("unexpected type encountered in variance inference: {}", ty); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index a7cbd209c42b0..201cb061cf7f4 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -168,6 +168,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .span_delayed_bug(span, format!("`{t:?}` should be sized but is not?")); return Err(guar); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }) } } diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index f6cfe6faf7a79..f86f34489e9d7 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -954,6 +954,9 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { | ty::Pat(..) | ty::Placeholder(..) | ty::UnsafeBinder(..) => {} + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index f1f2077f81937..7de5c2ad091b2 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -428,6 +428,9 @@ impl<'cx, 'tcx> TypeFolder> for Canonicalizer<'cx, 'tcx> { t } } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_lint/src/reference_casting.rs b/compiler/rustc_lint/src/reference_casting.rs index 97f33806d3023..cdc4bd9212e80 100644 --- a/compiler/rustc_lint/src/reference_casting.rs +++ b/compiler/rustc_lint/src/reference_casting.rs @@ -316,6 +316,9 @@ fn is_ty_fully_unsafe_celled<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool // FIXME: How to handle unsafe binders? ty::UnsafeBinder(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_lint/src/types/improper_ctypes.rs b/compiler/rustc_lint/src/types/improper_ctypes.rs index 45615d1476f36..65c94b6c0be95 100644 --- a/compiler/rustc_lint/src/types/improper_ctypes.rs +++ b/compiler/rustc_lint/src/types/improper_ctypes.rs @@ -989,6 +989,9 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { | ty::Error(_) | ty::Placeholder(..) | ty::FnDef(..) => bug!("unexpected type in foreign function: {:?}", ty), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index 6f2fc5cac0024..fb8f161602344 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -455,6 +455,9 @@ fn def_id_of_type_cached<'a>(ty: Ty<'a>, visited: &mut SsoHashSet>) -> Op | ty::Error(_) | ty::Never | ty::Float(_) => None, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 007d12b5e8fa8..d33c4f72758f8 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1943,7 +1943,8 @@ impl<'tcx> TyCtxt<'tcx> { Infer, Alias, Pat, - Foreign + Foreign, + View )?; writeln!(fmt, "GenericArgs interner: #{}", self.interners.args.len())?; diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index fb4e30b161d44..989ed3aa2ad88 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -228,6 +228,9 @@ impl<'tcx> Ty<'tcx> { ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) => "type alias".into(), ty::Param(_) => "type parameter".into(), ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => "opaque type".into(), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } diff --git a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs index a06bc1662bcf5..4836fffef3c8a 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs @@ -342,6 +342,9 @@ impl<'tcx> OpsemInhabitedCtx<'tcx> { | ty::CoroutineWitness(..) => { bug!("non-normalized type in `is_opsem_uninhabited`: `{ty}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 80bfbb5b551e0..1f1a769665c26 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -1033,6 +1033,9 @@ where | ty::Param(_) | ty::Infer(_) | ty::Error(_) => bug!("TyAndLayout::field: unexpected type `{}`", this.ty), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_middle/src/ty/offload_meta.rs b/compiler/rustc_middle/src/ty/offload_meta.rs index 6cf8abc482260..97d77dd7cf689 100644 --- a/compiler/rustc_middle/src/ty/offload_meta.rs +++ b/compiler/rustc_middle/src/ty/offload_meta.rs @@ -185,6 +185,9 @@ impl MappingFlags { .span_err(rustc_span::DUMMY_SP, format!("type `{ty:?}` cannot be offloaded")); MappingFlags::empty() } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index 7c62c5a5c4f17..e2720b20c9229 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -347,6 +347,9 @@ fn characteristic_def_id_of_type_cached<'a>( | ty::Error(_) | ty::Never | ty::Float(_) => None, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } pub fn characteristic_def_id_of_type(ty: Ty<'_>) -> Option { diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 9666120a3ee3a..883852234b8cc 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1035,6 +1035,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty.print(self)?; write!(self, "]")?; } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } Ok(()) diff --git a/compiler/rustc_middle/src/ty/significant_drop_order.rs b/compiler/rustc_middle/src/ty/significant_drop_order.rs index d700c362cfa8d..3f5e3c8259349 100644 --- a/compiler/rustc_middle/src/ty/significant_drop_order.rs +++ b/compiler/rustc_middle/src/ty/significant_drop_order.rs @@ -156,5 +156,8 @@ pub fn ty_dtor_span<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option { | ty::FnDef(did, _) | ty::Foreign(did) => Some(tcx.def_span(did)), ty::Param(_) => None, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 810d6908829d6..2cffd53c28a1e 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -370,6 +370,9 @@ impl<'tcx> TypeSuperFoldable> for Ty<'tcx> { | ty::Placeholder(..) | ty::Never | ty::Foreign(..) => return Ok(self), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; Ok(if *self.kind() == kind { self } else { folder.cx().mk_ty_from_kind(kind) }) @@ -409,6 +412,9 @@ impl<'tcx> TypeSuperFoldable> for Ty<'tcx> { | ty::Placeholder(..) | ty::Never | ty::Foreign(..) => return self, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; if *self.kind() == kind { self } else { folder.cx().mk_ty_from_kind(kind) } @@ -462,6 +468,9 @@ impl<'tcx> TypeSuperVisitable> for Ty<'tcx> { | ty::Param(..) | ty::Never | ty::Foreign(..) => V::Result::output(), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 2a417812dd22e..d8f9ea9698f76 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1761,6 +1761,9 @@ impl<'tcx> Ty<'tcx> { | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("`discriminant_ty` applied to unexpected type: {:?}", self) } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -1793,6 +1796,8 @@ impl<'tcx> Ty<'tcx> { | ty::Error(_) => Ok(tcx.types.unit), // Extern types have metadata = (). ty::Foreign(..) => Ok(tcx.types.unit), + // FIXME(scrabsha): i expect views to behave like foreign types here? + ty::View(..) => Ok(tcx.types.unit), // If returned by `struct_tail_raw` this is a unit struct // without any fields, or not a struct, and therefore is Sized. ty::Adt(..) => Ok(tcx.types.unit), @@ -2006,6 +2011,9 @@ impl<'tcx> Ty<'tcx> { ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self) } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -2065,6 +2073,9 @@ impl<'tcx> Ty<'tcx> { ty::Param(..) | ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(..) => { false } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -2111,6 +2122,9 @@ impl<'tcx> Ty<'tcx> { | ty::CoroutineWitness(..) | ty::Alias(..) | ty::Error(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_middle/src/ty/trait_def.rs b/compiler/rustc_middle/src/ty/trait_def.rs index 114e5331b8b9b..8da60d6fc616e 100644 --- a/compiler/rustc_middle/src/ty/trait_def.rs +++ b/compiler/rustc_middle/src/ty/trait_def.rs @@ -268,6 +268,9 @@ impl<'tcx> TyCtxt<'tcx> { ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("unexpected self type: {self_ty:?}"); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } #[allow(rustc::usage_of_type_ir_traits)] diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 8e6850ca0f07a..a588114cda6ce 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -1217,6 +1217,9 @@ impl<'tcx> Ty<'tcx> { | ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -1267,6 +1270,9 @@ impl<'tcx> Ty<'tcx> { | ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -1321,6 +1327,9 @@ impl<'tcx> Ty<'tcx> { | ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -1490,6 +1499,9 @@ impl<'tcx> Ty<'tcx> { } ty::Foreign(_) | ty::CoroutineWitness(..) | ty::Error(_) | ty::UnsafeBinder(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -1595,6 +1607,9 @@ pub fn needs_drop_components_with_async<'tcx>( | ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::UnsafeBinder(_) => Ok(smallvec![ty]), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs index d4dddc5c1fcb1..c853ad9b5dbe4 100644 --- a/compiler/rustc_mir_dataflow/src/move_paths/builder.rs +++ b/compiler/rustc_mir_dataflow/src/move_paths/builder.rs @@ -173,6 +173,9 @@ impl<'a, 'tcx, F: Fn(Ty<'tcx>) -> bool> MoveDataBuilder<'a, 'tcx, F> { | ty::Placeholder(_) => { bug!("When Place is Deref it's type shouldn't be {place_ty:#?}") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }, MoveSubPath::Field(_) => match place_ty.kind() { ty::Adt(adt, _) => { @@ -213,6 +216,9 @@ impl<'a, 'tcx, F: Fn(Ty<'tcx>) -> bool> MoveDataBuilder<'a, 'tcx, F> { | ty::Placeholder(_) => bug!( "When Place contains ProjectionElem::Field its type shouldn't be {place_ty:#?}" ), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }, MoveSubPath::ConstantIndex(_) => match place_ty.kind() { ty::Slice(_) => { diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index ab7391b65bd79..4efa985af3195 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -874,6 +874,9 @@ fn try_write_constant<'tcx>( | ty::UnsafeBinder(_) => throw_machine_stop_str!("unsupported type"), ty::Error(_) | ty::Infer(..) | ty::CoroutineWitness(..) => bug!(), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } interp_ok(()) diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index b29bf5636f66c..33cb4de098b92 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -1754,6 +1754,9 @@ impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> { | ty::Alias(..) | ty::Param(_) | ty::Placeholder(_) => true, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } ty_may_have_ref_inner(self.tcx, ty, 0) diff --git a/compiler/rustc_next_trait_solver/src/canonical/canonicalizer.rs b/compiler/rustc_next_trait_solver/src/canonical/canonicalizer.rs index 9780bf8bbadd2..73be112e40244 100644 --- a/compiler/rustc_next_trait_solver/src/canonical/canonicalizer.rs +++ b/compiler/rustc_next_trait_solver/src/canonical/canonicalizer.rs @@ -419,6 +419,9 @@ impl<'a, D: SolverDelegate, I: Interner> Canonicalizer<'a, D, I> { | ty::Error(_) => { return t.super_fold_with(self); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; let var = self.get_or_insert_bound_var(t, kind); diff --git a/compiler/rustc_next_trait_solver/src/coherence.rs b/compiler/rustc_next_trait_solver/src/coherence.rs index ad6fc98601f69..a400a11c2eef8 100644 --- a/compiler/rustc_next_trait_solver/src/coherence.rs +++ b/compiler/rustc_next_trait_solver/src/coherence.rs @@ -447,6 +447,9 @@ where | ty::CoroutineWitness(..) => { unreachable!("unnameable type in coherence: {ty:?}"); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; // A bit of a hack, the `OrphanChecker` is only used to visit a `TraitRef`, so // the first type we visit is always the self type. 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 ed34da0477c05..a89e3e770db43 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -880,6 +880,9 @@ where self.cx().delay_bug(format!("could not normalize {self_ty:?}, it is not WF")); return Ok(()); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; match consider_self_bounds { @@ -989,6 +992,9 @@ where ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) | ty::Bound(..) => panic!("unexpected self type for `{goal:?}`"), ty::Dynamic(bounds, ..) => bounds, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; // Do not consider built-in object impls for dyn-incompatible types. 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 52285f8e0eff0..410458d6bbc5f 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 @@ -107,6 +107,9 @@ where .map(Unnormalized::skip_norm_wip) .collect(), )), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -186,6 +189,9 @@ where Ok(ty::Binder::dummy(vec![])) } } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -270,6 +276,9 @@ where | ty::Bound(..) => { panic!("unexpected type `{ty:?}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -410,6 +419,9 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable { panic!("unexpected type `{self_ty:?}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -590,6 +602,9 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_async_callable { panic!("unexpected type `{self_ty:?}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -761,6 +776,9 @@ pub(in crate::solve) fn extract_fn_def_from_const_callable( | ty::Bound(..) => { panic!("unexpected type `{self_ty:?}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -847,6 +865,9 @@ pub(in crate::solve) fn const_conditions_for_destruct( | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { panic!("unexpected type `{self_ty:?}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } 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 d382590dd31ed..71c4ae1f57e3a 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 @@ -759,6 +759,9 @@ where | ty::Closure(..) | ty::CoroutineClosure(..) | ty::Coroutine(..) => LowerAvailableDepth::Yes, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } else { LowerAvailableDepth::Yes diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs index da6f57f044d5a..a5dfecac89c02 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to.rs @@ -816,6 +816,9 @@ where "unexpected self ty `{:?}` when normalizing `::Metadata`", goal.predicate.self_ty() ), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| { @@ -1036,6 +1039,9 @@ where "unexpected self ty `{:?}` when normalizing `::Discriminant`", goal.predicate.self_ty() ), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| { 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 1157523585c5e..17a88ddb57376 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -842,6 +842,9 @@ where ) => { panic!("unexpected type `{ty:?}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) @@ -1531,6 +1534,9 @@ where ty::Infer(_) | ty::Alias(ty::IsRigid::No, _) | ty::Bound(_, _) => { panic!("unexpected type `{self_ty:?}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_passes/src/check_export.rs b/compiler/rustc_passes/src/check_export.rs index dbb6d4b72d432..a2965ff0c8441 100644 --- a/compiler/rustc_passes/src/check_export.rs +++ b/compiler/rustc_passes/src/check_export.rs @@ -321,6 +321,9 @@ impl<'tcx, 'a> TypeVisitor> for ExportableItemsChecker<'tcx, 'a> { } ty::Alias(..) | ty::Infer(_) | ty::Placeholder(_) | ty::Bound(..) => unreachable!(), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } ControlFlow::Continue(()) } diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index ea46150ed7ca2..7d7bb392b67d3 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -432,6 +432,9 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { ty::CoroutineWitness(_, _) | ty::Bound(_, _) | ty::Placeholder(_) | ty::Infer(_) => { bug!("Encountered unexpected type in `ConstructorSet::for_ty`: {ty:?}") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }) } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 926efb9ccd7c0..550f2ecfc8d69 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -314,6 +314,9 @@ where ty::Placeholder(..) | ty::Infer(..) => { bug!("unexpected type: {:?}", ty) } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } if V::SHALLOW { V::Result::output() } else { ty.super_visit_with(self) } diff --git a/compiler/rustc_public/src/unstable/convert/stable/ty.rs b/compiler/rustc_public/src/unstable/convert/stable/ty.rs index f4f461980023e..d60371f5e9ab4 100644 --- a/compiler/rustc_public/src/unstable/convert/stable/ty.rs +++ b/compiler/rustc_public/src/unstable/convert/stable/ty.rs @@ -508,6 +508,9 @@ impl<'tcx> Stable<'tcx> for ty::TyKind<'tcx> { ty::Placeholder(..) | ty::Infer(_) | ty::Error(_) => { unreachable!(); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } 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 30275f9f7244e..a76fc401c7c60 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 @@ -263,6 +263,9 @@ fn encode_const_value<'tcx>( | ty::Placeholder(..) => { bug!("encode_const_value: unexpected type `{:?}`", cv.ty); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } s @@ -750,6 +753,9 @@ pub(crate) fn encode_ty<'tcx>( | ty::Placeholder(..) => { bug!("encode_ty: unexpected `{:?}`", ty.kind()); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; typeid 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 0d47a89b2a002..69258a21cff03 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 @@ -226,6 +226,9 @@ impl<'tcx> TypeFolder> for TransformTy<'tcx> { ty::Bound(..) | ty::Error(..) | ty::Infer(..) | ty::Param(..) | ty::Placeholder(..) => { bug!("fold_ty: unexpected `{:?}`", t.kind()); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_symbol_mangling/src/export.rs b/compiler/rustc_symbol_mangling/src/export.rs index 65caeb4f63d97..2c730e494be28 100644 --- a/compiler/rustc_symbol_mangling/src/export.rs +++ b/compiler/rustc_symbol_mangling/src/export.rs @@ -126,6 +126,9 @@ impl<'tcx> AbiStableHash<'tcx> for Ty<'tcx> { | ty::UnsafeBinder(_) => unreachable!(), ty::Error(_) => {} + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 7ab3c4a87eb83..e53c598952df9 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -686,6 +686,9 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { ty::Alias(..) => bug!("symbol_names: unexpected alias"), ty::CoroutineWitness(..) => bug!("symbol_names: unexpected `CoroutineWitness`"), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } // Only cache types that do not refer to an enclosing 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 927a5bcd40d11..13ee44fd6bb5e 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 @@ -2179,6 +2179,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ty::Pat(..) => Some(22), ty::UnsafeBinder(..) => Some(23), ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_trait_selection/src/traits/effects.rs b/compiler/rustc_trait_selection/src/traits/effects.rs index f3fbd0ba6cafb..a71e1599b59b3 100644 --- a/compiler/rustc_trait_selection/src/traits/effects.rs +++ b/compiler/rustc_trait_selection/src/traits/effects.rs @@ -428,6 +428,9 @@ fn evaluate_host_effect_for_copy_clone_goal<'tcx>( .instantiate(tcx, args) .skip_norm_wip() .map_bound(|bound| bound.types.to_vec())), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }?; Ok(constituent_tys @@ -527,6 +530,9 @@ fn evaluate_host_effect_for_destruct_goal<'tcx>( | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { panic!("unexpected type `{self_ty:?}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; Ok(const_conditions diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 774fa5903c78f..7db270d23522b 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -1141,6 +1141,9 @@ fn assemble_candidates_from_impls<'cx, 'tcx>( | ty::Placeholder(..) | ty::Infer(..) | ty::Error(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }, Some(LangItem::PointeeTrait) => { let tail = selcx.tcx().struct_tail_raw( @@ -1228,6 +1231,9 @@ fn assemble_candidates_from_impls<'cx, 'tcx>( } false } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } _ if tcx.trait_is_auto(trait_ref.def_id) => { 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 e9e1cea48ba20..004f0b84fb15d 100644 --- a/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs +++ b/compiler/rustc_trait_selection/src/traits/query/dropck_outlives.rs @@ -88,6 +88,9 @@ pub fn trivial_dropck_outlives<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { | ty::Bound(..) | ty::Coroutine(..) | ty::UnsafeBinder(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -417,5 +420,8 @@ pub fn dtorck_constraint_for_ty_inner<'tcx>( // be fully resolved. tcx.dcx().span_delayed_bug(span, format!("Unresolved type in dropck: {:?}.", ty)); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } 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 a9362d4c90908..309f5e71b19f2 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -720,6 +720,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // FIXME: Function definitions could actually implement `FnPtr` by // casting the ZST function def to a function pointer. ty::FnDef(_, _) => return true, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } // Generic params can implement `FnPtr` if the predicate @@ -908,6 +911,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Error(_) => { candidates.vec.push(AutoImplCandidate); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } @@ -1246,6 +1252,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -1317,6 +1326,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -1369,6 +1381,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { | ty::Error(_) | ty::Infer(_) | ty::Placeholder(_) => {} + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -1417,6 +1432,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)) => { candidates.ambiguous = true; } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -1477,6 +1495,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { candidates.ambiguous = true; } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 1d0696d745373..7fd95ce874cb2 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -1261,6 +1261,9 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { panic!("unexpected type `{self_ty:?}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } ImplSource::Builtin(BuiltinImplSource::Misc, obligations) diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index f571baf278290..5dfb800ca1498 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -2080,6 +2080,9 @@ impl<'tcx> SelectionContext<'_, 'tcx> { | ty::Bound(..) => { bug!("asked to assemble `Sized` of unexpected type: {:?}", self_ty); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -2159,6 +2162,9 @@ impl<'tcx> SelectionContext<'_, 'tcx> { | ty::Infer(ty::TyVar(_) | ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -2306,6 +2312,9 @@ impl<'tcx> SelectionContext<'_, 'tcx> { }) } } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }) } diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index d5cfc2b58c6ec..588bb389d9cfa 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -1122,6 +1122,9 @@ impl<'a, 'tcx> TypeVisitor> for WfPredicates<'a, 'tcx> { ))), )); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } t.super_visit_with(self) diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 6404a062f2731..903dd3785b6be 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -893,6 +893,9 @@ fn layout_of_uncached<'tcx>( // `ty::Error` is handled at the top of this function. bug!("layout_of: unexpected type `{ty}`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }) } diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 522444651778d..61e93c9942b91 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -313,6 +313,9 @@ where | ty::Error(_) => { bug!("unexpected type returned by `needs_drop_components`: {component}") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 5e78517661275..cde54de921be1 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -74,6 +74,9 @@ fn sizedness_constraint_for_ty<'tcx>( ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => { bug!("unexpected type `{ty:?}` in `sizedness_constraint_for_ty`") } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -393,6 +396,9 @@ fn impl_self_is_guaranteed_unsized<'tcx>(tcx: TyCtxt<'tcx>, impl_def_id: DefId) | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_type_ir/src/fast_reject.rs b/compiler/rustc_type_ir/src/fast_reject.rs index 398fddcd4a141..9946286db08b6 100644 --- a/compiler/rustc_type_ir/src/fast_reject.rs +++ b/compiler/rustc_type_ir/src/fast_reject.rs @@ -144,6 +144,9 @@ pub fn simplify_type( ty::Foreign(def_id) => Some(SimplifiedType::Foreign(def_id.into())), ty::Error(_) => Some(SimplifiedType::Error), ty::Bound(..) | ty::Infer(_) => None, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } @@ -302,6 +305,9 @@ impl {} + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; // The type system needs to support exponentially large types @@ -481,6 +487,9 @@ impl true, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_type_ir/src/flags.rs b/compiler/rustc_type_ir/src/flags.rs index 4af4f1479ec82..ba42a5dc4980d 100644 --- a/compiler/rustc_type_ir/src/flags.rs +++ b/compiler/rustc_type_ir/src/flags.rs @@ -372,6 +372,9 @@ impl FlagComputation { computation.add_ty(ty); }) } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index a43ff4c1a2141..fb57a57883030 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -202,6 +202,9 @@ pub trait Ty>: | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } diff --git a/compiler/rustc_type_ir/src/outlives.rs b/compiler/rustc_type_ir/src/outlives.rs index 15741c926092e..151bb6f11a577 100644 --- a/compiler/rustc_type_ir/src/outlives.rs +++ b/compiler/rustc_type_ir/src/outlives.rs @@ -211,6 +211,9 @@ impl TypeVisitor for OutlivesCollector<'_, I> { | ty::Tuple(_) => { ty.super_visit_with(self); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index 70efba8361b24..16143c3d10e06 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -307,6 +307,13 @@ pub enum TyKind { /// A tuple type. For example, `(i32, bool)`. Tuple(I::Tys), + /// A view over an [`Adt`]. + /// + /// This variant contains the same data as `Adt` as well as a `Ty` field that represents the + /// set of fields that are viewed. This `Ty` should be either a type variable or a tuple of + /// `FieldRepresentingType`. + View(I::AdtDef, I::GenericArgs, I::Ty), + /// A projection, opaque type, free type alias, or inherent associated type. /// /// All of these types are represented as pairs of def-id and args, and can @@ -421,6 +428,9 @@ impl TyKind { | ty::Param(_) | ty::Bound(_, _) | ty::Placeholder(_) => false, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } @@ -488,6 +498,9 @@ impl fmt::Debug for TyKind { Placeholder(p) => write!(f, "{p:?}"), Infer(t) => write!(f, "{:?}", t), TyKind::Error(_) => write!(f, "{{type error}}"), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } diff --git a/compiler/rustc_type_ir/src/walk.rs b/compiler/rustc_type_ir/src/walk.rs index 11c81c47b4cf5..b7dba6d0d0c1c 100644 --- a/compiler/rustc_type_ir/src/walk.rs +++ b/compiler/rustc_type_ir/src/walk.rs @@ -150,6 +150,9 @@ fn push_inner(stack: &mut TypeWalkerStack, parent: I::GenericArg ty::UnsafeBinder(bound_ty) => { stack.push(bound_ty.skip_binder().into()); } + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }, ty::GenericArgKind::Lifetime(_) => {} ty::GenericArgKind::Const(parent_ct) => match parent_ct.kind() { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 47e46bc35f922..5f5fab6d24aae 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2376,6 +2376,9 @@ pub(crate) fn clean_middle_ty<'tcx>( ty::Infer(..) => panic!("Infer"), ty::Error(_) => FatalError.raise(), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index aa97a29ddecf3..8844816e26bd0 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -1786,6 +1786,9 @@ impl PrimitiveType { | ty::Param(..) | ty::Placeholder(..) | ty::UnsafeBinder(..) => None, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 669c2f652bb7d..df4fa2bed9c53 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -562,6 +562,9 @@ fn ty_to_res<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option { | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => return None, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }) } diff --git a/src/librustdoc/passes/collect_trait_impls.rs b/src/librustdoc/passes/collect_trait_impls.rs index 1b77ee74cbdbe..30123a91bffb8 100644 --- a/src/librustdoc/passes/collect_trait_impls.rs +++ b/src/librustdoc/passes/collect_trait_impls.rs @@ -260,6 +260,9 @@ impl SelfTyHead { | ty::Infer(..) => panic!("unexpected impl self ty {bound_ty}"), ty::Error(_) => FatalError.raise(), + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), } } } diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index d61a39b02172a..8a75feee99237 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -991,6 +991,9 @@ impl TyCoercionStability { }, ) | ty::UnsafeBinder(_) => Self::Deref, + + // FIXME(scrabsha) + ty::View(..) => unimplemented!(), }; } } From 8bb5d1dfe40ee0beb5a9a03ac512de2e1a90e167 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 6 Nov 2026 12:46:17 +0100 Subject: [PATCH 11/39] outline `TyCtxt::new_adt`'s `DefKind` check --- compiler/rustc_middle/src/ty/context.rs | 38 +++++++++++++++++++++++++ compiler/rustc_middle/src/ty/sty.rs | 36 +---------------------- 2 files changed, 39 insertions(+), 35 deletions(-) diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index d33c4f72758f8..d3440db8424c7 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -2385,6 +2385,44 @@ impl<'tcx> TyCtxt<'tcx> { } } + pub(crate) fn debug_assert_adt_def_kind_compatible(self, def: AdtDef<'tcx>) { + if cfg!(debug_assertions) { + match self.def_kind(def.did()) { + DefKind::Struct | DefKind::Union | DefKind::Enum => {} + DefKind::Mod + | DefKind::Variant + | DefKind::Trait + | DefKind::TyAlias + | DefKind::ForeignTy + | DefKind::TraitAlias + | DefKind::AssocTy + | DefKind::TyParam + | DefKind::Fn + | DefKind::Const + | DefKind::ConstParam + | DefKind::Static { .. } + | DefKind::Ctor(..) + | DefKind::AssocFn + | DefKind::AssocConst + | DefKind::Macro(..) + | DefKind::ExternCrate + | DefKind::Use + | DefKind::ForeignMod + | DefKind::AnonConst + | DefKind::OpaqueTy + | DefKind::Field + | DefKind::LifetimeParam + | DefKind::GlobalAsm + | DefKind::Impl { .. } + | DefKind::Closure + | DefKind::SyntheticCoroutineBody + | DefKind::TestBinderConstraints => { + bug!("not an adt: {def:?} ({:?})", self.def_kind(def.did())) + } + } + } + } + fn emit_bug_args_compatible( self, def_id: DefId, diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index d8f9ea9698f76..336782ff19eb7 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -637,41 +637,7 @@ impl<'tcx> Ty<'tcx> { #[inline] pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgs<'tcx>) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def.did(), args); - if cfg!(debug_assertions) { - match tcx.def_kind(def.did()) { - DefKind::Struct | DefKind::Union | DefKind::Enum => {} - DefKind::Mod - | DefKind::Variant - | DefKind::Trait - | DefKind::TyAlias - | DefKind::ForeignTy - | DefKind::TraitAlias - | DefKind::AssocTy - | DefKind::TyParam - | DefKind::Fn - | DefKind::Const - | DefKind::ConstParam - | DefKind::Static { .. } - | DefKind::Ctor(..) - | DefKind::AssocFn - | DefKind::AssocConst - | DefKind::Macro(..) - | DefKind::ExternCrate - | DefKind::Use - | DefKind::ForeignMod - | DefKind::AnonConst - | DefKind::OpaqueTy - | DefKind::Field - | DefKind::LifetimeParam - | DefKind::GlobalAsm - | DefKind::Impl { .. } - | DefKind::Closure - | DefKind::SyntheticCoroutineBody - | DefKind::TestBinderConstraints => { - bug!("not an adt: {def:?} ({:?})", tcx.def_kind(def.did())) - } - } - } + tcx.debug_assert_adt_def_kind_compatible(def); Ty::new(tcx, Adt(def, args)) } From 292f9b10ddde28c4ba348cb0510c305a4a9c089e Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 6 Nov 2026 12:46:17 +0100 Subject: [PATCH 12/39] view-types: lower view types from HIR types /!\ the test suite is has not been updated /!\ the `unreachable!()`s added previously are suddenly reached, triggering literally all the view types test suite to ICE. this is fixed by the next commit. --- .../src/hir_ty_lowering/mod.rs | 44 +++++++++---------- compiler/rustc_middle/src/ty/sty.rs | 19 ++++++++ 2 files changed, 39 insertions(+), 24 deletions(-) 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 62fb178d41951..5074aa3a25dd4 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -3911,33 +3911,30 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } // Step 2: check that the viewed type is a struct. - let variant = match inner_ty.kind() { - ty::Adt(def, _) if def.is_struct() => def.non_enum_variant(), - - ty::Adt(def, _) => { - let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedAdt { - ty: inner_ty, - span: ty_span, - article: def.article(), - kind: def.descr(), - }); - return Ty::new_error(self.tcx(), guar); - } - - _ => { - let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedNonAdt { - ty: inner_ty, - span: ty_span, - }); - return Ty::new_error(self.tcx(), guar); - } + let (ty::Adt(def, args) | ty::View(def, args, _)) = inner_ty.kind() else { + let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedNonAdt { + ty: inner_ty, + span: ty_span, + }); + return Ty::new_error(self.tcx(), guar); }; + if !def.is_struct() { + let guar = self.dcx().emit_err(diagnostics::OnlyStructsCanBeViewedAdt { + ty: inner_ty, + span: ty_span, + article: def.article(), + kind: def.descr(), + }); + return Ty::new_error(self.tcx(), guar); + } + // Step 3: check that every viewed field exists. let mut viewed_indices = Vec::with_capacity(viewed_fields.len()); let mut error = None; for field in viewed_fields { - let Some((_, field)) = variant + let Some((field_idx, _)) = def + .non_enum_variant() .fields .iter_enumerated() .find(|(_, f)| f.ident(self.tcx()).normalize_to_macros_2_0() == field) @@ -3948,13 +3945,12 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { continue; }; - viewed_indices.push(field); + viewed_indices.push(field_idx); } if let Some(guar) = error { return Ty::new_error(self.tcx(), guar); } - // FIXME(scrabsha): actually lower view types. - inner_ty + Ty::new_view(self.tcx(), *def, *args, &viewed_indices) } } diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 336782ff19eb7..03f3e1be9a75a 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -835,6 +835,25 @@ impl<'tcx> Ty<'tcx> { Ty::new_coroutine_witness(tcx, def_id, args) } + pub fn new_view( + tcx: TyCtxt<'tcx>, + def: AdtDef<'tcx>, + args: GenericArgs<'tcx>, + fields: &[FieldIdx], + ) -> Ty<'tcx> { + tcx.debug_assert_args_compatible(def.did(), args); + tcx.debug_assert_adt_def_kind_compatible(def); + + let base = Ty::new_adt(tcx, def, args); + + let fields = fields + .iter() + .map(|field| Ty::new_field_representing_type(tcx, base, FIRST_VARIANT, *field)); + let fields = Ty::new_tup_from_iter(tcx, fields); + + Ty::new(tcx, TyKind::View(def, args, fields)) + } + // misc #[inline] From c74615ed43cbf3211dcb0fdbc622dab7c340c686 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 6 Nov 2026 12:46:17 +0100 Subject: [PATCH 13/39] view-types: remove FIXMEs reachable from the test suite --- .../src/infer/canonical/canonicalizer.rs | 4 +-- compiler/rustc_middle/src/ty/context.rs | 4 +-- compiler/rustc_middle/src/ty/print/pretty.rs | 10 ++++--- .../rustc_middle/src/ty/structural_impls.rs | 12 +++++---- compiler/rustc_middle/src/ty/sty.rs | 11 +++----- compiler/rustc_middle/src/ty/trait_def.rs | 6 ++--- compiler/rustc_privacy/src/lib.rs | 4 +-- .../src/traits/project.rs | 5 ++-- .../src/traits/select/candidate_assembly.rs | 5 +--- .../rustc_trait_selection/src/traits/wf.rs | 10 +++++-- compiler/rustc_type_ir/src/fast_reject.rs | 5 ++-- compiler/rustc_type_ir/src/flags.rs | 6 +++-- compiler/rustc_type_ir/src/outlives.rs | 6 ++--- tests/ui/view-types/duplicate_field.rs | 2 ++ tests/ui/view-types/duplicate_field.stderr | 23 ++++++++++++++-- tests/ui/view-types/hygiene.rs | 3 ++- tests/ui/view-types/hygiene.stderr | 26 +++++++++++++++++++ tests/ui/view-types/syntax-errors.rs | 1 + tests/ui/view-types/syntax-errors.stderr | 14 ++++++++-- tests/ui/view-types/tuple-structs.rs | 3 +-- tests/ui/view-types/tuple-structs.stderr | 12 +++++++++ 21 files changed, 120 insertions(+), 52 deletions(-) create mode 100644 tests/ui/view-types/hygiene.stderr create mode 100644 tests/ui/view-types/tuple-structs.stderr diff --git a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs index 7de5c2ad091b2..363adb6321ae2 100644 --- a/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs +++ b/compiler/rustc_infer/src/infer/canonical/canonicalizer.rs @@ -418,6 +418,7 @@ impl<'cx, 'tcx> TypeFolder> for Canonicalizer<'cx, 'tcx> { | ty::UnsafeBinder(_) | ty::Never | ty::Tuple(..) + | ty::View(..) | ty::Alias(..) | ty::Foreign(..) | ty::Pat(..) @@ -428,9 +429,6 @@ impl<'cx, 'tcx> TypeFolder> for Canonicalizer<'cx, 'tcx> { t } } - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index d3440db8424c7..30a77f2587026 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1938,13 +1938,13 @@ impl<'tcx> TyCtxt<'tcx> { Closure, CoroutineClosure, Tuple, + View, Bound, Param, Infer, Alias, Pat, - Foreign, - View + Foreign )?; writeln!(fmt, "GenericArgs interner: #{}", self.interners.args.len())?; diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index 883852234b8cc..a6a12699c8043 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -1035,9 +1035,13 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { ty.print(self)?; write!(self, "]")?; } - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), + ty::View(def, args, fields) => { + write!(self, "view_type!(")?; + self.print_def_path(def.did(), args)?; + write!(self, ".{{ ")?; + self.print_type(fields)?; + write!(self, " }})")?; + } } Ok(()) diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 2cffd53c28a1e..42c0341f7353e 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -398,6 +398,9 @@ impl<'tcx> TypeSuperFoldable> for Ty<'tcx> { ty::CoroutineClosure(did, args) => ty::CoroutineClosure(did, args.fold_with(folder)), ty::Alias(is_rigid, data) => ty::Alias(is_rigid, data.fold_with(folder)), ty::Pat(ty, pat) => ty::Pat(ty.fold_with(folder), pat.fold_with(folder)), + ty::View(tid, args, fields) => { + ty::View(tid, args.fold_with(folder), fields.fold_with(folder)) + } ty::Bool | ty::Char @@ -412,9 +415,6 @@ impl<'tcx> TypeSuperFoldable> for Ty<'tcx> { | ty::Placeholder(..) | ty::Never | ty::Foreign(..) => return self, - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), }; if *self.kind() == kind { self } else { folder.cx().mk_ty_from_kind(kind) } @@ -469,8 +469,10 @@ impl<'tcx> TypeSuperVisitable> for Ty<'tcx> { | ty::Never | ty::Foreign(..) => V::Result::output(), - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), + ty::View(_, args, fields) => { + try_visit!(args.visit_with(visitor)); + fields.visit_with(visitor) + } } } } diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 03f3e1be9a75a..05d861d093f85 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1989,16 +1989,15 @@ impl<'tcx> Ty<'tcx> { ty.instantiate(tcx, args).skip_norm_wip().has_trivial_sizedness(tcx, sizedness) }), - ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) => false, + ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) | ty::Bound(..) | ty::View(..) => { + false + } ty::Infer(ty::TyVar(_)) => false, ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("`has_trivial_sizedness` applied to unexpected type: {:?}", self) } - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } @@ -2106,10 +2105,8 @@ impl<'tcx> Ty<'tcx> { | ty::Coroutine(..) | ty::CoroutineWitness(..) | ty::Alias(..) + | ty::View(..) | ty::Error(_) => false, - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_middle/src/ty/trait_def.rs b/compiler/rustc_middle/src/ty/trait_def.rs index 8da60d6fc616e..13de0b04d3157 100644 --- a/compiler/rustc_middle/src/ty/trait_def.rs +++ b/compiler/rustc_middle/src/ty/trait_def.rs @@ -175,7 +175,8 @@ impl<'tcx> TyCtxt<'tcx> { | ty::Coroutine(_, _) | ty::Never | ty::Tuple(_) - | ty::UnsafeBinder(_) => { + | ty::UnsafeBinder(_) + | ty::View(_, _, _) => { let simp = ty::fast_reject::simplify_type( tcx, self_ty, @@ -268,9 +269,6 @@ impl<'tcx> TyCtxt<'tcx> { ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("unexpected self type: {self_ty:?}"); } - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } #[allow(rustc::usage_of_type_ir_traits)] diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index 550f2ecfc8d69..a9ecf10d17ff7 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -183,6 +183,7 @@ where let ty_kind = *ty.kind(); match ty_kind { ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..) + | ty::View(ty::AdtDef(Interned(&ty::AdtDefData { did: def_id, .. }, _)), ..) | ty::Foreign(def_id) | ty::FnDef(def_id, ..) | ty::Closure(def_id, ..) @@ -314,9 +315,6 @@ where ty::Placeholder(..) | ty::Infer(..) => { bug!("unexpected type: {:?}", ty) } - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } if V::SHALLOW { V::Result::output() } else { ty.super_visit_with(self) } diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 7db270d23522b..a5ea2ad1c4fe3 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -1191,6 +1191,8 @@ fn assemble_candidates_from_impls<'cx, 'tcx>( | ty::Adt(..) // If returned by `struct_tail` this is the empty tuple. | ty::Tuple(..) + // FIXME(scrabsha): i guess view types behave like foreign types here? + | ty::View(_, _, _) // Integers and floats are always Sized, and so have unit type metadata. | ty::Infer(ty::InferTy::IntVar(_) | ty::InferTy::FloatVar(..)) // This happens if we reach the recursion limit when finding the struct tail. @@ -1231,9 +1233,6 @@ fn assemble_candidates_from_impls<'cx, 'tcx>( } false } - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } _ if tcx.trait_is_auto(trait_ref.def_id) => { 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 309f5e71b19f2..81eb9284bd315 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -1312,7 +1312,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { }, // Not `MetaSized` or `Sized`. - ty::Foreign(..) => {} + ty::Foreign(..) | ty::View(..) => {} ty::Alias(..) | ty::Param(_) | ty::Placeholder(..) => {} @@ -1326,9 +1326,6 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { bug!("asked to assemble builtin bounds of unexpected type: {:?}", self_ty); } - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 588bb389d9cfa..2f1ec0414e3fd 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -1123,8 +1123,14 @@ impl<'a, 'tcx> TypeVisitor> for WfPredicates<'a, 'tcx> { )); } - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), + ty::View(def, args, _fields) => { + // FIXME(scrabsha): what should we require from fields? + + // WfNominalType + self.nominal_obligations(def.did(), args, |this, obligation| { + this.out.push(obligation) + }); + } } t.super_visit_with(self) diff --git a/compiler/rustc_type_ir/src/fast_reject.rs b/compiler/rustc_type_ir/src/fast_reject.rs index 9946286db08b6..487880d858099 100644 --- a/compiler/rustc_type_ir/src/fast_reject.rs +++ b/compiler/rustc_type_ir/src/fast_reject.rs @@ -37,6 +37,7 @@ pub enum SimplifiedType { Coroutine(DefId), CoroutineWitness(DefId), Function(usize), + View(DefId), UnsafeBinder, Placeholder, Error, @@ -142,11 +143,9 @@ pub fn simplify_type( TreatParams::AsRigid | TreatParams::InstantiateWithInfer => None, }, ty::Foreign(def_id) => Some(SimplifiedType::Foreign(def_id.into())), + ty::View(def, _, _) => Some(SimplifiedType::View(def.def_id().into())), ty::Error(_) => Some(SimplifiedType::Error), ty::Bound(..) | ty::Infer(_) => None, - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } diff --git a/compiler/rustc_type_ir/src/flags.rs b/compiler/rustc_type_ir/src/flags.rs index ba42a5dc4980d..26476826b1d19 100644 --- a/compiler/rustc_type_ir/src/flags.rs +++ b/compiler/rustc_type_ir/src/flags.rs @@ -373,8 +373,10 @@ impl FlagComputation { }) } - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), + ty::View(_, args, fields) => { + self.add_args(args.as_slice()); + self.add_ty(fields); + } } } diff --git a/compiler/rustc_type_ir/src/outlives.rs b/compiler/rustc_type_ir/src/outlives.rs index 151bb6f11a577..35747ffcb5535 100644 --- a/compiler/rustc_type_ir/src/outlives.rs +++ b/compiler/rustc_type_ir/src/outlives.rs @@ -208,12 +208,10 @@ impl TypeVisitor for OutlivesCollector<'_, I> { | ty::FnPtr(..) | ty::UnsafeBinder(_) | ty::Dynamic(_, _) - | ty::Tuple(_) => { + | ty::Tuple(_) + | ty::View(_, _, _) => { ty.super_visit_with(self); } - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } diff --git a/tests/ui/view-types/duplicate_field.rs b/tests/ui/view-types/duplicate_field.rs index 4b3e0ca0850e0..a9d4d40ae157d 100644 --- a/tests/ui/view-types/duplicate_field.rs +++ b/tests/ui/view-types/duplicate_field.rs @@ -19,11 +19,13 @@ fn f( impl Foo { fn f(self: &mut view_type!(Self.{ bar, bar })) {} //~^ ERROR field `bar` is already part of the view + //~| ERROR invalid `self` parameter type } impl Pair { fn f(self: &mut view_type!(Self.{ 0, 0 })) {} //~^ ERROR field `0` is already part of the view + //~| ERROR invalid `self` parameter type } fn main() {} diff --git a/tests/ui/view-types/duplicate_field.stderr b/tests/ui/view-types/duplicate_field.stderr index c974b0ead238a..75dfe30be0121 100644 --- a/tests/ui/view-types/duplicate_field.stderr +++ b/tests/ui/view-types/duplicate_field.stderr @@ -22,13 +22,32 @@ LL | fn f(self: &mut view_type!(Self.{ bar, bar })) {} | | | field `bar` is declared as viewed here +error[E0307]: invalid `self` parameter type: `&mut view_type!(Foo.{ (field_of!(Foo, bar),) })` + --> $DIR/duplicate_field.rs:20:16 + | +LL | fn f(self: &mut view_type!(Self.{ bar, bar })) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: type of `self` must be `Self` or a type that dereferences to it + = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) + error: field `0` is already part of the view - --> $DIR/duplicate_field.rs:25:42 + --> $DIR/duplicate_field.rs:26:42 | LL | fn f(self: &mut view_type!(Self.{ 0, 0 })) {} | - ^ | | | field `0` is declared as viewed here -error: aborting due to 4 previous errors +error[E0307]: invalid `self` parameter type: `&mut view_type!(Pair.{ (field_of!(Pair, 0),) })` + --> $DIR/duplicate_field.rs:26:16 + | +LL | fn f(self: &mut view_type!(Self.{ 0, 0 })) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: type of `self` must be `Self` or a type that dereferences to it + = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) + +error: aborting due to 6 previous errors +For more information about this error, try `rustc --explain E0307`. diff --git a/tests/ui/view-types/hygiene.rs b/tests/ui/view-types/hygiene.rs index b0c8c9f29250f..f2d1a69d68eb4 100644 --- a/tests/ui/view-types/hygiene.rs +++ b/tests/ui/view-types/hygiene.rs @@ -1,4 +1,3 @@ -//@ run-pass //@ aux-build: hygiene.rs #![feature(view_types, decl_macro)] @@ -16,6 +15,7 @@ pub macro what($name: ident) { impl Foo { fn f(self: &mut view_type!(Self.{ bar, $name })) {} + //~^ ERROR invalid `self` parameter type } } @@ -27,6 +27,7 @@ struct Bar { impl Bar { fn f(self: &hygiene::view_bar!()) {} + //~^ ERROR invalid `self` parameter type } fn main() {} diff --git a/tests/ui/view-types/hygiene.stderr b/tests/ui/view-types/hygiene.stderr new file mode 100644 index 0000000000000..eb368fe73fa5e --- /dev/null +++ b/tests/ui/view-types/hygiene.stderr @@ -0,0 +1,26 @@ +error[E0307]: invalid `self` parameter type: `&mut view_type!(Foo.{ (field_of!(Foo, bar), field_of!(Foo, bar)) })` + --> $DIR/hygiene.rs:17:20 + | +LL | pub macro what($name: ident) { +... +LL | fn f(self: &mut view_type!(Self.{ bar, $name })) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +... +LL | what!(bar); + | ---------- in this macro invocation + | + = note: type of `self` must be `Self` or a type that dereferences to it + = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) + +error[E0307]: invalid `self` parameter type: `&view_type!(Bar.{ (field_of!(Bar, async),) })` + --> $DIR/hygiene.rs:29:16 + | +LL | fn f(self: &hygiene::view_bar!()) {} + | ^^^^^^^^^^^^^^^^^^^^^ + | + = note: type of `self` must be `Self` or a type that dereferences to it + = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0307`. diff --git a/tests/ui/view-types/syntax-errors.rs b/tests/ui/view-types/syntax-errors.rs index 84bcb977827e0..6e621dfc96646 100644 --- a/tests/ui/view-types/syntax-errors.rs +++ b/tests/ui/view-types/syntax-errors.rs @@ -23,6 +23,7 @@ impl Foo { fn no_comma(self: &mut view_type!(Foo.{ bar baz }), _: &mut view_type!(Foo.{ bar baz })) {} //~^ ERROR expected one of //~| ERROR expected one of + //~| ERROR invalid `self` parameter type } fn main() {} diff --git a/tests/ui/view-types/syntax-errors.stderr b/tests/ui/view-types/syntax-errors.stderr index 479151b267e2e..0775aa1b4daad 100644 --- a/tests/ui/view-types/syntax-errors.stderr +++ b/tests/ui/view-types/syntax-errors.stderr @@ -72,6 +72,16 @@ error[E0609]: no field `r#for` on type `Foo` LL | fn keyword(self: &mut view_type!(Foo.{ where }), _: &mut view_type!(Foo.{ for })) {} | ^^^ -error: aborting due to 10 previous errors +error[E0307]: invalid `self` parameter type: `&mut view_type!(Foo.{ (field_of!(Foo, bar), field_of!(Foo, baz)) })` + --> $DIR/syntax-errors.rs:23:23 + | +LL | fn no_comma(self: &mut view_type!(Foo.{ bar baz }), _: &mut view_type!(Foo.{ bar baz })) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: type of `self` must be `Self` or a type that dereferences to it + = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) + +error: aborting due to 11 previous errors -For more information about this error, try `rustc --explain E0609`. +Some errors have detailed explanations: E0307, E0609. +For more information about an error, try `rustc --explain E0307`. diff --git a/tests/ui/view-types/tuple-structs.rs b/tests/ui/view-types/tuple-structs.rs index 04dd222cef98d..15fe5b2b60807 100644 --- a/tests/ui/view-types/tuple-structs.rs +++ b/tests/ui/view-types/tuple-structs.rs @@ -1,5 +1,3 @@ -//@ run-pass - #![feature(view_types)] #![allow(unused)] @@ -9,6 +7,7 @@ struct Pair(usize, u32); impl Pair { fn foo(self: &mut view_type!(Pair.{ 0, 1 })) {} + //~^ ERROR invalid `self` parameter type fn bar(_pair: &mut view_type!(Pair.{ 0, 1 })) {} } diff --git a/tests/ui/view-types/tuple-structs.stderr b/tests/ui/view-types/tuple-structs.stderr new file mode 100644 index 0000000000000..674742527ab00 --- /dev/null +++ b/tests/ui/view-types/tuple-structs.stderr @@ -0,0 +1,12 @@ +error[E0307]: invalid `self` parameter type: `&mut view_type!(Pair.{ (field_of!(Pair, 0), field_of!(Pair, 1)) })` + --> $DIR/tuple-structs.rs:9:18 + | +LL | fn foo(self: &mut view_type!(Pair.{ 0, 1 })) {} + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: type of `self` must be `Self` or a type that dereferences to it + = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0307`. From 00bbf35e99444878d990d0b9ca8aca84431dabd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Rakic?= Date: Tue, 10 Nov 2026 17:34:23 +0100 Subject: [PATCH 14/39] use the correct cargo stage when not optimizing cargo By default, we optimize cargo and thus need to run the stage2 PGO-instrumented cargo binary to get its profiles. When we opt out of that, we don't have a stage2 cargo, and don't need it, so we just use the regular stage0 cargo there. --- src/tools/opt-dist/src/training.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/tools/opt-dist/src/training.rs b/src/tools/opt-dist/src/training.rs index 88a22ffe569e4..5df5419cd7bb0 100644 --- a/src/tools/opt-dist/src/training.rs +++ b/src/tools/opt-dist/src/training.rs @@ -14,6 +14,12 @@ fn init_compiler_benchmarks( scenarios: &[&str], crates: &[&str], ) -> CmdBuilder { + // If we're currently trying to optimize cargo, we need to run benchmarks with the + // PGO-instrumented binary we just built to actually gather the profiles: the stage2 cargo. + // Otherwise, running the benchmarks using the beta/stage0 cargo is enough. + let benchmark_cargo = + if env.optimize_cargo { env.cargo_stage_2() } else { env.cargo_stage_0() }; + // Run rustc-perf benchmarks // Benchmark using profile_local with eprintln, which essentially just means // don't actually benchmark -- just make sure we run rustc a bunch of times. @@ -31,7 +37,7 @@ fn init_compiler_benchmarks( "--id", "Test", "--cargo", - env.cargo_stage_2().as_str(), + benchmark_cargo.as_str(), "--profiles", profiles.join(",").as_str(), "--scenarios", From b21e098e940a9ecaf1b8adaba68b2cbec9e83133 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Thu, 12 Nov 2026 11:44:51 +0100 Subject: [PATCH 15/39] Update `sysinfo` version to `0.40.3` --- Cargo.lock | 4 +-- src/bootstrap/Cargo.lock | 4 +-- src/bootstrap/Cargo.toml | 2 +- src/bootstrap/src/utils/metrics.rs | 47 +++++++++++++++++++---------- src/tools/opt-dist/Cargo.toml | 2 +- src/tools/opt-dist/src/utils/mod.rs | 6 ++-- 6 files changed, 40 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 53de49d87d5f9..5f0194a78143e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5634,9 +5634,9 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.39.2" +version = "0.40.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14311e7e9a03114cd4b65eedd54e8fed2945e17f08586ae97ef53bc0669f9581" +checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6" dependencies = [ "libc", "objc2-core-foundation", diff --git a/src/bootstrap/Cargo.lock b/src/bootstrap/Cargo.lock index 4d72f562a0bc6..1a327cb45f96a 100644 --- a/src/bootstrap/Cargo.lock +++ b/src/bootstrap/Cargo.lock @@ -688,9 +688,9 @@ dependencies = [ [[package]] name = "sysinfo" -version = "0.39.2" +version = "0.40.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14311e7e9a03114cd4b65eedd54e8fed2945e17f08586ae97ef53bc0669f9581" +checksum = "a86bac2f7d06e6384984118ad727f5694110f0ec44d924d05c8fdec3d030bee6" dependencies = [ "libc", "memchr", diff --git a/src/bootstrap/Cargo.toml b/src/bootstrap/Cargo.toml index fa744c895477f..c7bef3a36eaeb 100644 --- a/src/bootstrap/Cargo.toml +++ b/src/bootstrap/Cargo.toml @@ -62,7 +62,7 @@ xz2 = "0.1" # tidy-alphabetical-end # Dependencies needed by the build-metrics feature -sysinfo = { version = "0.39.2", default-features = false, optional = true, features = ["system"] } +sysinfo = { version = "0.40.3", default-features = false, optional = true, features = ["system"] } # Dependencies needed by the `tracing` feature chrono = { version = "0.4", default-features = false, optional = true, features = ["now", "std"] } diff --git a/src/bootstrap/src/utils/metrics.rs b/src/bootstrap/src/utils/metrics.rs index 79d967452d0c5..e907a8a5a1aab 100644 --- a/src/bootstrap/src/utils/metrics.rs +++ b/src/bootstrap/src/utils/metrics.rs @@ -58,7 +58,8 @@ impl BuildMetrics { system_info: System::new_with_specifics( RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()), - ), + ) + .ok(), timer_start: None, invocation_timer_start: Instant::now(), invocation_start: SystemTime::now(), @@ -80,7 +81,9 @@ impl BuildMetrics { self.collect_stats(&mut state); } - state.system_info.refresh_cpu_usage(); + if let Some(ref mut system_info) = state.system_info { + system_info.refresh_cpu_usage(); + } state.timer_start = Some(Instant::now()); state.running_steps.push(StepMetrics { @@ -113,7 +116,9 @@ impl BuildMetrics { state.running_steps.last_mut().unwrap().children.push(step); // Start collecting again for the parent step. - state.system_info.refresh_cpu_usage(); + if let Some(ref mut system_info) = state.system_info { + system_info.refresh_cpu_usage(); + } state.timer_start = Some(Instant::now()); } } @@ -151,9 +156,11 @@ impl BuildMetrics { let elapsed = state.timer_start.unwrap().elapsed(); step.duration_excluding_children_sec += elapsed; - state.system_info.refresh_cpu_usage(); - let cpu = state.system_info.cpus().iter().map(|p| p.cpu_usage()).sum::(); - step.cpu_usage_time_sec += cpu as f64 / 100.0 * elapsed.as_secs_f64(); + if let Some(ref mut system_info) = state.system_info { + system_info.refresh_cpu_usage(); + let cpu = system_info.cpus().iter().map(|p| p.usage()).sum::(); + step.cpu_usage_time_sec += cpu as f64 / 100.0 * elapsed.as_secs_f64(); + } } pub(crate) fn persist(&self, sess: &Session) { @@ -162,18 +169,26 @@ impl BuildMetrics { let dest = sess.out.join("metrics.json"); - let mut system = System::new_with_specifics( + let system_stats = if let Ok(mut system) = System::new_with_specifics( RefreshKind::nothing().with_cpu(CpuRefreshKind::everything()), - ); - system.refresh_cpu_usage(); - system.refresh_memory(); - - let system_stats = JsonInvocationSystemStats { - cpu_threads_count: system.cpus().len(), - cpu_model: system.cpus()[0].brand().into(), + ) { + system.refresh_cpu_usage(); + system.refresh_memory(); + JsonInvocationSystemStats { + cpu_threads_count: system.cpus().len(), + cpu_model: system.cpus()[0].brand().into(), + + memory_total_bytes: system.total_memory(), + } + } else { + JsonInvocationSystemStats { + cpu_threads_count: 0, + cpu_model: String::new(), - memory_total_bytes: system.total_memory(), + memory_total_bytes: 0, + } }; + let steps = std::mem::take(&mut state.finished_steps); // Some of our CI builds consist of multiple independent CI invocations. Ensure all the @@ -265,7 +280,7 @@ struct MetricsState { finished_steps: Vec, running_steps: Vec, - system_info: System, + system_info: Option, timer_start: Option, invocation_timer_start: Instant, invocation_start: SystemTime, diff --git a/src/tools/opt-dist/Cargo.toml b/src/tools/opt-dist/Cargo.toml index 5893bf87b5c34..222649a3acc73 100644 --- a/src/tools/opt-dist/Cargo.toml +++ b/src/tools/opt-dist/Cargo.toml @@ -10,7 +10,7 @@ log = "0.4" anyhow = "1" humantime = "2" humansize = "2" -sysinfo = { version = "0.39.2", default-features = false, features = ["disk"] } +sysinfo = { version = "0.40.3", default-features = false, features = ["disk"] } fs_extra = "1" camino = "1" tar = "0.4.45" diff --git a/src/tools/opt-dist/src/utils/mod.rs b/src/tools/opt-dist/src/utils/mod.rs index fb4f14ea41aea..12fee79224cce 100644 --- a/src/tools/opt-dist/src/utils/mod.rs +++ b/src/tools/opt-dist/src/utils/mod.rs @@ -16,9 +16,9 @@ pub fn format_env_variables() -> String { } pub fn print_free_disk_space() -> anyhow::Result<()> { - let disks = Disks::new_with_refreshed_list(); - let available_space: u64 = disks.list().iter().map(|d| d.available_space()).sum(); - let total_space: u64 = disks.list().iter().map(|d| d.total_space()).sum(); + let Ok(disks) = Disks::new_with_refreshed_list() else { return Ok(()) }; + let available_space: u64 = disks.iter().map(|d| d.available_space()).sum(); + let total_space: u64 = disks.iter().map(|d| d.total_space()).sum(); let used_space = total_space - available_space; log::info!( From a804f3a0d7dddf6f1da64d1b2b26385bd4f05081 Mon Sep 17 00:00:00 2001 From: Tess4552 Date: Wed, 11 Nov 2026 09:13:45 +0100 Subject: [PATCH 16/39] reflection: introduce reflect attribute as tool --- compiler/rustc_feature/src/unstable.rs | 2 ++ compiler/rustc_resolve/src/macros.rs | 6 ++++++ compiler/rustc_span/src/symbol.rs | 1 + tests/ui/feature-gates/feature-gate-type_info.rs | 4 ++++ tests/ui/feature-gates/feature-gate-type_info.stderr | 9 +++++++++ 5 files changed, 22 insertions(+) create mode 100644 tests/ui/feature-gates/feature-gate-type_info.rs create mode 100644 tests/ui/feature-gates/feature-gate-type_info.stderr diff --git a/compiler/rustc_feature/src/unstable.rs b/compiler/rustc_feature/src/unstable.rs index ed2bf64263c67..dd71bc9e1c057 100644 --- a/compiler/rustc_feature/src/unstable.rs +++ b/compiler/rustc_feature/src/unstable.rs @@ -767,6 +767,8 @@ declare_features! ( /// Allows creation of instances of a struct by moving fields that have /// not changed from prior instances of the same struct (RFC #2528) (unstable, type_changing_struct_update, "1.58.0", Some(86555)), + /// Allows using reflection features + (unstable, type_info, "1.94.0", Some(146922)), /// Allows using `_ = ` enum variants. (incomplete, unnamed_enum_variants, "1.98.0", Some(156628)), /// Allows using `unsafe<'a> &'a T` unsafe binder types. diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 28633ea2ce39c..b809911045341 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -139,6 +139,12 @@ pub(crate) fn registered_attr_tools(tcx: TyCtxt<'_>, (): ()) -> RegisteredTools }; // We implicitly add predefined tools, but it's not an error to register them explicitly. + + // FIXME this should instead be using tool attribute imports or something similar + if tcx.features().type_info() { + registered_tools.insert(Ident::with_dummy_span(sym::reflection_placeholder)); + } + registered_tools.extend(PREDEFINED_TOOLS.iter().cloned().map(Ident::with_dummy_span)); registered_tools } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 2170f610f0939..860a50dd27699 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1729,6 +1729,7 @@ symbols! { ref_unwind_safe_trait, reference, reflect, + reflection_placeholder, reg, reg16, reg32, diff --git a/tests/ui/feature-gates/feature-gate-type_info.rs b/tests/ui/feature-gates/feature-gate-type_info.rs new file mode 100644 index 0000000000000..001a797b16a16 --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-type_info.rs @@ -0,0 +1,4 @@ +#[reflection_placeholder::a] //~ ERROR cannot find module or crate `reflection_placeholder` in this scope [E0433] +struct A; + +fn main() {} diff --git a/tests/ui/feature-gates/feature-gate-type_info.stderr b/tests/ui/feature-gates/feature-gate-type_info.stderr new file mode 100644 index 0000000000000..ffbec352f775b --- /dev/null +++ b/tests/ui/feature-gates/feature-gate-type_info.stderr @@ -0,0 +1,9 @@ +error[E0433]: cannot find module or crate `reflection_placeholder` in this scope + --> $DIR/feature-gate-type_info.rs:1:3 + | +LL | #[reflection_placeholder::a] + | ^^^^^^^^^^^^^^^^^^^^^^ use of unresolved module or unlinked crate `reflection_placeholder` + +error: aborting due to 1 previous error + +For more information about this error, try `rustc --explain E0433`. From 8689b3e907e720ff11c3126c5cce59c883c4881f Mon Sep 17 00:00:00 2001 From: Tess4552 Date: Wed, 11 Nov 2026 09:13:57 +0100 Subject: [PATCH 17/39] reflection: reflect attributes from adts, fields, and variants --- Cargo.lock | 1 + compiler/rustc_const_eval/Cargo.toml | 1 + .../src/const_eval/machine.rs | 50 +++++++++++++- .../src/const_eval/type_info.rs | 40 ++++++++++- .../rustc_hir_analysis/src/check/intrinsic.rs | 22 ++++++ compiler/rustc_span/src/symbol.rs | 2 + library/core/src/intrinsics/reflection.rs | 17 +++++ library/core/src/mem/type_info.rs | 68 +++++++++++++++++++ library/coretests/tests/mem/type_info.rs | 38 +++++++++++ 9 files changed, 237 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6a677f5957794..91f5bf1efb5a3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3905,6 +3905,7 @@ dependencies = [ "rustc_data_structures", "rustc_errors", "rustc_hir", + "rustc_hir_pretty", "rustc_index", "rustc_infer", "rustc_lint_defs", diff --git a/compiler/rustc_const_eval/Cargo.toml b/compiler/rustc_const_eval/Cargo.toml index 8d14d86581a66..fd1e0c16ed1ab 100644 --- a/compiler/rustc_const_eval/Cargo.toml +++ b/compiler/rustc_const_eval/Cargo.toml @@ -13,6 +13,7 @@ rustc_attr_ir = { path = "../rustc_attr_ir" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_hir = { path = "../rustc_hir" } +rustc_hir_pretty = { path = "../rustc_hir_pretty" } rustc_index = { path = "../rustc_index" } rustc_infer = { path = "../rustc_infer" } rustc_lint_defs = { path = "../rustc_lint_defs" } diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index 39831f28118b0..2ad6ee2a88a43 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -4,8 +4,8 @@ use std::{fmt, mem}; use rustc_abi::{Align, FIRST_VARIANT, FieldIdx, Size, VariantIdx}; use rustc_ast::Mutability; -use rustc_attr_ir::find_attr; use rustc_attr_ir::lang_items::LangItem; +use rustc_attr_ir::{HasAttrs, find_attr}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{CRATE_HIR_ID, HirId}; @@ -796,6 +796,28 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { )?; } + sym::type_id_variant_reflected_attrs => { + let base = ecx.read_type_id(&args[0])?; + + if let ty::Adt(def, _) = base.kind() { + let variant_idx = ecx.read_target_usize(&args[1])? as usize; + if variant_idx >= def.variants().len() { + throw_ub!(BoundsCheckFailed { + len: def.variants().len() as u64, + index: variant_idx as u64 + }); + } + let variant_idx = VariantIdx::from_usize(variant_idx); + + ecx.write_reflect_attributes( + dest, + def.variant(variant_idx).def_id.get_attrs(&ecx.tcx), + )?; + } else { + span_bug!(ecx.cur_span(), "expected enum type, got {base}") + }; + } + sym::type_id_variant_non_exhaustive => { let base = ecx.read_type_id(&args[0])?; @@ -891,6 +913,32 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { ecx.write_type_id(field_ty, dest)?; } + sym::type_id_reflected_attrs => { + let ty = ecx.read_type_id(&args[0])?; + let attrs = match ty.kind() { + ty::Adt(def, args) + if let Some(FieldInfo { base, variant_idx, field_idx, .. }) = + def.field_representing_type_info(ecx.tcx(), *args) => + { + match base.kind() { + ty::Adt(base_def, _) => { + let field = &base_def.variants()[variant_idx].fields[field_idx]; + field.did.get_attrs(&ecx.tcx) + } + ty::Tuple(_) => &[], + _ => { + // only adts and tuples have fields + span_bug!(ecx.cur_span(), "expected adt or tuple type, got {ty}"); + } + } + } + ty::Adt(def, _) => def.did().get_attrs(&ecx.tcx), + _ => &[], + }; + + ecx.write_reflect_attributes(dest, attrs)?; + } + sym::type_id_generics => { let ty = ecx.read_type_id(&args[0])?; ecx.write_type_id_generics(dest, ty)?; diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index fc32787fa8703..50efefe8ca967 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -3,8 +3,11 @@ mod adt; use std::borrow::Cow; use rustc_abi::{ExternAbi, FieldIdx}; +use rustc_attr_ir::AttrItem; +use rustc_attr_ir::Attribute::Tool; use rustc_attr_ir::lang_items::LangItem; -use rustc_middle::ty::layout::TyAndLayout; +use rustc_hir::intravisit::HirTyCtxt; +use rustc_middle::ty::layout::{HasTyCtxt, TyAndLayout}; use rustc_middle::ty::{self, FnHeader, FnSigKind, FnSigTys, ScalarInt, Ty, TyCtxt}; use rustc_span::{Symbol, span_bug, sym}; @@ -346,4 +349,39 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { interp_ok(()) } + + pub(crate) fn write_reflect_attributes( + &mut self, + place: &impl Writeable<'tcx, CtfeProvenance>, + attrs: &'tcx [rustc_attr_ir::Attribute], + ) -> InterpResult<'tcx> { + let attrs: Vec<_> = attrs + .iter() + .filter_map(|attr| { + if let Tool(a_itm @ AttrItem { .. }) = attr + && a_itm.path.segments.first() == Some(&sym::reflection_placeholder) + { + Some(rustc_hir_pretty::attritem_to_string( + &(&self.tcx() as &dyn HirTyCtxt<'_>), + &a_itm, + )) + } else { + None + } + }) + .collect(); + + self.allocate_fill_and_write_slice_ptr(place, attrs.len() as _, |this, i, place| { + let attr = &attrs[i as usize]; + let ptr = this.allocate_bytes_dedup(attr.trim_end().as_bytes())?; + + this.write_immediate( + Immediate::ScalarPair( + Scalar::from_pointer(ptr, this), + Scalar::from_target_usize(attr.trim_end().len() as u64, this), + ), + &place, + ) + }) + } } diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 8b55734d90c8f..cbacbd138500c 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -181,10 +181,12 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::type_id_non_exhaustive | sym::type_id_points_mutably | sym::type_id_points_to + | sym::type_id_reflected_attrs | sym::type_id_size_of | sym::type_id_type_of | sym::type_id_variant_name | sym::type_id_variant_non_exhaustive + | sym::type_id_variant_reflected_attrs | sym::type_id_variants | sym::type_id_vtable | sym::type_name @@ -291,6 +293,16 @@ pub(crate) fn check_intrinsic_type( sym::type_name => (1, 0, vec![], Ty::new_static_str(tcx)), sym::type_id => (1, 0, vec![], type_id_ty()), + sym::type_id_reflected_attrs => ( + 0, + 0, + vec![type_id_ty()], + Ty::new_imm_ref( + tcx, + tcx.lifetimes.re_static, + Ty::new_slice(tcx, Ty::new_static_str(tcx)), + ), + ), sym::type_id_array_len => (0, 0, vec![type_id_ty()], tcx.types.usize), sym::type_id_element_ty => (0, 0, vec![type_id_ty()], Ty::new_option(tcx, type_id_ty())), sym::type_id_eq => (0, 0, vec![type_id_ty(), type_id_ty()], tcx.types.bool), @@ -313,6 +325,16 @@ pub(crate) fn check_intrinsic_type( sym::type_id_points_mutably => (0, 0, vec![type_id_ty()], tcx.types.bool), sym::type_id_points_to => (0, 0, vec![type_id_ty()], Ty::new_option(tcx, type_id_ty())), sym::type_id_variants => (0, 0, vec![type_id_ty()], tcx.types.usize), + sym::type_id_variant_reflected_attrs => ( + 0, + 0, + vec![type_id_ty(), tcx.types.usize], + Ty::new_imm_ref( + tcx, + tcx.lifetimes.re_static, + Ty::new_slice(tcx, Ty::new_static_str(tcx)), + ), + ), sym::type_id_variant_name => { (0, 0, vec![type_id_ty(), tcx.types.usize], Ty::new_static_str(tcx)) } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index 860a50dd27699..8f4f1b27c86f7 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2226,10 +2226,12 @@ symbols! { type_id_non_exhaustive, type_id_points_mutably, type_id_points_to, + type_id_reflected_attrs, type_id_size_of, type_id_type_of, type_id_variant_name, type_id_variant_non_exhaustive, + type_id_variant_reflected_attrs, type_id_variants, type_id_vtable, type_info, diff --git a/library/core/src/intrinsics/reflection.rs b/library/core/src/intrinsics/reflection.rs index 46830b05b14bc..0054cd32cdc03 100644 --- a/library/core/src/intrinsics/reflection.rs +++ b/library/core/src/intrinsics/reflection.rs @@ -108,6 +108,16 @@ pub fn type_id_variants(_id: crate::any::TypeId) -> usize; #[rustc_comptime] pub fn type_id_variant_name(_base: crate::any::TypeId, _variant_index: usize) -> &'static str; +/// Returns the reflection attributes given a the variant represented by the base `TypeId` and variant_idx. +/// +/// The more user-friendly version of this intrinsic is [`core::mem::type_info::VariantId::reflected_attrs`]. +#[rustc_intrinsic] +#[rustc_comptime] +pub fn type_id_variant_reflected_attrs( + _base: crate::any::TypeId, + _variant_index: usize, +) -> &'static [&'static str]; + /// Returns true when the variant represented by the base `TypeId` and variant_idx is non /// exhaustive. /// @@ -173,3 +183,10 @@ pub fn type_id_points_mutably(_id: crate::any::TypeId) -> bool; #[rustc_intrinsic] #[rustc_comptime] pub fn type_id_function_ptr(_type_id: crate::any::TypeId) -> Option; + +/// Returns the reflection attributes given a `TypeId` which represents a structure, enumeration, union or `FieldId`. +/// +/// The more user-friendly version of this intrinsic is [`core::any::TypeId::reflected_attrs`]. +#[rustc_intrinsic] +#[rustc_comptime] +pub fn type_id_reflected_attrs(_type_id: crate::any::TypeId) -> &'static [&'static str]; diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 71a9627c24f9c..5edca89d4c759 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -656,6 +656,27 @@ impl TypeId { pub fn function_ptr(self) -> Option { intrinsics::reflection::type_id_function_ptr(self) } + + /// Given given a `TypeId`, which represents a structure, enum or union returns a list of attributes. + /// Only the attributes of the tool `reflection_placeholder` are returned, all other attributes are excluded. + /// The attributes are in a string representation. + /// + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// #[reflection_placeholder::a(1, false)] + /// #[reflection_placeholder::foo=123] + /// struct A; + /// + /// assert_eq!(const { TypeId::of::().reflected_attrs() }, ["#[reflection_placeholder::a(1, false)]", "#[reflection_placeholder::foo = 123]"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn reflected_attrs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_reflected_attrs(self) + } } /// Variant representing type ID. Representing a variant of an enum. @@ -705,6 +726,30 @@ impl VariantId { pub fn non_exhaustive(self) -> bool { intrinsics::reflection::type_id_variant_non_exhaustive(self.base, self.variant) } + + /// Given given a `VariantId` returns a list of attributes. + /// Only the attributes of the tool `reflection_placeholder` are returned, all other attributes are excluded. + /// The attributes are in a string representation. + /// + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// enum A { + /// #[reflection_placeholder::a(1, false)] + /// #[reflection_placeholder::foo=123] + /// VarA, + /// VarB, + /// } + /// + /// assert_eq!(const { TypeId::of::().variant(0).reflected_attrs() }, &["#[reflection_placeholder::a(1, false)]", "#[reflection_placeholder::foo = 123]"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn reflected_attrs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_variant_reflected_attrs(self.base, self.variant) + } } /// Field representing type ID. Representing a field of a struct, tuple or enum variant. @@ -788,4 +833,27 @@ impl FieldId { pub fn offset(self) -> usize { intrinsics::field_representing_type_offset(self.frt_type_id) } + + /// Given given a `FieldId` returns a list of attributes. + /// Only the attributes of the tool `reflection_placeholder` are returned, all other attributes are excluded. + /// The attributes are in a string representation. + /// + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// struct A { + /// #[reflection_placeholder::a(1, false)] + /// #[reflection_placeholder::foo=123] + /// first: u8, + /// } + /// + /// assert_eq!(const { TypeId::of::().field(0, 0).reflected_attrs() }, &["#[reflection_placeholder::a(1, false)]", "#[reflection_placeholder::foo = 123]"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn reflected_attrs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_reflected_attrs(self.frt_type_id) + } } diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index 865b6a269afff..34128bc4d8d63 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -57,8 +57,12 @@ fn test_tuples() { #[test] fn test_structs() { const { + #[reflection_placeholder::TestStruct] struct TestStruct { + #[reflection_placeholder::first(1)] + #[reflection_placeholder::first(2)] first: u8, + #[reflection_placeholder::second] second: u16, reference: &'static u16, } @@ -66,14 +70,20 @@ fn test_structs() { let ty_id = TypeId::of::(); assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::TestStruct]"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 3); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 0).offset() == offset_of!(TestStruct, first)); assert!(ty_id.field(0, 0).name() == "first"); + assert!( + ty_id.field(0, 0).reflected_attrs() + == &["#[reflection_placeholder::first(1)]", "#[reflection_placeholder::first(2)]"] + ); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).offset() == offset_of!(TestStruct, second)); assert!(ty_id.field(0, 1).name() == "second"); + assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflection_placeholder::second]"]); assert!(ty_id.field(0, 2).type_id() == TypeId::of::<&u16>()); assert!(ty_id.field(0, 2).offset() == offset_of!(TestStruct, reference)); assert!(ty_id.field(0, 2).name() == "reference"); @@ -102,6 +112,7 @@ fn test_structs() { } const { + #[reflection_placeholder::a] struct Generics<'a, T, const C: u64> { a: &'a T, } @@ -109,6 +120,7 @@ fn test_structs() { let ty_id = TypeId::of::>(); assert!(ty_id.fields(0) == 1); assert!(ty_id.generics().len() == 3); + assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::a]"]); let Generic::Lifetime(_) = ty_id.generics()[0] else { panic!() }; let Generic::Type(GenericType { ty: generic_ty, .. }) = ty_id.generics()[1] else { @@ -123,8 +135,11 @@ fn test_structs() { #[test] fn test_unions() { const { + #[reflection_placeholder::a] union TestUnion { + #[reflection_placeholder::first] first: i16, + #[reflection_placeholder::second] second: u16, } @@ -132,13 +147,17 @@ fn test_unions() { assert!(ty_id.size() == Some(size_of::())); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 2); + assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::a]"]); assert!(ty_id.field(0, 0).name() == "first"); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); + assert!(ty_id.field(0, 0).reflected_attrs() == &["#[reflection_placeholder::first]"]); assert!(ty_id.field(0, 1).name() == "second"); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); + assert!(ty_id.field(0, 1).reflected_attrs() == &["#[reflection_placeholder::second]"]); } const { + #[reflection_placeholder::a] union Generics<'a, T: Copy, const C: u64> { a: T, z: &'a (), @@ -146,6 +165,7 @@ fn test_unions() { let ty_id = TypeId::of::>(); assert!(ty_id.fields(0) == 2); + assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::a]"]); assert!(ty_id.field(0, 1).offset() == offset_of!(Generics<'static, i32, 1_u64>, a)); assert!(ty_id.field(0, 1).offset() == offset_of!(Generics<'static, i32, 1_u64>, z)); @@ -163,12 +183,17 @@ fn test_unions() { #[test] fn test_enums() { const { + #[reflection_placeholder::a] enum E { + #[reflection_placeholder::some] Some(u32), + #[reflection_placeholder::none] None, + #[reflection_placeholder::foomp] #[non_exhaustive] Foomp { a: (), + #[reflection_placeholder::b] b: &'static str, }, } @@ -176,23 +201,28 @@ fn test_enums() { let ty_id = TypeId::of::(); assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.reflected_attrs() == &["#[reflection_placeholder::a]"]); assert!(ty_id.variants() == 3); assert!(ty_id.variant(0).name() == "Some"); + assert!(ty_id.variant(0).reflected_attrs() == &["#[reflection_placeholder::some]"]); assert!(!ty_id.variant(0).non_exhaustive()); assert!(ty_id.fields(0) == 1); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.variant(1).name() == "None"); + assert!(ty_id.variant(1).reflected_attrs() == &["#[reflection_placeholder::none]"]); assert!(!ty_id.variant(1).non_exhaustive()); assert!(ty_id.fields(1) == 0); assert!(ty_id.variant(2).name() == "Foomp"); + assert!(ty_id.variant(2).reflected_attrs() == &["#[reflection_placeholder::foomp]"]); assert!(ty_id.variant(2).non_exhaustive()); assert!(ty_id.fields(2) == 2); assert!(ty_id.field(2, 0).type_id() == TypeId::of::<()>()); assert!(ty_id.field(2, 1).type_id() == TypeId::of::<&str>()); assert!(ty_id.field(2, 1).name() == "b"); + assert!(ty_id.field(2, 1).reflected_attrs() == &["#[reflection_placeholder::b]"]); assert!(ty_id.generics().is_empty()); } @@ -224,45 +254,53 @@ fn test_primitives() { let Type { kind: Bool, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Char, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Float, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Str(_ty), .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == None); + assert!(ty_id.reflected_attrs() == &[""; 0]); assert!(ty_id.variants() == 1); } } From 336b4e720e11132636784a5082554b4af3f6d038 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:49:24 +0100 Subject: [PATCH 18/39] Remove orphaned RustcShouldNotBeCalledOnConstItems --- compiler/rustc_attr_ir/src/data_structures.rs | 3 --- compiler/rustc_attr_ir/src/encode_cross_crate.rs | 2 -- compiler/rustc_passes/src/check_attr.rs | 1 - compiler/rustc_span/src/symbol.rs | 1 - 4 files changed, 7 deletions(-) diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index e32a31ea7e458..3f0983374122d 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -1466,9 +1466,6 @@ pub enum AttributeKind { element_count: Option, }, - /// Represents `#[rustc_should_not_be_called_on_const_items]` - RustcShouldNotBeCalledOnConstItems, - /// Represents `#[rustc_show_spans]` RustcShowSpans(ThinVec), diff --git a/compiler/rustc_attr_ir/src/encode_cross_crate.rs b/compiler/rustc_attr_ir/src/encode_cross_crate.rs index cabef51f754d1..d8cb1d2cdf360 100644 --- a/compiler/rustc_attr_ir/src/encode_cross_crate.rs +++ b/compiler/rustc_attr_ir/src/encode_cross_crate.rs @@ -189,7 +189,6 @@ impl AttributeKind { RustcReallocator => No, RustcRegions => No, RustcScalableVector { .. } => Yes, - RustcShouldNotBeCalledOnConstItems => Yes, RustcShowSpans(_) => No, RustcSimdMonomorphizeLaneLimit(..) => Yes, // Affects layout computation, which needs to work cross-crate RustcSkipDuringMethodDispatch { .. } => No, @@ -408,7 +407,6 @@ impl AttributeKind { RustcReallocator => false, RustcRegions => false, RustcScalableVector { .. } => false, - RustcShouldNotBeCalledOnConstItems => false, RustcShowSpans(_) => false, RustcSimdMonomorphizeLaneLimit(..) => false, RustcSkipDuringMethodDispatch { .. } => false, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index a2a9dde01dc71..b6511ce0528ee 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -378,7 +378,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { AttributeKind::RustcReallocator => (), AttributeKind::RustcRegions => (), AttributeKind::RustcScalableVector { .. } => (), - AttributeKind::RustcShouldNotBeCalledOnConstItems => (), AttributeKind::RustcShowSpans(_) => (), AttributeKind::RustcSimdMonomorphizeLaneLimit(..) => (), AttributeKind::RustcSkipDuringMethodDispatch { .. } => (), diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index ea360c953afe8..369ceb7b64bd9 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -1909,7 +1909,6 @@ symbols! { rustc_reallocator, rustc_regions, rustc_scalable_vector, - rustc_should_not_be_called_on_const_items, rustc_show_spans, rustc_simd_monomorphize_lane_limit, rustc_skip_during_method_dispatch, From 466e6409ec7251f6d334dc7d23b0ea78fecaca28 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:50:39 +0100 Subject: [PATCH 19/39] Fix typo --- compiler/rustc_attr_parsing/src/attributes/repr.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/repr.rs b/compiler/rustc_attr_parsing/src/attributes/repr.rs index bc4f9d20545fc..d29bd25362b68 100644 --- a/compiler/rustc_attr_parsing/src/attributes/repr.rs +++ b/compiler/rustc_attr_parsing/src/attributes/repr.rs @@ -162,7 +162,7 @@ fn parse_repr(cx: &mut AcceptContext<'_, '_>, param: &MetaItemParser) -> Option< &AllowedTargets::AllowList(&[ Allow(Target::Struct), Allow(Target::Enum), - Allow(Target::Union), // Feature gated in `rustc_attr_ir_analysis` + Allow(Target::Union), // Feature gated in `rustc_hir_analysis` Warn(Target::MacroCall), ]), ); From 892f046a4b1af8660f2e95a09d48567295ee8a7a Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 12 Nov 2026 14:55:14 +0100 Subject: [PATCH 20/39] Correct `RustcPubTransparent` docs --- compiler/rustc_attr_ir/src/data_structures.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index 3f0983374122d..7f4b83b0ea022 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -1450,7 +1450,8 @@ pub enum AttributeKind { /// Represents `#[rustc_proc_macro_decls]` RustcProcMacroDecls, - /// Represents `#[rustc_pub_transparent]` (used by the `repr_transparent_external_private_fields` lint). + /// Represents `#[rustc_pub_transparent]` (used to mark a type as "publicly" transparent, for + /// semver and documentation purposes). RustcPubTransparent(Span), /// Represents `#[rustc_reallocator]` From 34d133891859c941be24648fb42c7fe404a6dd50 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:20:04 +0100 Subject: [PATCH 21/39] Remove documentation from `BUILTIN_ATTRIBUTES` --- compiler/rustc_attr_ir/src/data_structures.rs | 58 +++++-- compiler/rustc_feature/src/builtin_attrs.rs | 144 +----------------- 2 files changed, 47 insertions(+), 155 deletions(-) diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index 7f4b83b0ea022..e5c42f325118d 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -861,6 +861,8 @@ pub enum AttributeKind { ConstContinue(Span), /// Represents `#[coroutine]`. + /// + /// This attribute can be applied to closures to make them coroutines instead. Coroutine, /// Represents `#[coverage(..)]`. @@ -1130,7 +1132,10 @@ pub enum AttributeKind { limit: Limit, }, - /// Represents `#[pin_v2]` + /// Represents `#[pin_v2]`. + /// + /// The `#[pin_v2]` attribute is part of the `pin_ergonomics` experiment that allows + /// structurally pinning, tracked in . PinV2(Span), /// Represents `#[prelude_import]` @@ -1177,8 +1182,9 @@ pub enum AttributeKind { kind: RustcAbiAttrKind, }, - /// Represents `#[align(N)]`. - // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity + /// Represents `#[rustc_align(N)]`. + /// + /// FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity RustcAlign { align: Align, span: Span, @@ -1261,7 +1267,9 @@ pub enum AttributeKind { /// Represents `#[rustc_const_stable_indirect]`. RustcConstStableIndirect, - /// Represents `#[rustc_conversion_suggestion]` + /// Represents `#[rustc_conversion_suggestion]`. + /// + /// Enumerates "identity-like" conversion methods to suggest on type mismatch. RustcConversionSuggestion, /// Represents `#[rustc_deallocator]` @@ -1280,7 +1288,10 @@ pub enum AttributeKind { /// Represents `#[rustc_diagnostic_item]` RustcDiagnosticItem(Symbol), - /// Represents `#[rustc_do_not_const_check]` + /// Represents `#[rustc_do_not_const_check]`. + /// + /// Functions with this attribute will not have their body const-checked. It will always get + /// replaced during CTFE via `hook_special_const_fn`. RustcDoNotConstCheck, /// Represents `#[rustc_doc_primitive = ...]` @@ -1366,18 +1377,30 @@ pub enum AttributeKind { attr_span: Span, }, - /// Represents `#[rustc_lint_opt_deny_field_access]` + /// Represents `#[rustc_lint_opt_deny_field_access]`. + /// + /// Used by the `rustc::bad_opt_access` lint on fields + /// types (as well as any others in future). RustcLintOptDenyFieldAccess { lint_message: Symbol, }, - /// Represents `#[rustc_lint_opt_ty]` + /// Represents `#[rustc_lint_opt_ty]`. + /// + /// Used by the `rustc::bad_opt_access` lint to identify `DebuggingOptions` and `CodegenOptions` + /// types (as well as any others in future) RustcLintOptTy, - /// Represents `#[rustc_lint_query_instability]` + /// Represents `#[rustc_lint_query_instability]`. + /// + /// Used by the `rustc::potential_query_instability` lint to warn methods which + /// might not be stable during incremental compilation. RustcLintQueryInstability, - /// Represents `#[rustc_lint_untracked_query_information]` + /// Represents `#[rustc_lint_untracked_query_information]`. + /// + /// Used by the `rustc::untracked_query_information` lint to warn methods which + /// might not be stable during incremental compilation. RustcLintUntrackedQueryInformation, /// Represents `#[rustc_macro_transparency]`. @@ -1441,7 +1464,9 @@ pub enum AttributeKind { /// Represents `#[rustc_pass_by_value]` (used by the `rustc_pass_by_value` lint). RustcPassByValue, - /// Represents `#[rustc_pass_indirectly_in_non_rustic_abis]` + /// Represents `#[rustc_pass_indirectly_in_non_rustic_abis]`, + /// + /// See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details. RustcPassIndirectlyInNonRusticAbis(Span), /// Represents `#[rustc_preserve_ub_checks]` @@ -1514,7 +1539,11 @@ pub enum AttributeKind { reason: Option, }, - /// Represents `#[rustc_splat]` + /// Represents `#[rustc_splat]`. + /// + /// The `#[rustc_splat]` attribute is part of the `splat` experiment that improves the + /// ergonomics of function overloading, tracked in + /// . Splat(Span), /// Represents `#[stable]`, `#[unstable]` and `#[rustc_allowed_through_unstable_modules]`. @@ -1550,8 +1579,11 @@ pub enum AttributeKind { // FIXME(#134963): Temporarily prefixed with `rustc_` to prevent potential name resolution ambiguities. UncheckedTypeAlias, - /// Represents `#[rustc_unroll]` - // FIXME(#159429): temporarily renamed from `#[unroll]` to mitigate nameres ambiguity + /// Represents `#[rustc_unroll]`. + /// + /// Tracked in . + /// + /// FIXME(#159429): temporarily renamed from `#[unroll]` to mitigate nameres ambiguity. Unroll(UnrollAttr), /// Represents `#[unstable_feature_bound]`. diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 52dba353eb24b..70ba3e56411db 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -81,28 +81,17 @@ pub enum AttributeStability { /// Attributes that have a special meaning to rustc or rustdoc. #[rustfmt::skip] pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ - // ========================================================================== - // Stable attributes: - // ========================================================================== - - // Conditional compilation: sym::cfg, sym::cfg_attr, - - // Testing: sym::ignore, sym::should_panic, - - // Macros: sym::automatically_derived, sym::macro_use, - sym::macro_escape, // Deprecated synonym for `macro_use`. + sym::macro_escape, sym::macro_export, sym::proc_macro, sym::proc_macro_derive, sym::proc_macro_attribute, - - // Lints: sym::warn, sym::allow, sym::expect, @@ -111,17 +100,12 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ sym::must_use, sym::must_not_suspend, sym::deprecated, - - // Crate properties: sym::crate_name, sym::crate_type, - - // ABI, linking, symbols, and FFI sym::link, sym::link_name, sym::no_link, sym::repr, - // FIXME(#82232, #143834): temporarily renamed to mitigate `#[align]` nameres ambiguity sym::rustc_align, sym::rustc_align_static, sym::export_name, @@ -130,28 +114,17 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ sym::used, sym::link_ordinal, sym::naked, - // See `TyAndLayout::pass_indirectly_in_non_rustic_abis` for details. sym::rustc_pass_indirectly_in_non_rustic_abis, - - // Limits: sym::recursion_limit, sym::type_length_limit, sym::move_size_limit, - - // Entry point: sym::no_main, - - // Modules, prelude, and resolution: sym::path, sym::no_std, sym::no_implicit_prelude, sym::non_exhaustive, - - // Runtime sym::windows_subsystem, - sym::panic_handler, // RFC 2070 - - // Code generation: + sym::panic_handler, sym::inline, sym::cold, sym::no_builtins, @@ -162,87 +135,31 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ sym::sanitize, sym::coverage, sym::optimize, - sym::doc, - - // Debugging sym::debugger_visualizer, sym::collapse_debuginfo, - - // ========================================================================== - // Unstable attributes: - // ========================================================================== - - // Linking: sym::export_stable, - - // Testing: sym::test_runner, - sym::reexport_test_harness_main, - - // RFC #1268 sym::marker, sym::thread_local, sym::no_core, - sym::ffi_pure, sym::ffi_const, sym::register_attribute_tool, sym::register_lint_tool, sym::register_tool, - // `#[cfi_encoding = ""]` sym::cfi_encoding, - - // `#[coroutine]` attribute to be applied to closures to make them coroutines instead sym::coroutine, - - // RFC 3543 - // `#[patchable_function_entry(prefix_nops = m, entry_nops = n)]` sym::patchable_function_entry, - - // The `#[loop_match]` and `#[const_continue]` attributes are part of the - // lang experiment for RFC 3720 tracked in: - // - // - https://github.com/rust-lang/rust/issues/132306 sym::const_continue, sym::loop_match, - - // The `#[pin_v2]` attribute is part of the `pin_ergonomics` experiment - // that allows structurally pinning, tracked in: - // - // - https://github.com/rust-lang/rust/issues/130494 sym::pin_v2, - - // The `#[rustc_splat]` attribute is part of the `splat` experiment - // that improves the ergonomics of function overloading, tracked in: - // - // - https://github.com/rust-lang/rust/issues/153629 sym::rustc_splat, - - // The `#[rustc_unroll]` attribute. - // - // - https://github.com/rust-lang/rust/pull/156816 - // - // FIXME(#159429): temporarily renamed to mitigate `#[unroll]` nameres ambiguity sym::rustc_unroll, - - // `#[instrument_fn = "on|off"]` to insert or inhibit instrumentation function - // calls inside a function, usually around the prologue. - // - // - https://github.com/rust-lang/rust/issues/157081 sym::instrument_fn, - - // The attribute is part of feature `checked_type_aliases`. Its name is but a placeholder. - // FIXME(#134963): Temporarily prefixed with `rustc_` to prevent potential name resolution ambiguities. sym::rustc_unchecked_type_alias, - - // ========================================================================== - // Internal attributes: Stability, deprecation, and unsafe: - // ========================================================================== - sym::feature, - // DuplicatesOk since it has its own validation sym::stable, sym::unstable, sym::unstable_feature_bound, @@ -256,18 +173,8 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ sym::rustc_allowed_through_unstable_modules, sym::rustc_deprecated_safe_2024, sym::rustc_pub_transparent, - - // ========================================================================== - // Internal attributes: Type system related: - // ========================================================================== - sym::fundamental, sym::may_dangle, - - // ========================================================================== - // Internal attributes: Runtime related: - // ========================================================================== - sym::rustc_allocator, sym::rustc_nounwind, sym::rustc_reallocator, @@ -280,75 +187,34 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ sym::needs_panic_runtime, sym::compiler_builtins, sym::profiler_runtime, - - // ========================================================================== - // Internal attributes, Linkage: - // ========================================================================== - sym::linkage, sym::rustc_std_internal_symbol, sym::rustc_objc_class, sym::rustc_objc_selector, - - // ========================================================================== - // Internal attributes, Macro related: - // ========================================================================== - sym::rustc_builtin_macro, sym::rustc_proc_macro_decls, sym::rustc_macro_transparency, sym::rustc_autodiff, sym::rustc_offload_kernel, - - // ========================================================================== - // Internal attributes, Diagnostics related: - // ========================================================================== - sym::rustc_on_unimplemented, sym::rustc_confusables, - // Enumerates "identity-like" conversion methods to suggest on type mismatch. sym::rustc_conversion_suggestion, - // Prevents field reads in the marked trait or method to be considered - // during dead code analysis. sym::rustc_trivial_field_reads, - // Used by the `rustc::potential_query_instability` lint to warn methods which - // might not be stable during incremental compilation. sym::rustc_lint_query_instability, - // Used by the `rustc::untracked_query_information` lint to warn methods which - // might not be stable during incremental compilation. sym::rustc_lint_untracked_query_information, - // Used by the `rustc::bad_opt_access` lint to identify `DebuggingOptions` and `CodegenOptions` - // types (as well as any others in future). sym::rustc_lint_opt_ty, - // Used by the `rustc::bad_opt_access` lint on fields - // types (as well as any others in future). sym::rustc_lint_opt_deny_field_access, sym::rustc_diagnostic_opaque, sym::rustc_assert_variance, - - // ========================================================================== - // Internal attributes, Const related: - // ========================================================================== - sym::rustc_always_gca, sym::rustc_promotable, sym::rustc_legacy_const_generics, - // Do not const-check this function's body. It will always get replaced during CTFE via `hook_special_const_fn`. sym::rustc_do_not_const_check, sym::rustc_const_stable_indirect, sym::rustc_intrinsic_const_stable_indirect, sym::rustc_allow_const_fn_unstable, - - // ========================================================================== - // Internal attributes, Layout related: - // ========================================================================== - sym::rustc_simd_monomorphize_lane_limit, sym::rustc_nonnull_optimization_guaranteed, - - // ========================================================================== - // Internal attributes, Misc: - // ========================================================================== sym::lang, sym::rustc_pass_by_value, sym::rustc_no_implicit_autorefs, @@ -362,7 +228,6 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ sym::rustc_has_incoherent_inherent_impls, sym::rustc_non_const_trait_method, sym::rustc_panics_when_zero, - sym::rustc_canonical_symbol, sym::rustc_diagnostic_item, sym::prelude_import, @@ -381,11 +246,6 @@ pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ sym::rustc_scalable_vector, sym::rustc_must_match_exhaustively, sym::rustc_no_writable, - - // ========================================================================== - // Internal attributes, Testing: - // ========================================================================== - sym::rustc_show_spans, sym::rustc_effective_visibility, sym::rustc_dump_inferred_outlives, From 04b5048dc24a0817435a3a3822d42459992ed6f8 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:27:55 +0100 Subject: [PATCH 22/39] Sort `BUILTIN_ATTRIBUTES` --- compiler/rustc_feature/src/builtin_attrs.rs | 335 ++++++++++---------- 1 file changed, 168 insertions(+), 167 deletions(-) diff --git a/compiler/rustc_feature/src/builtin_attrs.rs b/compiler/rustc_feature/src/builtin_attrs.rs index 70ba3e56411db..c431e4aa2ba9b 100644 --- a/compiler/rustc_feature/src/builtin_attrs.rs +++ b/compiler/rustc_feature/src/builtin_attrs.rs @@ -78,208 +78,209 @@ pub enum AttributeStability { Stable, } -/// Attributes that have a special meaning to rustc or rustdoc. -#[rustfmt::skip] +/// Enumerates all built-in attributes. pub static BUILTIN_ATTRIBUTES: &[Symbol] = &[ + // tidy-alphabetical-start + sym::allow, + sym::allow_internal_unsafe, + sym::allow_internal_unstable, + sym::automatically_derived, sym::cfg, sym::cfg_attr, - sym::ignore, - sym::should_panic, - sym::automatically_derived, - sym::macro_use, - sym::macro_escape, - sym::macro_export, - sym::proc_macro, - sym::proc_macro_derive, - sym::proc_macro_attribute, - sym::warn, - sym::allow, - sym::expect, - sym::forbid, - sym::deny, - sym::must_use, - sym::must_not_suspend, - sym::deprecated, + sym::cfi_encoding, + sym::cold, + sym::collapse_debuginfo, + sym::compiler_builtins, + sym::const_continue, + sym::coroutine, + sym::coverage, sym::crate_name, sym::crate_type, + sym::custom_mir, + sym::debugger_visualizer, + sym::default_lib_allocator, + sym::deny, + sym::deprecated, + sym::doc, + sym::expect, + sym::export_name, + sym::export_stable, + sym::feature, + sym::ffi_const, + sym::ffi_pure, + sym::forbid, + sym::force_target_feature, + sym::fundamental, + sym::ignore, + sym::inline, + sym::instruction_set, + sym::instrument_fn, + sym::lang, sym::link, sym::link_name, - sym::no_link, - sym::repr, - sym::rustc_align, - sym::rustc_align_static, - sym::export_name, - sym::link_section, - sym::no_mangle, - sym::used, sym::link_ordinal, - sym::naked, - sym::rustc_pass_indirectly_in_non_rustic_abis, - sym::recursion_limit, - sym::type_length_limit, + sym::link_section, + sym::linkage, + sym::loop_match, + sym::macro_escape, + sym::macro_export, + sym::macro_use, + sym::marker, + sym::may_dangle, sym::move_size_limit, + sym::must_not_suspend, + sym::must_use, + sym::naked, + sym::needs_allocator, + sym::needs_panic_runtime, + sym::no_builtins, + sym::no_core, + sym::no_implicit_prelude, + sym::no_link, sym::no_main, - sym::path, + sym::no_mangle, sym::no_std, - sym::no_implicit_prelude, sym::non_exhaustive, - sym::windows_subsystem, - sym::panic_handler, - sym::inline, - sym::cold, - sym::no_builtins, - sym::target_feature, - sym::track_caller, - sym::instruction_set, - sym::force_target_feature, - sym::sanitize, - sym::coverage, sym::optimize, - sym::doc, - sym::debugger_visualizer, - sym::collapse_debuginfo, - sym::export_stable, - sym::test_runner, + sym::panic_handler, + sym::panic_runtime, + sym::patchable_function_entry, + sym::path, + sym::pattern_complexity_limit, + sym::pin_v2, + sym::prelude_import, + sym::proc_macro, + sym::proc_macro_attribute, + sym::proc_macro_derive, + sym::profiler_runtime, + sym::recursion_limit, sym::reexport_test_harness_main, - sym::marker, - sym::thread_local, - sym::no_core, - sym::ffi_pure, - sym::ffi_const, sym::register_attribute_tool, sym::register_lint_tool, sym::register_tool, - sym::cfi_encoding, - sym::coroutine, - sym::patchable_function_entry, - sym::const_continue, - sym::loop_match, - sym::pin_v2, - sym::rustc_splat, - sym::rustc_unroll, - sym::instrument_fn, - sym::rustc_unchecked_type_alias, - sym::feature, - sym::stable, - sym::unstable, - sym::unstable_feature_bound, - sym::unstable_removed, - sym::rustc_const_unstable, - sym::rustc_const_stable, - sym::rustc_default_body_unstable, - sym::allow_internal_unstable, - sym::allow_internal_unsafe, - sym::rustc_eii_foreign_item, - sym::rustc_allowed_through_unstable_modules, - sym::rustc_deprecated_safe_2024, - sym::rustc_pub_transparent, - sym::fundamental, - sym::may_dangle, + sym::repr, + sym::rustc_abi, + sym::rustc_align, + sym::rustc_align_static, sym::rustc_allocator, - sym::rustc_nounwind, - sym::rustc_reallocator, - sym::rustc_deallocator, sym::rustc_allocator_zeroed, sym::rustc_allocator_zeroed_variant, - sym::default_lib_allocator, - sym::needs_allocator, - sym::panic_runtime, - sym::needs_panic_runtime, - sym::compiler_builtins, - sym::profiler_runtime, - sym::linkage, - sym::rustc_std_internal_symbol, - sym::rustc_objc_class, - sym::rustc_objc_selector, - sym::rustc_builtin_macro, - sym::rustc_proc_macro_decls, - sym::rustc_macro_transparency, - sym::rustc_autodiff, - sym::rustc_offload_kernel, - sym::rustc_on_unimplemented, - sym::rustc_confusables, - sym::rustc_conversion_suggestion, - sym::rustc_trivial_field_reads, - sym::rustc_lint_query_instability, - sym::rustc_lint_untracked_query_information, - sym::rustc_lint_opt_ty, - sym::rustc_lint_opt_deny_field_access, - sym::rustc_diagnostic_opaque, - sym::rustc_assert_variance, - sym::rustc_always_gca, - sym::rustc_promotable, - sym::rustc_legacy_const_generics, - sym::rustc_do_not_const_check, - sym::rustc_const_stable_indirect, - sym::rustc_intrinsic_const_stable_indirect, sym::rustc_allow_const_fn_unstable, - sym::rustc_simd_monomorphize_lane_limit, - sym::rustc_nonnull_optimization_guaranteed, - sym::lang, - sym::rustc_pass_by_value, - sym::rustc_no_implicit_autorefs, + sym::rustc_allow_incoherent_impl, + sym::rustc_allow_lifetime_dependent_specialization, + sym::rustc_allowed_through_unstable_modules, + sym::rustc_always_gca, + sym::rustc_assert_variance, + sym::rustc_autodiff, + sym::rustc_builtin_macro, + sym::rustc_canonical_symbol, + sym::rustc_capture_analysis, + sym::rustc_clean, sym::rustc_coherence_is_core, sym::rustc_coinductive, sym::rustc_comptime, - sym::rustc_allow_incoherent_impl, - sym::rustc_preserve_ub_checks, + sym::rustc_confusables, + sym::rustc_const_stable, + sym::rustc_const_stable_indirect, + sym::rustc_const_unstable, + sym::rustc_conversion_suggestion, + sym::rustc_deallocator, + sym::rustc_default_body_unstable, + sym::rustc_delayed_bug_from_inside_query, sym::rustc_deny_explicit_impl, + sym::rustc_deprecated_safe_2024, + sym::rustc_diagnostic_item, + sym::rustc_diagnostic_opaque, + sym::rustc_do_not_const_check, + sym::rustc_doc_primitive, + sym::rustc_dummy, + sym::rustc_dump_clauses, + sym::rustc_dump_def_parents, + sym::rustc_dump_def_path, + sym::rustc_dump_generics, + sym::rustc_dump_hidden_type_of_opaques, + sym::rustc_dump_inferred_outlives, + sym::rustc_dump_item_bounds, + sym::rustc_dump_layout, + sym::rustc_dump_object_lifetime_defaults, + sym::rustc_dump_symbol_name, + sym::rustc_dump_user_args, + sym::rustc_dump_variances, + sym::rustc_dump_variances_of_opaques, + sym::rustc_dump_vtable, sym::rustc_dyn_incompatible_trait, + sym::rustc_effective_visibility, + sym::rustc_eii_foreign_item, + sym::rustc_evaluate_where_clauses, + sym::rustc_expected_cgu_reuse, + sym::rustc_force_inline, sym::rustc_has_incoherent_inherent_impls, - sym::rustc_non_const_trait_method, - sym::rustc_panics_when_zero, - sym::rustc_canonical_symbol, - sym::rustc_diagnostic_item, - sym::prelude_import, - sym::rustc_paren_sugar, + sym::rustc_if_this_changed, sym::rustc_inherit_overflow_checks, - sym::rustc_test_marker, - sym::rustc_allow_lifetime_dependent_specialization, - sym::rustc_specialization_trait, + sym::rustc_insignificant_dtor, + sym::rustc_intrinsic, + sym::rustc_intrinsic_const_stable_indirect, + sym::rustc_legacy_const_generics, + sym::rustc_lint_opt_deny_field_access, + sym::rustc_lint_opt_ty, + sym::rustc_lint_query_instability, + sym::rustc_lint_untracked_query_information, + sym::rustc_macro_transparency, sym::rustc_main, - sym::rustc_skip_during_method_dispatch, + sym::rustc_mir, sym::rustc_must_implement_one_of, - sym::rustc_doc_primitive, - sym::rustc_intrinsic, - sym::rustc_no_mir_inline, - sym::rustc_force_inline, - sym::rustc_scalable_vector, sym::rustc_must_match_exhaustively, + sym::rustc_no_implicit_autorefs, + sym::rustc_no_implicit_bounds, + sym::rustc_no_mir_inline, sym::rustc_no_writable, + sym::rustc_non_const_trait_method, + sym::rustc_nonnull_optimization_guaranteed, + sym::rustc_nounwind, + sym::rustc_objc_class, + sym::rustc_objc_selector, + sym::rustc_offload_kernel, + sym::rustc_on_unimplemented, + sym::rustc_panics_when_zero, + sym::rustc_paren_sugar, + sym::rustc_partition_codegened, + sym::rustc_partition_reused, + sym::rustc_pass_by_value, + sym::rustc_pass_indirectly_in_non_rustic_abis, + sym::rustc_preserve_ub_checks, + sym::rustc_proc_macro_decls, + sym::rustc_promotable, + sym::rustc_pub_transparent, + sym::rustc_reallocator, + sym::rustc_regions, + sym::rustc_scalable_vector, sym::rustc_show_spans, - sym::rustc_effective_visibility, - sym::rustc_dump_inferred_outlives, - sym::rustc_capture_analysis, - sym::rustc_insignificant_dtor, - sym::rustc_no_implicit_bounds, + sym::rustc_simd_monomorphize_lane_limit, + sym::rustc_skip_during_method_dispatch, + sym::rustc_specialization_trait, + sym::rustc_splat, + sym::rustc_std_internal_symbol, sym::rustc_strict_coherence, - sym::rustc_dump_variances, - sym::rustc_dump_variances_of_opaques, - sym::rustc_dump_generics, - sym::rustc_dump_hidden_type_of_opaques, - sym::rustc_dump_layout, - sym::rustc_abi, - sym::rustc_regions, - sym::rustc_delayed_bug_from_inside_query, - sym::rustc_dump_user_args, - sym::rustc_evaluate_where_clauses, - sym::rustc_if_this_changed, + sym::rustc_test_marker, sym::rustc_then_this_would_need, - sym::rustc_clean, - sym::rustc_partition_reused, - sym::rustc_partition_codegened, - sym::rustc_expected_cgu_reuse, - sym::rustc_dump_symbol_name, - sym::rustc_dump_def_path, - sym::rustc_mir, - sym::custom_mir, - sym::rustc_dump_item_bounds, - sym::rustc_dump_clauses, - sym::rustc_dump_def_parents, - sym::rustc_dump_object_lifetime_defaults, - sym::rustc_dump_vtable, - sym::rustc_dummy, - sym::pattern_complexity_limit, + sym::rustc_trivial_field_reads, + sym::rustc_unchecked_type_alias, + sym::rustc_unroll, + sym::sanitize, + sym::should_panic, + sym::stable, + sym::target_feature, + sym::test_runner, + sym::thread_local, + sym::track_caller, + sym::type_length_limit, + sym::unstable, + sym::unstable_feature_bound, + sym::unstable_removed, + sym::used, + sym::warn, + sym::windows_subsystem, + // tidy-alphabetical-end ]; pub fn is_builtin_attr_name(name: Symbol) -> bool { From e8a2dfd94971e6ff55087092eba03eb531dbcaff Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:30:33 +0100 Subject: [PATCH 23/39] Fix `MustNotSupend` typo --- compiler/rustc_attr_ir/src/data_structures.rs | 2 +- compiler/rustc_attr_ir/src/encode_cross_crate.rs | 4 ++-- .../rustc_attr_parsing/src/attributes/must_not_suspend.rs | 2 +- compiler/rustc_mir_transform/src/coroutine/layout.rs | 6 +++--- compiler/rustc_mir_transform/src/diagnostics.rs | 4 ++-- compiler/rustc_passes/src/check_attr.rs | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_attr_ir/src/data_structures.rs b/compiler/rustc_attr_ir/src/data_structures.rs index e5c42f325118d..b1b0bebb8a9a5 100644 --- a/compiler/rustc_attr_ir/src/data_structures.rs +++ b/compiler/rustc_attr_ir/src/data_structures.rs @@ -1026,7 +1026,7 @@ pub enum AttributeKind { }, /// Represents `#[must_not_suspend]` - MustNotSupend { + MustNotSuspend { reason: Option, }, diff --git a/compiler/rustc_attr_ir/src/encode_cross_crate.rs b/compiler/rustc_attr_ir/src/encode_cross_crate.rs index d8cb1d2cdf360..4fab9e54cf02c 100644 --- a/compiler/rustc_attr_ir/src/encode_cross_crate.rs +++ b/compiler/rustc_attr_ir/src/encode_cross_crate.rs @@ -69,7 +69,7 @@ impl AttributeKind { Marker => No, MayDangle(..) => No, MoveSizeLimit { .. } => No, - MustNotSupend { .. } => Yes, + MustNotSuspend { .. } => Yes, MustUse { .. } => Yes, Naked(..) => No, NeedsAllocator => No, @@ -287,7 +287,7 @@ impl AttributeKind { Marker => false, MayDangle(..) => false, MoveSizeLimit { .. } => false, - MustNotSupend { .. } => false, + MustNotSuspend { .. } => false, MustUse { .. } => false, Naked(..) => false, NeedsAllocator => false, diff --git a/compiler/rustc_attr_parsing/src/attributes/must_not_suspend.rs b/compiler/rustc_attr_parsing/src/attributes/must_not_suspend.rs index c7c302dd9ee2d..00e89640bf48e 100644 --- a/compiler/rustc_attr_parsing/src/attributes/must_not_suspend.rs +++ b/compiler/rustc_attr_parsing/src/attributes/must_not_suspend.rs @@ -25,6 +25,6 @@ impl SingleAttributeParser for MustNotSuspendParser { } }; - Some(AttributeKind::MustNotSupend { reason }) + Some(AttributeKind::MustNotSuspend { reason }) } } diff --git a/compiler/rustc_mir_transform/src/coroutine/layout.rs b/compiler/rustc_mir_transform/src/coroutine/layout.rs index 8742529d7015b..d0c236c4d53a6 100644 --- a/compiler/rustc_mir_transform/src/coroutine/layout.rs +++ b/compiler/rustc_mir_transform/src/coroutine/layout.rs @@ -47,7 +47,7 @@ use rustc_trait_selection::infer::TyCtxtInferExt as _; use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt}; use tracing::{debug, instrument}; -use crate::diagnostics::{MustNotSupend, MustNotSuspendReason}; +use crate::diagnostics::{MustNotSuspend, MustNotSuspendReason}; const SELF_ARG: Local = Local::arg(0); @@ -700,13 +700,13 @@ fn check_must_not_suspend_def( hir_id: hir::HirId, data: SuspendCheckData<'_>, ) -> bool { - if let Some(reason_str) = find_attr!(tcx, def_id, MustNotSupend {reason} => reason) { + if let Some(reason_str) = find_attr!(tcx, def_id, MustNotSuspend {reason} => reason) { let reason = reason_str.map(|s| MustNotSuspendReason { span: data.source_span, reason: s }); tcx.emit_node_span_lint( MUST_NOT_SUSPEND, hir_id, data.source_span, - MustNotSupend { + MustNotSuspend { tcx, yield_sp: data.yield_span, reason, diff --git a/compiler/rustc_mir_transform/src/diagnostics.rs b/compiler/rustc_mir_transform/src/diagnostics.rs index 6e083fef20928..88572514736c9 100644 --- a/compiler/rustc_mir_transform/src/diagnostics.rs +++ b/compiler/rustc_mir_transform/src/diagnostics.rs @@ -327,7 +327,7 @@ pub(crate) struct PatternTypo { pub kind: &'static str, } -pub(crate) struct MustNotSupend<'a, 'tcx> { +pub(crate) struct MustNotSuspend<'a, 'tcx> { pub tcx: TyCtxt<'tcx>, pub yield_sp: Span, pub reason: Option, @@ -338,7 +338,7 @@ pub(crate) struct MustNotSupend<'a, 'tcx> { } // Needed for def_path_str -impl<'a> Diagnostic<'a> for MustNotSupend<'_, '_> { +impl<'a> Diagnostic<'a> for MustNotSuspend<'_, '_> { fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a> { let mut diag = Diag::new( dcx, diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index b6511ce0528ee..e4a32b7cf43ac 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -266,7 +266,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { AttributeKind::MacroUse { .. } => (), AttributeKind::Marker => (), AttributeKind::MoveSizeLimit { .. } => (), - AttributeKind::MustNotSupend { .. } => (), + AttributeKind::MustNotSuspend { .. } => (), AttributeKind::MustUse { .. } => (), AttributeKind::Naked(..) => (), AttributeKind::NeedsAllocator => (), From 65ae6475a62e98dfb96c21e7a6602357f6558701 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:36:14 +0100 Subject: [PATCH 24/39] Remove useless doc attr comment --- compiler/rustc_passes/src/check_attr.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index e4a32b7cf43ac..774564cea519c 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -239,7 +239,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> { AttributeKind::DefaultLibAllocator => (), AttributeKind::Deprecated { .. } => (), AttributeKind::DoNotRecommend => (), - // `#[doc]` is actually a lot more than just doc comments, so is checked below AttributeKind::DocComment { .. } => (), AttributeKind::EiiDeclaration { .. } => (), AttributeKind::ExportName { .. } => (), From 65d368e0ce335cc2a10b0598fb951cb45eac4233 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Fri, 6 Nov 2026 12:46:17 +0100 Subject: [PATCH 25/39] view-types: allow types that dereference to views to be receivers --- .../rustc_hir_analysis/src/check/wfcheck.rs | 39 +++++++++++++++++++ tests/ui/view-types/duplicate_field.rs | 2 - tests/ui/view-types/duplicate_field.stderr | 23 +---------- tests/ui/view-types/hygiene.rs | 3 +- tests/ui/view-types/hygiene.stderr | 26 ------------- tests/ui/view-types/syntax-errors.rs | 1 - tests/ui/view-types/syntax-errors.stderr | 14 +------ tests/ui/view-types/tuple-structs.rs | 3 +- tests/ui/view-types/tuple-structs.stderr | 12 ------ 9 files changed, 46 insertions(+), 77 deletions(-) delete mode 100644 tests/ui/view-types/hygiene.stderr delete mode 100644 tests/ui/view-types/tuple-structs.stderr diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index d3ebb2b173da7..75c98764443ba 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -1974,6 +1974,9 @@ fn receiver_is_valid<'tcx>( confirm_type_is_not_a_method_generic_param(potential_self_ty, method_generics)?; + // Treat view types in receiver position like their counterpart. + let potential_self_ty = ignore_view(wfcx, potential_self_ty); + // Check if the self type unifies. If it does, then commit the result // since it may have region side-effects. if let Ok(()) = wfcx.infcx.commit_if_ok(|_| { @@ -2018,6 +2021,42 @@ fn receiver_is_valid<'tcx>( Err(ReceiverValidityError::DoesNotDeref) } +fn ignore_view<'tcx>(wfcx: &WfCheckingCtxt<'_, 'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { + match ty.kind() { + ty::View(def, args, _) => Ty::new_adt(wfcx.tcx(), *def, *args), + + ty::Bool + | ty::Char + | ty::Int(_) + | ty::Uint(_) + | ty::Float(_) + | ty::Adt(_, _) + | ty::Foreign(_) + | ty::Str + | ty::Array(_, _) + | ty::Pat(_, _) + | ty::Slice(_) + | ty::RawPtr(_, _) + | ty::Ref(_, _, _) + | ty::FnDef(_, _) + | ty::FnPtr(_, _) + | ty::UnsafeBinder(_) + | ty::Dynamic(_, _) + | ty::Closure(_, _) + | ty::CoroutineClosure(_, _) + | ty::Coroutine(_, _) + | ty::CoroutineWitness(_, _) + | ty::Never + | ty::Tuple(_) + | ty::Alias(_, _) + | ty::Param(_) + | ty::Bound(_, _) + | ty::Placeholder(_) + | ty::Infer(_) + | ty::Error(_) => ty, + } +} + fn legacy_receiver_is_implemented<'tcx>( wfcx: &WfCheckingCtxt<'_, 'tcx>, legacy_receiver_trait_def_id: DefId, diff --git a/tests/ui/view-types/duplicate_field.rs b/tests/ui/view-types/duplicate_field.rs index a9d4d40ae157d..4b3e0ca0850e0 100644 --- a/tests/ui/view-types/duplicate_field.rs +++ b/tests/ui/view-types/duplicate_field.rs @@ -19,13 +19,11 @@ fn f( impl Foo { fn f(self: &mut view_type!(Self.{ bar, bar })) {} //~^ ERROR field `bar` is already part of the view - //~| ERROR invalid `self` parameter type } impl Pair { fn f(self: &mut view_type!(Self.{ 0, 0 })) {} //~^ ERROR field `0` is already part of the view - //~| ERROR invalid `self` parameter type } fn main() {} diff --git a/tests/ui/view-types/duplicate_field.stderr b/tests/ui/view-types/duplicate_field.stderr index 75dfe30be0121..c974b0ead238a 100644 --- a/tests/ui/view-types/duplicate_field.stderr +++ b/tests/ui/view-types/duplicate_field.stderr @@ -22,32 +22,13 @@ LL | fn f(self: &mut view_type!(Self.{ bar, bar })) {} | | | field `bar` is declared as viewed here -error[E0307]: invalid `self` parameter type: `&mut view_type!(Foo.{ (field_of!(Foo, bar),) })` - --> $DIR/duplicate_field.rs:20:16 - | -LL | fn f(self: &mut view_type!(Self.{ bar, bar })) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: type of `self` must be `Self` or a type that dereferences to it - = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) - error: field `0` is already part of the view - --> $DIR/duplicate_field.rs:26:42 + --> $DIR/duplicate_field.rs:25:42 | LL | fn f(self: &mut view_type!(Self.{ 0, 0 })) {} | - ^ | | | field `0` is declared as viewed here -error[E0307]: invalid `self` parameter type: `&mut view_type!(Pair.{ (field_of!(Pair, 0),) })` - --> $DIR/duplicate_field.rs:26:16 - | -LL | fn f(self: &mut view_type!(Self.{ 0, 0 })) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: type of `self` must be `Self` or a type that dereferences to it - = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) - -error: aborting due to 6 previous errors +error: aborting due to 4 previous errors -For more information about this error, try `rustc --explain E0307`. diff --git a/tests/ui/view-types/hygiene.rs b/tests/ui/view-types/hygiene.rs index f2d1a69d68eb4..b0c8c9f29250f 100644 --- a/tests/ui/view-types/hygiene.rs +++ b/tests/ui/view-types/hygiene.rs @@ -1,3 +1,4 @@ +//@ run-pass //@ aux-build: hygiene.rs #![feature(view_types, decl_macro)] @@ -15,7 +16,6 @@ pub macro what($name: ident) { impl Foo { fn f(self: &mut view_type!(Self.{ bar, $name })) {} - //~^ ERROR invalid `self` parameter type } } @@ -27,7 +27,6 @@ struct Bar { impl Bar { fn f(self: &hygiene::view_bar!()) {} - //~^ ERROR invalid `self` parameter type } fn main() {} diff --git a/tests/ui/view-types/hygiene.stderr b/tests/ui/view-types/hygiene.stderr deleted file mode 100644 index eb368fe73fa5e..0000000000000 --- a/tests/ui/view-types/hygiene.stderr +++ /dev/null @@ -1,26 +0,0 @@ -error[E0307]: invalid `self` parameter type: `&mut view_type!(Foo.{ (field_of!(Foo, bar), field_of!(Foo, bar)) })` - --> $DIR/hygiene.rs:17:20 - | -LL | pub macro what($name: ident) { -... -LL | fn f(self: &mut view_type!(Self.{ bar, $name })) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -... -LL | what!(bar); - | ---------- in this macro invocation - | - = note: type of `self` must be `Self` or a type that dereferences to it - = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) - -error[E0307]: invalid `self` parameter type: `&view_type!(Bar.{ (field_of!(Bar, async),) })` - --> $DIR/hygiene.rs:29:16 - | -LL | fn f(self: &hygiene::view_bar!()) {} - | ^^^^^^^^^^^^^^^^^^^^^ - | - = note: type of `self` must be `Self` or a type that dereferences to it - = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) - -error: aborting due to 2 previous errors - -For more information about this error, try `rustc --explain E0307`. diff --git a/tests/ui/view-types/syntax-errors.rs b/tests/ui/view-types/syntax-errors.rs index 6e621dfc96646..84bcb977827e0 100644 --- a/tests/ui/view-types/syntax-errors.rs +++ b/tests/ui/view-types/syntax-errors.rs @@ -23,7 +23,6 @@ impl Foo { fn no_comma(self: &mut view_type!(Foo.{ bar baz }), _: &mut view_type!(Foo.{ bar baz })) {} //~^ ERROR expected one of //~| ERROR expected one of - //~| ERROR invalid `self` parameter type } fn main() {} diff --git a/tests/ui/view-types/syntax-errors.stderr b/tests/ui/view-types/syntax-errors.stderr index 0775aa1b4daad..479151b267e2e 100644 --- a/tests/ui/view-types/syntax-errors.stderr +++ b/tests/ui/view-types/syntax-errors.stderr @@ -72,16 +72,6 @@ error[E0609]: no field `r#for` on type `Foo` LL | fn keyword(self: &mut view_type!(Foo.{ where }), _: &mut view_type!(Foo.{ for })) {} | ^^^ -error[E0307]: invalid `self` parameter type: `&mut view_type!(Foo.{ (field_of!(Foo, bar), field_of!(Foo, baz)) })` - --> $DIR/syntax-errors.rs:23:23 - | -LL | fn no_comma(self: &mut view_type!(Foo.{ bar baz }), _: &mut view_type!(Foo.{ bar baz })) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: type of `self` must be `Self` or a type that dereferences to it - = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) - -error: aborting due to 11 previous errors +error: aborting due to 10 previous errors -Some errors have detailed explanations: E0307, E0609. -For more information about an error, try `rustc --explain E0307`. +For more information about this error, try `rustc --explain E0609`. diff --git a/tests/ui/view-types/tuple-structs.rs b/tests/ui/view-types/tuple-structs.rs index 15fe5b2b60807..04dd222cef98d 100644 --- a/tests/ui/view-types/tuple-structs.rs +++ b/tests/ui/view-types/tuple-structs.rs @@ -1,3 +1,5 @@ +//@ run-pass + #![feature(view_types)] #![allow(unused)] @@ -7,7 +9,6 @@ struct Pair(usize, u32); impl Pair { fn foo(self: &mut view_type!(Pair.{ 0, 1 })) {} - //~^ ERROR invalid `self` parameter type fn bar(_pair: &mut view_type!(Pair.{ 0, 1 })) {} } diff --git a/tests/ui/view-types/tuple-structs.stderr b/tests/ui/view-types/tuple-structs.stderr deleted file mode 100644 index 674742527ab00..0000000000000 --- a/tests/ui/view-types/tuple-structs.stderr +++ /dev/null @@ -1,12 +0,0 @@ -error[E0307]: invalid `self` parameter type: `&mut view_type!(Pair.{ (field_of!(Pair, 0), field_of!(Pair, 1)) })` - --> $DIR/tuple-structs.rs:9:18 - | -LL | fn foo(self: &mut view_type!(Pair.{ 0, 1 })) {} - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - | - = note: type of `self` must be `Self` or a type that dereferences to it - = help: consider changing to `self`, `&self`, `&mut self`, `self: Box`, `self: Rc`, `self: Arc`, or `self: Pin

` (where P is one of the previous types except `Self`) - -error: aborting due to 1 previous error - -For more information about this error, try `rustc --explain E0307`. From 87f5568fa7219eac5933c16bd03684f0d9e883b2 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Wed, 11 Nov 2026 12:37:36 +0100 Subject: [PATCH 26/39] view-types: add format tests --- src/tools/rustfmt/tests/source/view_types.rs | 7 +++++++ src/tools/rustfmt/tests/target/view_types.rs | 7 +++++++ 2 files changed, 14 insertions(+) create mode 100644 src/tools/rustfmt/tests/source/view_types.rs create mode 100644 src/tools/rustfmt/tests/target/view_types.rs diff --git a/src/tools/rustfmt/tests/source/view_types.rs b/src/tools/rustfmt/tests/source/view_types.rs new file mode 100644 index 0000000000000..ae9a0c7130f78 --- /dev/null +++ b/src/tools/rustfmt/tests/source/view_types.rs @@ -0,0 +1,7 @@ +#![feature(view_types, view_type_macro)] + +use std::view::view_type; + +type Foo_ = std::view::view_type!(Foo.{}); +type Foo_ = std::view::view_type!(Foo.{ bar }); +type Foo_ = std::view::view_type!(Foo.{ bar, baz }); diff --git a/src/tools/rustfmt/tests/target/view_types.rs b/src/tools/rustfmt/tests/target/view_types.rs new file mode 100644 index 0000000000000..ae9a0c7130f78 --- /dev/null +++ b/src/tools/rustfmt/tests/target/view_types.rs @@ -0,0 +1,7 @@ +#![feature(view_types, view_type_macro)] + +use std::view::view_type; + +type Foo_ = std::view::view_type!(Foo.{}); +type Foo_ = std::view::view_type!(Foo.{ bar }); +type Foo_ = std::view::view_type!(Foo.{ bar, baz }); From af3705feb8a8714a8c41dd76211b30ccee5a5611 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Wed, 11 Nov 2026 16:37:51 +0100 Subject: [PATCH 27/39] clippy: teach dereference lints about view types --- src/tools/clippy/clippy_lints/src/dereference.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 8a75feee99237..3823dc1b1b3c0 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -956,7 +956,7 @@ impl TyCoercionStability { | ty::Placeholder(_) | ty::Dynamic(..) | ty::Param(_) => Self::Reborrow, - ty::Adt(_, args) + ty::Adt(_, args) | ty::View(_, args, _) if ty.has_placeholders() || ty.has_opaque_types() || (!for_return && args.has_non_region_param()) => @@ -990,10 +990,8 @@ impl TyCoercionStability { .. }, ) - | ty::UnsafeBinder(_) => Self::Deref, - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), + | ty::UnsafeBinder(_) + | ty::View(..) => Self::Deref, }; } } From 70801970ae81e3513c0f0ce15d3b95e338f2ace8 Mon Sep 17 00:00:00 2001 From: Sasha Pourcelot Date: Wed, 11 Nov 2026 16:37:51 +0100 Subject: [PATCH 28/39] rustdoc: teach about view types --- src/librustdoc/clean/mod.rs | 16 +++++++++++++--- src/librustdoc/clean/types.rs | 10 ++++++---- src/librustdoc/html/format.rs | 8 ++++++++ src/librustdoc/html/render/search_index.rs | 1 + src/librustdoc/json/conversions.rs | 4 +++- src/librustdoc/passes/collect_intra_doc_links.rs | 9 +++------ src/librustdoc/passes/collect_trait_impls.rs | 4 +--- 7 files changed, 35 insertions(+), 17 deletions(-) diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 5f5fab6d24aae..ff5aeb1097799 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2367,6 +2367,19 @@ pub(crate) fn clean_middle_ty<'tcx>( ty } } + ty::View(def, args, fields) => { + let did = def.did(); + let kind = match def.adt_kind() { + AdtKind::Struct => ItemType::Struct, + AdtKind::Union => ItemType::Union, + AdtKind::Enum => ItemType::Enum, + }; + inline::record_extern_fqn(cx, did, kind); + let path = + Box::new(clean_middle_path(cx, did, false, ThinVec::new(), bound_ty.rebind(args))); + let fields = format!("{fields:?}").into_boxed_str(); + Type::View(path, fields) + } ty::Closure(..) => panic!("Closure"), ty::CoroutineClosure(..) => panic!("CoroutineClosure"), @@ -2376,9 +2389,6 @@ pub(crate) fn clean_middle_ty<'tcx>( ty::Infer(..) => panic!("Infer"), ty::Error(_) => FatalError.raise(), - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index 8844816e26bd0..51a66df33d915 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -35,7 +35,7 @@ use tracing::{debug, trace}; pub(crate) use self::Type::{ Array, BareFunction, BorrowedRef, DynTrait, Generic, ImplTrait, Infer, Primitive, QPath, - RawPointer, SelfTy, Slice, Tuple, UnsafeBinder, + RawPointer, SelfTy, Slice, Tuple, UnsafeBinder, View, }; use crate::clean::cfg::Cfg; use crate::clean::clean_middle_path; @@ -1406,6 +1406,8 @@ pub(crate) enum Type { /// A qualified path to an associated item: `::Name` QPath(Box), + View(Box, Box), + /// A type that is inferred: `_` Infer, @@ -1600,6 +1602,7 @@ impl Type { BorrowedRef { type_: Generic(..), .. } => None, BorrowedRef { type_, .. } => type_.real_def_id(), QPath(QPathData { self_type, .. }) => self_type.real_def_id(), + View(path, _) => Some(path.def_id()), DynTrait(..) | Primitive(..) | Tuple(..) @@ -1641,6 +1644,7 @@ impl Type { Type::FieldOf(..) => PrimitiveType::FieldOf, RawPointer(..) => PrimitiveType::RawPointer, QPath(QPathData { self_type, .. }) => return self_type.def_id(cache), + Type::View(path, _) => return Some(path.def_id()), Generic(_) | SelfTy | Infer | ImplTrait(_) | UnsafeBinder(_) => return None, }; Primitive(t).def_id(cache) @@ -1782,13 +1786,11 @@ impl PrimitiveType { | ty::Dynamic(..) | ty::Error(..) | ty::Foreign(..) + | ty::View(..) | ty::Infer(..) | ty::Param(..) | ty::Placeholder(..) | ty::UnsafeBinder(..) => None, - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 3c65329ca0406..6d712a0a26dcf 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -1260,6 +1260,14 @@ fn fmt_type( write!(f, "impl {}", WithOpts::from(f).display(print_generic_bounds(bounds, cx))) } clean::QPath(qpath) => print_qpath_data(qpath, cx).fmt(f), + clean::View(path, fields) => { + // Paths like `T::Output` and `Self::Output` should be rendered with all segments. + let did = path.def_id(); + let path = + fmt::from_fn(|f| resolved_path(f, did, path, path.is_assoc_ty(), use_absolute, cx)); + + write!(f, "{path}.{{ {fields} }}") + } } } diff --git a/src/librustdoc/html/render/search_index.rs b/src/librustdoc/html/render/search_index.rs index d56ab9fd7d275..17adc49f6a1bd 100644 --- a/src/librustdoc/html/render/search_index.rs +++ b/src/librustdoc/html/render/search_index.rs @@ -2083,6 +2083,7 @@ fn get_index_type_id( None } } + clean::View(ref path, _) => Some(RenderTypeId::DefId(path.def_id())), // Not supported yet clean::Type::Pat(..) | clean::Type::FieldOf(..) diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 49e79fe99e073..88e6d48e975c3 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -652,7 +652,7 @@ impl FromClean for Type { fn from_clean(ty: &clean::Type, renderer: &JsonRenderer<'_>) -> Self { use clean::Type::{ Array, BareFunction, BorrowedRef, Generic, ImplTrait, Infer, Primitive, QPath, - RawPointer, SelfTy, Slice, Tuple, UnsafeBinder, + RawPointer, SelfTy, Slice, Tuple, UnsafeBinder, View, }; match ty { @@ -691,6 +691,8 @@ impl FromClean for Type { QPath(qpath) => qpath.into_json(renderer), // FIXME(unsafe_binder): Implement rustdoc-json. UnsafeBinder(_) => unimplemented!(), + // FIXME(view_types): that's quite bad but heh + View(path, _) => Type::ResolvedPath(path.into_json(renderer)), } } } diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index df4fa2bed9c53..3b13271e39682 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -547,9 +547,9 @@ fn ty_to_res<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option { ty::FnDef(..) => panic!("type alias to a function definition"), ty::FnPtr(..) => Res::Primitive(Fn), ty::Never => Res::Primitive(Never), - ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) | ty::Foreign(did) => { - Res::from_def_id(tcx, did) - } + ty::Adt(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _) + | ty::View(ty::AdtDef(Interned(&ty::AdtDefData { did, .. }, _)), _, _) + | ty::Foreign(did) => Res::from_def_id(tcx, did), ty::Alias(_, ..) | ty::Closure(..) | ty::CoroutineClosure(..) @@ -562,9 +562,6 @@ fn ty_to_res<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option { | ty::Placeholder(_) | ty::Infer(_) | ty::Error(_) => return None, - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), }) } diff --git a/src/librustdoc/passes/collect_trait_impls.rs b/src/librustdoc/passes/collect_trait_impls.rs index 30123a91bffb8..109131daefc20 100644 --- a/src/librustdoc/passes/collect_trait_impls.rs +++ b/src/librustdoc/passes/collect_trait_impls.rs @@ -201,6 +201,7 @@ impl SelfTyHead { // but clean_middle_ty doesn't handle this correctly yet either ty::UnsafeBinder(_) => Self::Other, ty::Adt(def, _) => Self::Item(def.did()), + ty::View(def, _, _) => Self::Item(def.did()), ty::Foreign(did) => Self::Item(did), ty::Dynamic(obj, _) => { // HACK: pick the first `did` as the `did` of the trait object. Someone @@ -260,9 +261,6 @@ impl SelfTyHead { | ty::Infer(..) => panic!("unexpected impl self ty {bound_ty}"), ty::Error(_) => FatalError.raise(), - - // FIXME(scrabsha) - ty::View(..) => unimplemented!(), } } } From 1708a76b94ca7a69e932c0e79b67379968f219c4 Mon Sep 17 00:00:00 2001 From: malezjaa Date: Sun, 8 Nov 2026 09:54:38 +0100 Subject: [PATCH 29/39] 1/n: split set_struct_body into set_struct_body and set_packed_struct_body --- .../rustc_codegen_llvm/src/builder/gpu_offload.rs | 4 ++-- compiler/rustc_codegen_llvm/src/consts.rs | 6 ++---- compiler/rustc_codegen_llvm/src/type_.rs | 13 ++++++++----- compiler/rustc_codegen_llvm/src/type_of.rs | 9 ++++++--- 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs index f26c02fe394eb..a2b99b032febf 100644 --- a/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs +++ b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs @@ -171,7 +171,7 @@ pub(crate) fn generate_at_one<'ll>(cx: &CodegenCx<'ll, '_>) -> llvm::Value<'ll> ]; let struct_elems_ty: Vec<_> = struct_elems.iter().map(|&x| cx.val_ty(x)).collect(); let initializer = crate::common::named_struct(struct_ident_ty, &struct_elems); - cx.set_struct_body(struct_ident_ty, &struct_elems_ty, false); + cx.set_struct_body(struct_ident_ty, &struct_elems_ty); let at_one = add_unnamed_global(&cx, &"", initializer, PrivateLinkage); llvm::set_alignment(at_one, Align::EIGHT); at_one @@ -199,7 +199,7 @@ impl TgtOffloadEntry { // For each kernel to run on the gpu, we will later generate one entry of this type. // copied from LLVM let entry_elements = vec![ti64, ti16, ti16, ti32, tptr, tptr, ti64, ti64, tptr]; - cx.set_struct_body(offload_entry_ty, &entry_elements, false); + cx.set_struct_body(offload_entry_ty, &entry_elements); offload_entry_ty } diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 4952fdc732e9f..36a7fdfa48d1e 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -731,8 +731,7 @@ impl<'ll> CodegenCx<'ll, '_> { let class_t = self.type_named_struct("struct._class_t"); let els = [self.type_ptr(); 5]; - let packed = false; - self.set_struct_body(class_t, &els, packed); + self.set_struct_body(class_t, &els); self.objc_class_t.set(Some(class_t)); class_t @@ -884,8 +883,7 @@ impl<'ll> CodegenCx<'ll, '_> { let llty = self.type_named_struct("struct._objc_module"); let i32_llty = self.type_i32(); let ptr_llty = self.type_ptr(); - let packed = false; - self.set_struct_body(llty, &[i32_llty, i32_llty, ptr_llty, ptr_llty], packed); + self.set_struct_body(llty, &[i32_llty, i32_llty, ptr_llty, ptr_llty]); let version = self.const_uint(i32_llty, 7); let size = self.const_uint(i32_llty, 16); diff --git a/compiler/rustc_codegen_llvm/src/type_.rs b/compiler/rustc_codegen_llvm/src/type_.rs index d69559593e227..90250fc97b284 100644 --- a/compiler/rustc_codegen_llvm/src/type_.rs +++ b/compiler/rustc_codegen_llvm/src/type_.rs @@ -13,7 +13,7 @@ use rustc_target::callconv::{CastTarget, FnAbi}; use crate::abi::{FnAbiLlvmExt, LlvmType}; use crate::common; use crate::context::{CodegenCx, GenericCx, SCx}; -use crate::llvm::{self, FALSE, TRUE, ToLlvmBool, Type, TypeKind, Value}; +use crate::llvm::{self, FALSE, TRUE, Type, TypeKind, Value}; use crate::type_of::LayoutLlvmExt; impl<'ll> fmt::Debug for Type<'ll> { @@ -34,11 +34,14 @@ impl<'ll, CX: Borrow>> GenericCx<'ll, CX> { unsafe { llvm::LLVMStructCreateNamed(self.llcx(), name.as_ptr()) } } - pub(crate) fn set_struct_body(&self, ty: Type<'ll>, els: &[Type<'ll>], packed: bool) { - unsafe { - llvm::LLVMStructSetBody(ty, els.as_ptr(), els.len() as c_uint, packed.to_llvm_bool()) - } + pub(crate) fn set_struct_body(&self, ty: Type<'ll>, els: &[Type<'ll>]) { + unsafe { llvm::LLVMStructSetBody(ty, els.as_ptr(), els.len() as c_uint, FALSE) } } + + pub(crate) fn set_struct_body_packed(&self, ty: Type<'ll>, els: &[Type<'ll>]) { + unsafe { llvm::LLVMStructSetBody(ty, els.as_ptr(), els.len() as c_uint, TRUE) } + } + pub(crate) fn type_void(&self) -> Type<'ll> { unsafe { llvm::LLVMVoidTypeInContext(self.llcx()) } } diff --git a/compiler/rustc_codegen_llvm/src/type_of.rs b/compiler/rustc_codegen_llvm/src/type_of.rs index 190cbe32ac65b..a23b4731f936b 100644 --- a/compiler/rustc_codegen_llvm/src/type_of.rs +++ b/compiler/rustc_codegen_llvm/src/type_of.rs @@ -79,8 +79,7 @@ fn uncached_llvm_type<'ll, 'tcx>( None => cx.type_struct(&[fill]), Some(ref name) => { let llty = cx.type_named_struct(name); - let packed = false; - cx.set_struct_body(llty, &[fill], packed); + cx.set_struct_body(llty, &[fill]); llty } } @@ -269,7 +268,11 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> { if let Some((llty, layout)) = defer { let (llfields, packed) = struct_llfields(cx, layout); - cx.set_struct_body(llty, &llfields, packed); + if packed { + cx.set_struct_body_packed(llty, &llfields) + } else { + cx.set_struct_body(llty, &llfields) + } } llty } From 5627340486af7149a05014e1f2e4181a0d34e1b0 Mon Sep 17 00:00:00 2001 From: malezjaa Date: Sun, 8 Nov 2026 10:03:31 +0100 Subject: [PATCH 30/39] 2/n: remove pointless casts --- compiler/rustc_codegen_llvm/src/back/write.rs | 10 ++++------ compiler/rustc_codegen_llvm/src/builder/autodiff.rs | 2 +- compiler/rustc_codegen_llvm/src/common.rs | 2 +- compiler/rustc_codegen_llvm/src/debuginfo/mod.rs | 8 ++++---- compiler/rustc_codegen_llvm/src/intrinsic.rs | 8 ++++---- compiler/rustc_codegen_llvm/src/type_of.rs | 2 +- 6 files changed, 15 insertions(+), 17 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 83b5b7405d63d..c3f03db59b986 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -669,7 +669,7 @@ pub(crate) unsafe fn llvm_optimize<'ll>( } // Create the new parameter list, with ptr as the first argument - let mut new_param_types = Vec::with_capacity(old_param_count as usize + 1); + let mut new_param_types = Vec::with_capacity(old_param_count + 1); new_param_types.push(cx.type_ptr()); // This relies on undocumented LLVM knowledge that scalars must be passed as i64 @@ -1043,14 +1043,12 @@ pub(crate) fn codegen( output_ptr: *mut c_char, output_len: size_t, ) -> size_t { - let input = - unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len as usize) }; + let input = unsafe { slice::from_raw_parts(input_ptr as *const u8, input_len) }; let Ok(input) = str::from_utf8(input) else { return 0 }; - let output = unsafe { - slice::from_raw_parts_mut(output_ptr as *mut u8, output_len as usize) - }; + let output = + unsafe { slice::from_raw_parts_mut(output_ptr as *mut u8, output_len) }; let mut cursor = io::Cursor::new(output); let Ok(demangled) = rustc_demangle::try_demangle(input) else { return 0 }; diff --git a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs index 72ce05213fb7d..7b233abc02144 100644 --- a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs +++ b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs @@ -163,7 +163,7 @@ fn match_args_from_caller_to_enzyme<'ll, 'tcx>( let global_dupnoneedv = cx.declare_global("enzyme_dupnoneedv", cx.type_ptr()); while activity_pos < inputs.len() { - let diff_activity = inputs[activity_pos as usize]; + let diff_activity = inputs[activity_pos]; // Duplicated arguments received a shadow argument, into which enzyme will write the // gradient. let (activity, duplicated): (Value<'ll>, bool) = match diff_activity { diff --git a/compiler/rustc_codegen_llvm/src/common.rs b/compiler/rustc_codegen_llvm/src/common.rs index 7e47267a29f8b..48abedf850f32 100644 --- a/compiler/rustc_codegen_llvm/src/common.rs +++ b/compiler/rustc_codegen_llvm/src/common.rs @@ -291,7 +291,7 @@ impl<'ll, 'tcx> ConstCodegenMethods for CodegenCx<'ll, 'tcx> { } fn const_i64(&self, i: i64) -> Value<'ll> { - self.const_int(self.type_i64(), i as i64) + self.const_int(self.type_i64(), i) } fn const_int(&self, t: Type<'ll>, i: i64) -> Value<'ll> { diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index 687d3bbd6b780..2736e18577f61 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -540,22 +540,22 @@ impl<'ll, 'tcx> DebugInfoBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { if direct_offset.bytes() > 0 { addr_ops.push(DW_OP_plus_uconst); - addr_ops.push(direct_offset.bytes() as u64); + addr_ops.push(direct_offset.bytes()); addr_ops.push(DW_OP_stack_value); } for &offset in indirect_offsets { addr_ops.push(DW_OP_deref); if offset.bytes() > 0 { addr_ops.push(DW_OP_plus_uconst); - addr_ops.push(offset.bytes() as u64); + addr_ops.push(offset.bytes()); } } if let Some(fragment) = fragment { // `DW_OP_LLVM_fragment` takes as arguments the fragment's // offset and size, both of them in bits. addr_ops.push(DW_OP_LLVM_fragment); - addr_ops.push(fragment.start.bits() as u64); - addr_ops.push((fragment.end - fragment.start).bits() as u64); + addr_ops.push(fragment.start.bits()); + addr_ops.push((fragment.end - fragment.start).bits()); } let di_builder = DIB(self.cx()); diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index c499cfc811a22..319dff0cac0f3 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -2298,7 +2298,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>( // Check that the indices are in-bounds. let indices = args[2].immediate(); for i in 0..n { - let val = bx.const_get_elt(indices, i as u64); + let val = bx.const_get_elt(indices, i); let idx = bx .const_to_opt_u128(val, true) .unwrap_or_else(|| bug!("typeck should have already ensured that these are const")); @@ -2390,7 +2390,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>( }), }; let i1 = bx.type_i1(); - let i1xn = bx.type_scalable_vector(i1, m_len as u64); + let i1xn = bx.type_scalable_vector(i1, m_len); bx.trunc(args[0].immediate(), i1xn) } else { let in_elem_bitwidth = require_int_or_uint_ty!( @@ -3340,7 +3340,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>( in_elem }), }, - in_len as u64, + in_len, ); let llvm_intrinsic = match name { sym::simd_bswap => "llvm.bswap", @@ -3427,7 +3427,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>( if signed { 's' } else { 'u' }, if is_add { "add" } else { "sub" }, ); - let vec_ty = bx.cx.type_vector(elem_ty, in_len as u64); + let vec_ty = bx.cx.type_vector(elem_ty, in_len); return Ok(bx.call_intrinsic(llvm_intrinsic, &[vec_ty], &[lhs, rhs])); } diff --git a/compiler/rustc_codegen_llvm/src/type_of.rs b/compiler/rustc_codegen_llvm/src/type_of.rs index a23b4731f936b..a5682692c1e4c 100644 --- a/compiler/rustc_codegen_llvm/src/type_of.rs +++ b/compiler/rustc_codegen_llvm/src/type_of.rs @@ -120,7 +120,7 @@ fn struct_llfields<'ll, 'tcx>( let mut prev_effective_align = layout.align; let mut result: Vec<_> = Vec::with_capacity(1 + field_count * 2); for i in layout.fields.index_by_increasing_offset() { - let target_offset = layout.fields.offset(i as usize); + let target_offset = layout.fields.offset(i); let field = layout.field(cx, i); let effective_field_align = layout.align.min(field.align).restrict_for_offset(target_offset); From a44ef56f555137227d6da9ad8851c3d17108b7d2 Mon Sep 17 00:00:00 2001 From: malezjaa Date: Sun, 8 Nov 2026 10:10:27 +0100 Subject: [PATCH 31/39] 3/n: returns --- compiler/rustc_codegen_llvm/src/builder.rs | 5 ++- compiler/rustc_codegen_llvm/src/consts.rs | 5 ++- .../src/debuginfo/metadata.rs | 8 ++--- .../src/debuginfo/metadata/enums/cpp_like.rs | 6 ++-- compiler/rustc_codegen_llvm/src/intrinsic.rs | 36 ++----------------- compiler/rustc_codegen_llvm/src/va_arg.rs | 9 ++--- 6 files changed, 15 insertions(+), 54 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index 32e9578355976..edcbf324cdc09 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -74,7 +74,7 @@ impl<'a, 'll> SBuilder<'a, 'll> { bundles.push(funclet_bundle); } - let call = unsafe { + unsafe { llvm::LLVMBuildCallWithOperandBundles( self.llbuilder(), llty, @@ -85,8 +85,7 @@ impl<'a, 'll> SBuilder<'a, 'll> { bundles.len() as c_uint, c"".as_ptr(), ) - }; - call + } } } diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 36a7fdfa48d1e..862713876846b 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -302,10 +302,9 @@ impl<'ll> CodegenCx<'ll, '_> { let gv = match kind { Some(kind) if !self.tcx.sess.fewer_names() => { let name = self.generate_local_symbol_name(kind); - let gv = self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| { + self.define_global(&name, self.val_ty(cv)).unwrap_or_else(|| { bug!("symbol `{}` is already defined", name); - }); - gv + }) } _ => self.define_global("", self.val_ty(cv)).unwrap_or_else(|| { bug!("anonymous global symbol is already defined"); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index ff0b924f5701e..fbfe1166a16e3 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -990,7 +990,7 @@ pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>( ); let flags = c""; - let unit_metadata = llvm::LLVMRustDIBuilderCreateCompileUnit( + llvm::LLVMRustDIBuilderCreateCompileUnit( debug_context.builder.as_ref(), dwarf_const::DW_LANG_Rust, compile_unit_file, @@ -1009,10 +1009,8 @@ pub(crate) fn build_compile_unit_di_node<'ll, 'tcx>( tcx.sess.opts.unstable_opts.split_dwarf_inlining, tcx.sess.opts.unstable_opts.debuginfo_for_profiling, debug_name_table_kind, - ); - - return unit_metadata; - }; + ) + } } /// Creates a `DW_TAG_member` entry inside the DIE represented by the given `type_di_node`. 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 100037d55b79d..217813b0c5751 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 @@ -213,10 +213,8 @@ pub(super) fn build_enum_type_di_node<'ll, 'tcx>( ), |cx, enum_type_di_node| { match enum_type_and_layout.variants { - Variants::Empty => { - // We don't generate any members for uninhabited types. - return smallvec![]; - } + // We don't generate any members for uninhabited types. + Variants::Empty => smallvec![], Variants::Single { index: variant_index } => build_single_variant_union_fields( cx, enum_adt_def, diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 319dff0cac0f3..a4a1dad355d09 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -1499,17 +1499,7 @@ fn codegen_msvc_try<'ll, 'tcx>( // Note that no invoke is used here because by definition this function // can't panic (that's what it's catching). - let ret = bx.call( - llty, - None, - None, - llfn, - ReturnSlot::Direct, - &[try_func, data, catch_func], - None, - None, - ); - ret + bx.call(llty, None, None, llfn, ReturnSlot::Direct, &[try_func, data, catch_func], None, None) } // WASM's definition of the `rust_try` function. @@ -1600,17 +1590,7 @@ fn codegen_wasm_try<'ll, 'tcx>( // Note that no invoke is used here because by definition this function // can't panic (that's what it's catching). - let ret = bx.call( - llty, - None, - None, - llfn, - ReturnSlot::Direct, - &[try_func, data, catch_func], - None, - None, - ); - ret + bx.call(llty, None, None, llfn, ReturnSlot::Direct, &[try_func, data, catch_func], None, None) } // Definition of the standard `try` function for Rust using the GNU-like model @@ -1685,17 +1665,7 @@ fn codegen_gnu_try<'ll, 'tcx>( // Note that no invoke is used here because by definition this function // can't panic (that's what it's catching). - let ret = bx.call( - llty, - None, - None, - llfn, - ReturnSlot::Direct, - &[try_func, data, catch_func], - None, - None, - ); - ret + bx.call(llty, None, None, llfn, ReturnSlot::Direct, &[try_func, data, catch_func], None, None) } // Helper function to give a Block to a closure to codegen a shim function. diff --git a/compiler/rustc_codegen_llvm/src/va_arg.rs b/compiler/rustc_codegen_llvm/src/va_arg.rs index e06cdaca0ae5a..339a2b45714cb 100644 --- a/compiler/rustc_codegen_llvm/src/va_arg.rs +++ b/compiler/rustc_codegen_llvm/src/va_arg.rs @@ -21,7 +21,7 @@ fn round_up_to_alignment<'ll>( align: Align, ) -> Value<'ll> { value = bx.add(value, bx.cx().const_i32(align.bytes() as i32 - 1)); - return bx.and(value, bx.cx().const_i32(-(align.bytes() as i32))); + bx.and(value, bx.cx().const_i32(-(align.bytes() as i32))) } fn round_pointer_up_to_alignment<'ll>( @@ -294,10 +294,7 @@ fn emit_aapcs_va_arg<'ll, 'tcx>( bx.br(end); bx.switch_to_block(end); - let val = - bx.phi(layout.immediate_llvm_type(bx), &[reg_value, stack_value], &[in_reg, on_stack]); - - val + bx.phi(layout.immediate_llvm_type(bx), &[reg_value, stack_value], &[in_reg, on_stack]) } fn is_powerpc_softfloat_abi(target: &Target) -> bool { @@ -1063,7 +1060,7 @@ fn emit_xtensa_va_arg<'ll, 'tcx>( assert!(bx.tcx().sess.target.endian == Endian::Little); let value_ptr = bx.phi(bx.type_ptr(), &[regsave_value_ptr, stack_value_ptr], &[from_regsave, from_stack]); - return bx.load(layout.llvm_type(bx), value_ptr, layout.align); + bx.load(layout.llvm_type(bx), value_ptr, layout.align) } /// Determine the va_arg implementation to use. The LLVM va_arg instruction From d4c5c52537e371444d169c2e7158037daa40b0ff Mon Sep 17 00:00:00 2001 From: malezjaa Date: Sun, 8 Nov 2026 10:15:26 +0100 Subject: [PATCH 32/39] 4/n: smaller cleanups --- compiler/rustc_codegen_llvm/src/attributes.rs | 2 +- compiler/rustc_codegen_llvm/src/back/archive.rs | 8 ++++---- compiler/rustc_codegen_llvm/src/back/write.rs | 6 +++--- compiler/rustc_codegen_llvm/src/builder.rs | 2 +- compiler/rustc_codegen_llvm/src/builder/autodiff.rs | 2 +- compiler/rustc_codegen_llvm/src/coverageinfo/llvm_cov.rs | 2 +- compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs | 2 +- .../src/debuginfo/metadata/enums/cpp_like.rs | 2 +- .../rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs | 3 +-- compiler/rustc_codegen_llvm/src/intrinsic.rs | 5 +---- compiler/rustc_codegen_llvm/src/llvm_util.rs | 4 ++-- compiler/rustc_codegen_llvm/src/mono_item.rs | 5 ++--- 12 files changed, 19 insertions(+), 24 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/attributes.rs b/compiler/rustc_codegen_llvm/src/attributes.rs index 1a89c6491457e..f041e07dd14d6 100644 --- a/compiler/rustc_codegen_llvm/src/attributes.rs +++ b/compiler/rustc_codegen_llvm/src/attributes.rs @@ -413,7 +413,7 @@ fn stackprotector_attr<'ll>(cx: &SimpleCx<'ll>, sess: &Session) -> Option<&'ll A fn packed_stack_attr<'ll>( cx: &SimpleCx<'ll>, sess: &Session, - function_attributes: &Vec, + function_attributes: &[TargetFeature], ) -> Option<&'ll Attribute> { if sess.target.arch != Arch::S390x { return None; diff --git a/compiler/rustc_codegen_llvm/src/back/archive.rs b/compiler/rustc_codegen_llvm/src/back/archive.rs index f9dc48e3aba3f..80a465d4c88b4 100644 --- a/compiler/rustc_codegen_llvm/src/back/archive.rs +++ b/compiler/rustc_codegen_llvm/src/back/archive.rs @@ -82,10 +82,10 @@ fn get_llvm_object_symbols( unsafe extern "C" fn error_callback(error: *const c_char) -> *mut c_void { let error = unsafe { CStr::from_ptr(error) }; - Box::into_raw(Box::new(io::Error::new( - io::ErrorKind::Other, - format!("LLVM error: {}", error.to_string_lossy()), - )) as Box) as *mut c_void + Box::into_raw(Box::new(io::Error::other(format!( + "LLVM error: {}", + error.to_string_lossy() + )))) as *mut c_void } } diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index c3f03db59b986..38f24b465ad66 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -1181,15 +1181,15 @@ fn create_section_with_flags_asm(section_name: &str, section_flags: &str, data: if byte == b'\\' || byte == b'"' { asm.push(b'\\'); asm.push(byte); - } else if byte < 0x20 || byte >= 0x80 { + } else if (0x20..0x80).contains(&byte) { + asm.push(byte); + } else { // Avoid non UTF-8 inline assembly. Use octal escape sequence, because it is fixed // width, while hex escapes will consume following characters. asm.push(b'\\'); asm.push(b'0' + ((byte >> 6) & 0x7)); asm.push(b'0' + ((byte >> 3) & 0x7)); asm.push(b'0' + ((byte >> 0) & 0x7)); - } else { - asm.push(byte); } } asm.extend_from_slice(b"\"\n"); diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index edcbf324cdc09..ead0b28c0f218 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -153,7 +153,7 @@ impl<'a, 'll, CX: Borrow>> GenericBuilder<'a, 'll, CX> { // Cast to default addrspace if necessary llvm::LLVMBuildPointerCast(self.llbuilder(), alloca, self.cx.type_ptr(), UNNAMED) }; - if name != "" { + if !name.is_empty() { llvm::set_value_name(val, &name.as_bytes()); } val diff --git a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs index 7b233abc02144..8e680586f569e 100644 --- a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs +++ b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs @@ -110,7 +110,7 @@ pub(crate) fn adjust_activity_to_abi<'tcx>( if let rustc_abi::BackendRepr::ScalarPair { a: _, b: _, b_offset: _ } = layout.backend_repr() { - new_activities.push(da[i].clone()); + new_activities.push(da[i]); new_positions.push(i + 1 - del_activities); } } diff --git a/compiler/rustc_codegen_llvm/src/coverageinfo/llvm_cov.rs b/compiler/rustc_codegen_llvm/src/coverageinfo/llvm_cov.rs index 4467204abc7cd..47ebe9fe38900 100644 --- a/compiler/rustc_codegen_llvm/src/coverageinfo/llvm_cov.rs +++ b/compiler/rustc_codegen_llvm/src/coverageinfo/llvm_cov.rs @@ -41,7 +41,7 @@ pub(crate) fn create_pgo_func_name_var<'ll>( pub(crate) fn write_filenames_to_buffer(filenames: &[impl AsRef]) -> Vec { let (pointers, lengths) = filenames - .into_iter() + .iter() .map(AsRef::as_ref) .map(|s: &str| (s.as_ptr(), s.len())) .unzip::<_, _, Vec<_>, Vec<_>>(); diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index fbfe1166a16e3..b097536080798 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -1856,7 +1856,7 @@ pub(crate) fn extend_scope_to_file<'ll>( } fn tuple_field_name(field_index: usize) -> Cow<'static, str> { - const TUPLE_FIELD_NAMES: [&'static str; 16] = [ + const TUPLE_FIELD_NAMES: [&str; 16] = [ "__0", "__1", "__2", "__3", "__4", "__5", "__6", "__7", "__8", "__9", "__10", "__11", "__12", "__13", "__14", "__15", ]; 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 217813b0c5751..2d9480f9dbbf0 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 @@ -809,7 +809,7 @@ fn build_union_fields_for_direct_tag_enum_or_coroutine<'ll, 'tcx>( let mut unions_fields = SmallVec::with_capacity(variant_field_infos.len() + 1); // We create a field in the union for each variant ... - unions_fields.extend(variant_field_infos.into_iter().map(|variant_member_info| { + unions_fields.extend(variant_field_infos.iter().map(|variant_member_info| { let (file_di_node, line_number) = variant_member_info .source_info .unwrap_or_else(|| (unknown_file_metadata(cx), UNKNOWN_LINE_NUMBER)); 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 c9039bf46e416..e3ae84e6f496a 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs @@ -321,8 +321,7 @@ pub(super) fn build_type_with_children<'ll, 'tcx>( debug_context(cx).type_map.insert(stub_info.unique_type_id, stub_info.metadata); - let members: SmallVec<_> = - members(cx, stub_info.metadata).into_iter().map(|node| Some(node)).collect(); + let members: SmallVec<_> = members(cx, stub_info.metadata).into_iter().map(Some).collect(); let generics = generics(cx); if !(members.is_empty() && generics.is_empty()) { diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index a4a1dad355d09..bde0e130e748c 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -2143,10 +2143,7 @@ fn generic_simd_intrinsic<'ll, 'tcx>( return Ok(splat); } - let supports_scalable = match name { - sym::simd_cast | sym::simd_select => true, - _ => false, - }; + let supports_scalable = matches!(name, sym::simd_cast | sym::simd_select); // Every intrinsic below takes a SIMD vector as its first argument. Some intrinsics also accept // scalable vectors. `require_simd_or_scalable` is used regardless as it'll do the right thing diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index 09305eba07569..b9e976f662958 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -95,7 +95,7 @@ unsafe fn configure_llvm(sess: &EarlySession) { let sess_args = tg_opts.chain(cg_opts); let user_specified_args: FxHashSet<_> = - sess_args.clone().map(|s| llvm_arg_to_arg_name(s)).filter(|s| !s.is_empty()).collect(); + sess_args.clone().map(llvm_arg_to_arg_name).filter(|s| !s.is_empty()).collect(); { // This adds the given argument to LLVM. Unless `force` is true @@ -337,7 +337,7 @@ pub(crate) fn target_config(sess: &EarlySession) -> TargetConfig { sess, |feature| { to_llvm_features(&sess.target, feature) - .map(|f| SmallVec::<[&str; 2]>::from_iter(f.into_iter())) + .map(SmallVec::<[&str; 2]>::from_iter) .unwrap_or_default() }, |feature| { diff --git a/compiler/rustc_codegen_llvm/src/mono_item.rs b/compiler/rustc_codegen_llvm/src/mono_item.rs index cf674b1fd2f71..3413d5115edd3 100644 --- a/compiler/rustc_codegen_llvm/src/mono_item.rs +++ b/compiler/rustc_codegen_llvm/src/mono_item.rs @@ -1,4 +1,3 @@ -use std::borrow::Cow; use std::ffi::CString; use rustc_abi::AddressSpace; @@ -78,7 +77,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { fn predefine_without_aliases( &self, instance: Instance<'tcx>, - attrs: &Cow<'_, CodegenFnAttrs>, + attrs: &CodegenFnAttrs, linkage: Linkage, visibility: Visibility, symbol_name: &str, @@ -167,7 +166,7 @@ impl<'ll, 'tcx> CodegenCx<'ll, 'tcx> { &self, aliasee_instance: Instance<'tcx>, aliasee: llvm::Value<'ll>, - attrs: &Cow<'_, CodegenFnAttrs>, + attrs: &CodegenFnAttrs, aliases: &[(DefId, Linkage, Visibility)], ) { for (alias, linkage, visibility) in aliases { From d44804838572f679bd4d34bdc4b79fe8062e3206 Mon Sep 17 00:00:00 2001 From: malezjaa Date: Sun, 8 Nov 2026 10:32:07 +0100 Subject: [PATCH 33/39] 5/n: needless borrows/derefs --- compiler/rustc_codegen_llvm/src/abi.rs | 2 +- compiler/rustc_codegen_llvm/src/allocator.rs | 6 ++-- .../src/back/llvm_backend.rs | 6 ++-- compiler/rustc_codegen_llvm/src/back/lto.rs | 8 ++--- compiler/rustc_codegen_llvm/src/back/write.rs | 6 ++-- compiler/rustc_codegen_llvm/src/builder.rs | 2 +- .../src/builder/autodiff.rs | 2 +- .../src/builder/gpu_offload.rs | 30 +++++++++---------- compiler/rustc_codegen_llvm/src/consts.rs | 4 +-- compiler/rustc_codegen_llvm/src/context.rs | 2 +- .../src/debuginfo/metadata.rs | 2 +- .../src/debuginfo/metadata/enums/native.rs | 2 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 9 +++--- compiler/rustc_codegen_llvm/src/llvm_util.rs | 6 ++-- compiler/rustc_codegen_llvm/src/typetree.rs | 10 +++---- 15 files changed, 48 insertions(+), 49 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/abi.rs b/compiler/rustc_codegen_llvm/src/abi.rs index 49c07652c8261..f591511767fb5 100644 --- a/compiler/rustc_codegen_llvm/src/abi.rs +++ b/compiler/rustc_codegen_llvm/src/abi.rs @@ -749,7 +749,7 @@ impl<'ll, 'tcx> FnAbiLlvmExt<'ll, 'tcx> for FnAbi<'tcx, Ty<'tcx>> { } } - let cconv = self.llvm_cconv(&bx.cx); + let cconv = self.llvm_cconv(bx.cx); if cconv != llvm::CCallConv { llvm::SetInstructionCallConv(callsite, cconv); } diff --git a/compiler/rustc_codegen_llvm/src/allocator.rs b/compiler/rustc_codegen_llvm/src/allocator.rs index afddb875ec60c..9a0cdf5f77ff0 100644 --- a/compiler/rustc_codegen_llvm/src/allocator.rs +++ b/compiler/rustc_codegen_llvm/src/allocator.rs @@ -118,7 +118,7 @@ fn create_wrapper_function<'ll>( ) { let ty = cx.type_func(args, output.unwrap_or_else(|| cx.type_void())); let llfn = declare_simple_fn( - &cx, + cx, from_name, llvm::CallConv::CCallConv, llvm::UnnamedAddr::Global, @@ -149,11 +149,11 @@ fn create_wrapper_function<'ll>( } let llbb = unsafe { llvm::LLVMAppendBasicBlockInContext(cx.llcx, llfn, c"entry".as_ptr()) }; - let mut bx = SBuilder::build(&cx, llbb); + let mut bx = SBuilder::build(cx, llbb); if let Some(to_name) = to_name { let callee = declare_simple_fn( - &cx, + cx, to_name, llvm::CallConv::CCallConv, llvm::UnnamedAddr::Global, diff --git a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs index 7864d0cc81491..6bc2c4eddf0cf 100644 --- a/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs +++ b/compiler/rustc_codegen_llvm/src/back/llvm_backend.rs @@ -101,7 +101,7 @@ impl WriteBackendMethods for LlvmCodegenBackend { each_linked_rlib_for_lto: &[PathBuf], modules: Vec>, ) -> CompiledModule { - let mut module = back::lto::run_fat( + let module = back::lto::run_fat( cgcx, &sess.prof, shared_emitter, @@ -113,7 +113,7 @@ impl WriteBackendMethods for LlvmCodegenBackend { let dcx = DiagCtxt::new(Box::new(shared_emitter.clone())); let dcx = dcx.handle(); - back::lto::run_pass_manager(cgcx, &sess.prof, dcx, &mut module, false); + back::lto::run_pass_manager(cgcx, &sess.prof, dcx, &module, false); back::write::codegen(cgcx, &sess.prof, shared_emitter, module, &cgcx.module_config) } @@ -397,7 +397,7 @@ impl CodegenBackend for LlvmCodegenBackend { llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatisticsJSON(s) }).unwrap(); if !llvm_stats_json.is_empty() { - if let Err(e) = std::fs::write(&out_path, llvm_stats_json) { + if let Err(e) = std::fs::write(out_path, llvm_stats_json) { sess.dcx().err(format!("failed to write stats to {out_path}: {e}")); } } else { diff --git a/compiler/rustc_codegen_llvm/src/back/lto.rs b/compiler/rustc_codegen_llvm/src/back/lto.rs index 8258c1f7c8d20..d1ce0a3cbcf94 100644 --- a/compiler/rustc_codegen_llvm/src/back/lto.rs +++ b/compiler/rustc_codegen_llvm/src/back/lto.rs @@ -94,12 +94,12 @@ fn prepare_lto( let mut upstream_modules = Vec::new(); for path in each_linked_rlib_for_lto { let archive_data = unsafe { - Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib")) + Mmap::map(std::fs::File::open(path).expect("couldn't open rlib")) .expect("couldn't map rlib") }; let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib"); let metadata_link = - rmeta_link::read(&archive, &archive_data, &path, cgcx.target_is_like_aix).unwrap(); + rmeta_link::read(&archive, &archive_data, path, cgcx.target_is_like_aix).unwrap(); let obj_files = archive .members() .filter_map(|child| { @@ -465,7 +465,7 @@ fn thin_lto( incr_comp_session.new_session_directory.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME) }); - let prev_key_map = if let Some(ref old_incr_comp_session_dir) = incr_comp_session + let prev_key_map = if let Some(old_incr_comp_session_dir) = incr_comp_session .and_then(|incr_comp_session| incr_comp_session.old_session_directory.as_deref()) { let old_path = old_incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME); @@ -548,7 +548,7 @@ pub(crate) fn enable_autodiff_settings(ad: &[config::AutoDiff]) { } config::AutoDiff::PrintTAFn(fun) => { enzyme.set_print_type(true); // Enable general type printing - enzyme.set_print_type_fun(&fun); // Set specific function to analyze + enzyme.set_print_type_fun(fun); // Set specific function to analyze } config::AutoDiff::Inline => { enzyme.set_inline(true); diff --git a/compiler/rustc_codegen_llvm/src/back/write.rs b/compiler/rustc_codegen_llvm/src/back/write.rs index 38f24b465ad66..baa3824f0ee71 100644 --- a/compiler/rustc_codegen_llvm/src/back/write.rs +++ b/compiler/rustc_codegen_llvm/src/back/write.rs @@ -301,7 +301,7 @@ pub(crate) fn save_temp_bitcode( } fn write_bitcode_to_file(module: &ModuleLlvm, path: &Path) { - let path = path_to_c_string(&path); + let path = path_to_c_string(path); module.with_module_refs(|ModuleRefs { llmod, .. }| { unsafe { llvm::LLVMWriteBitcodeToFile(llmod, path.as_ptr()) }; }); @@ -689,7 +689,7 @@ pub(crate) unsafe fn llvm_optimize<'ll>( // Create the new function, with a temporary .offload name to avoid a name collision. let old_fn_name = String::from_utf8(llvm::get_value_name(old_fn)).unwrap(); - let new_fn_name = format!("{}.offload", &old_fn_name); + let new_fn_name = format!("{old_fn_name}.offload"); let new_fn = cx.add_func(&new_fn_name, new_fn_ty); let a0 = llvm::get_param(new_fn, 0); llvm::set_value_name(a0, CString::new("dyn_ptr").unwrap().as_bytes()); @@ -1026,7 +1026,7 @@ pub(crate) fn codegen( .generic_activity_with_arg("LLVM_module_codegen_embed_bitcode", &*module.name); let thin_bc = module.module_llvm.thin_lto_buffer.get().expect("cannot find embedded bitcode"); - embed_bitcode(cgcx, llcx, llmod, &thin_bc); + embed_bitcode(cgcx, llcx, llmod, thin_bc); } } diff --git a/compiler/rustc_codegen_llvm/src/builder.rs b/compiler/rustc_codegen_llvm/src/builder.rs index ead0b28c0f218..cac2b93676134 100644 --- a/compiler/rustc_codegen_llvm/src/builder.rs +++ b/compiler/rustc_codegen_llvm/src/builder.rs @@ -154,7 +154,7 @@ impl<'a, 'll, CX: Borrow>> GenericBuilder<'a, 'll, CX> { llvm::LLVMBuildPointerCast(self.llbuilder(), alloca, self.cx.type_ptr(), UNNAMED) }; if !name.is_empty() { - llvm::set_value_name(val, &name.as_bytes()); + llvm::set_value_name(val, name.as_bytes()); } val } diff --git a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs index 8e680586f569e..3593c31bcedc0 100644 --- a/compiler/rustc_codegen_llvm/src/builder/autodiff.rs +++ b/compiler/rustc_codegen_llvm/src/builder/autodiff.rs @@ -363,7 +363,7 @@ pub(crate) fn generate_enzyme_call<'ll, 'tcx>( match_args_from_caller_to_enzyme(bx, attrs.width, &mut args, &attrs.input_activity, fn_args); if !fnc_tree.args.is_empty() || !fnc_tree.ret.0.is_empty() { - crate::typetree::add_tt(&bx, fn_to_diff, fnc_tree); + crate::typetree::add_tt(bx, fn_to_diff, fnc_tree); } let call = bx.call(enzyme_ty, None, None, ad_fn, ReturnSlot::Direct, &args, None, None); diff --git a/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs index a2b99b032febf..34ba2812ac961 100644 --- a/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs +++ b/compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs @@ -127,7 +127,7 @@ fn generate_launcher<'ll>(cx: &CodegenCx<'ll, '_>) -> (llvm::Value<'ll>, llvm::T let args = vec![tptr, ti64, ti32, ti32, tptr, tptr]; let tgt_fn_ty = cx.type_func(&args, ti32); let name = "__tgt_target_kernel"; - let tgt_decl = declare_offload_fn(&cx, name, tgt_fn_ty); + let tgt_decl = declare_offload_fn(cx, name, tgt_fn_ty); let nounwind = llvm::AttributeKind::NoUnwind.create_attr(cx.llcx); attributes::apply_to_llfn(tgt_decl, Function, &[nounwind]); (tgt_decl, tgt_fn_ty) @@ -141,7 +141,7 @@ pub(crate) fn declare_omp_get_num_devices<'ll>( let ti32 = cx.type_i32(); let tgt_fn_ty = cx.type_func(&[], ti32); let name = "omp_get_num_devices"; - let tgt_decl = declare_offload_fn(&cx, name, tgt_fn_ty); + let tgt_decl = declare_offload_fn(cx, name, tgt_fn_ty); let nounwind = llvm::AttributeKind::NoUnwind.create_attr(cx.llcx); attributes::apply_to_llfn(tgt_decl, Function, &[nounwind]); (tgt_decl, tgt_fn_ty) @@ -157,7 +157,7 @@ pub(crate) fn generate_at_one<'ll>(cx: &CodegenCx<'ll, '_>) -> llvm::Value<'ll> let c_entry_name = CString::new(unknown_txt).unwrap(); let c_val = c_entry_name.as_bytes_with_nul(); let initializer = crate::common::bytes_in_context(cx.llcx, c_val); - let at_zero = add_unnamed_global(&cx, &"", initializer, PrivateLinkage); + let at_zero = add_unnamed_global(cx, "", initializer, PrivateLinkage); llvm::set_alignment(at_zero, Align::ONE); // @1 = private unnamed_addr constant %struct.ident_t { i32 0, i32 2, i32 0, i32 22, ptr @0 }, align 8 @@ -172,7 +172,7 @@ pub(crate) fn generate_at_one<'ll>(cx: &CodegenCx<'ll, '_>) -> llvm::Value<'ll> let struct_elems_ty: Vec<_> = struct_elems.iter().map(|&x| cx.val_ty(x)).collect(); let initializer = crate::common::named_struct(struct_ident_ty, &struct_elems); cx.set_struct_body(struct_ident_ty, &struct_elems_ty); - let at_one = add_unnamed_global(&cx, &"", initializer, PrivateLinkage); + let at_one = add_unnamed_global(cx, "", initializer, PrivateLinkage); llvm::set_alignment(at_one, Align::EIGHT); at_one } @@ -355,9 +355,9 @@ fn gen_tgt_data_mappers<'ll>( let mapper_begin = "__tgt_target_data_begin_mapper"; let mapper_update = "__tgt_target_data_update_mapper"; let mapper_end = "__tgt_target_data_end_mapper"; - let begin_mapper_decl = declare_offload_fn(&cx, mapper_begin, mapper_fn_ty); - let update_mapper_decl = declare_offload_fn(&cx, mapper_update, mapper_fn_ty); - let end_mapper_decl = declare_offload_fn(&cx, mapper_end, mapper_fn_ty); + let begin_mapper_decl = declare_offload_fn(cx, mapper_begin, mapper_fn_ty); + let update_mapper_decl = declare_offload_fn(cx, mapper_update, mapper_fn_ty); + let end_mapper_decl = declare_offload_fn(cx, mapper_end, mapper_fn_ty); let nounwind = llvm::AttributeKind::NoUnwind.create_attr(cx.llcx); attributes::apply_to_llfn(begin_mapper_decl, Function, &[nounwind]); @@ -455,34 +455,34 @@ pub(crate) fn gen_define_handling<'ll>( }) .collect::>(); let offload_sizes = - add_priv_unnamed_arr(&cx, &format!(".offload_sizes.{symbol}"), &actual_sizes); + add_priv_unnamed_arr(cx, &format!(".offload_sizes.{symbol}"), &actual_sizes); let memtransfer_begin = - add_priv_unnamed_arr(&cx, &format!(".offload_maptypes.{symbol}.begin"), &transfer_to); + add_priv_unnamed_arr(cx, &format!(".offload_maptypes.{symbol}.begin"), &transfer_to); let memtransfer_kernel = - add_priv_unnamed_arr(&cx, &format!(".offload_maptypes.{symbol}.kernel"), &transfer_kernel); + add_priv_unnamed_arr(cx, &format!(".offload_maptypes.{symbol}.kernel"), &transfer_kernel); let memtransfer_end = - add_priv_unnamed_arr(&cx, &format!(".offload_maptypes.{symbol}.end"), &transfer_from); + add_priv_unnamed_arr(cx, &format!(".offload_maptypes.{symbol}.end"), &transfer_from); // Next: For each function, generate these three entries. A weak constant, // the llvm.rodata entry name, and the llvm_offload_entries value let name = format!(".{symbol}.region_id"); let initializer = cx.get_const_i8(0); - let region_id = add_global(&cx, &name, initializer, WeakAnyLinkage); + let region_id = add_global(cx, &name, initializer, WeakAnyLinkage); let c_entry_name = CString::new(symbol.clone()).unwrap(); let c_val = c_entry_name.as_bytes_with_nul(); let offload_entry_name = format!(".offloading.entry_name.{symbol}"); let initializer = crate::common::bytes_in_context(cx.llcx, c_val); - let llglobal = add_unnamed_global(&cx, &offload_entry_name, initializer, InternalLinkage); + let llglobal = add_unnamed_global(cx, &offload_entry_name, initializer, InternalLinkage); llvm::set_alignment(llglobal, Align::ONE); llvm::set_section(llglobal, c".llvm.rodata.offloading"); let name = format!(".offloading.entry.{symbol}"); // See the __tgt_offload_entry documentation above. - let elems = TgtOffloadEntry::new(&cx, region_id, llglobal); + let elems = TgtOffloadEntry::new(cx, region_id, llglobal); let initializer = crate::common::named_struct(offload_entry_ty, &elems); let c_name = CString::new(name).unwrap(); @@ -735,7 +735,7 @@ pub(crate) fn gen_call_handling<'ll, 'tcx>( s_ident_t, ); let values = KernelArgsTy::new( - &cx, + cx, num_args, memtransfer_kernel, geps, diff --git a/compiler/rustc_codegen_llvm/src/consts.rs b/compiler/rustc_codegen_llvm/src/consts.rs index 862713876846b..ceef72e2a3dd6 100644 --- a/compiler/rustc_codegen_llvm/src/consts.rs +++ b/compiler/rustc_codegen_llvm/src/consts.rs @@ -216,7 +216,7 @@ fn check_and_apply_linkage<'ll, 'tcx>( { should_sign = true; } - cx.declare_fn(sym, &fn_abi, None) + cx.declare_fn(sym, fn_abi, None) } else { cx.declare_global(sym, cx.type_i8()) } @@ -891,7 +891,7 @@ impl<'ll> CodegenCx<'ll, '_> { let llval = crate::common::named_struct(llty, &[version, size, name, symtab]); let sym = "OBJC_MODULES"; - let g = self.define_global(&sym, llty).unwrap_or_else(|| { + let g = self.define_global(sym, llty).unwrap_or_else(|| { bug!("symbol `{}` is already defined", sym); }); set_global_alignment(self, g, self.tcx.data_layout.pointer_align()); diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 56f0be1a89e2a..3f6d3e9b412f3 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -1160,7 +1160,7 @@ impl<'ll> CodegenCx<'ll, '_> { _ => { let intrinsic = llvm::Intrinsic::lookup(base_name.as_bytes()) .unwrap_or_else(|| bug!("Unknown intrinsic: `{base_name}`")); - let f = intrinsic.get_declaration(self.llmod, &type_params); + let f = intrinsic.get_declaration(self.llmod, type_params); (self.get_type_of_global(f), f) } } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs index b097536080798..33b27c767c3cb 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata.rs @@ -531,7 +531,7 @@ pub(crate) fn spanned_type_di_node<'ll, 'tcx>( // FIXME(mw): Cache this via a regular UniqueTypeId instead of an extra field in the debug context. fn recursion_marker_type_di_node<'ll, 'tcx>(cx: &CodegenCx<'ll, 'tcx>) -> &'ll DIType { - *debug_context(cx).recursion_marker_type.get_or_init(move || { + debug_context(cx).recursion_marker_type.get_or_init(move || { // The choice of type here is pretty arbitrary - // anything reading the debuginfo for a recursive // type is going to see *something* weird - the only 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 c9cac61a8bbe1..2809e588b7635 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/enums/native.rs @@ -369,7 +369,7 @@ fn build_discr_member_di_node<'ll, 'tcx>( Some(create_member_type( cx, containing_scope, - &tag_name, + tag_name, file, UNKNOWN_LINE_NUMBER, layout, diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index bde0e130e748c..fcc0e4818db51 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -251,9 +251,8 @@ impl<'ll, 'tcx> IntrinsicCallBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { if let CVariadicStatus::Unstable { feature } = stability && !self.tcx.features().enabled(feature) { - let msg = - format!("C-variadic function definitions on this target are unstable"); - feature_err(&*self.sess(), feature, span, msg).emit(); + let msg = "C-variadic function definitions on this target are unstable"; + feature_err(self.sess(), feature, span, msg).emit(); } let BackendRepr::Scalar(scalar) = result_layout.backend_repr else { @@ -1808,7 +1807,7 @@ fn codegen_autodiff<'ll, 'tcx>( }; let val_arr = get_args_from_tuple(bx, args[2], fn_diff); - let diff_symbol = symbol_name_for_instance_in_crate(tcx, fn_diff.clone(), LOCAL_CRATE); + let diff_symbol = symbol_name_for_instance_in_crate(tcx, fn_diff, LOCAL_CRATE); let Some(Some(mut diff_attrs)) = find_attr!(tcx, fn_diff.def_id(), RustcAutodiff(attr) => attr.clone()) @@ -1910,7 +1909,7 @@ fn codegen_offload<'ll, 'tcx>( } }; let offload_data = - gpu_offload::gen_define_handling(&cx, &metadata, target_symbol, offload_globals); + gpu_offload::gen_define_handling(cx, &metadata, target_symbol, offload_globals); gpu_offload::gen_call_handling( bx, &offload_data, diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index b9e976f662958..e054eacce5143 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -144,7 +144,7 @@ unsafe fn configure_llvm(sess: &EarlySession) { } for arg in sess_args { - add(&(*arg), true); + add(arg, true); } match ( @@ -528,7 +528,7 @@ pub(crate) fn print(req: &PrintRequest, out: &mut String, sess: &Session) { fn print_target_cpus(sess: &Session, tm: &llvm::TargetMachine, out: &mut String) { let cpu_names = llvm::build_string(|s| unsafe { - llvm::LLVMRustPrintTargetCPUs(&tm, s); + llvm::LLVMRustPrintTargetCPUs(tm, s); }) .unwrap(); @@ -594,7 +594,7 @@ fn print_target_features(sess: &Session, tm: &llvm::TargetMachine, out: &mut Str } // LLVM asserts that these are sorted. LLVM and Rust both use byte comparison for these // strings. - let llvm_feature = to_llvm_features(&sess.target, *feature)?.llvm_feature_name; + let llvm_feature = to_llvm_features(&sess.target, feature)?.llvm_feature_name; let desc = match llvm_target_features.binary_search_by_key(&llvm_feature, |(f, _d)| f).ok() { Some(index) => { diff --git a/compiler/rustc_codegen_llvm/src/typetree.rs b/compiler/rustc_codegen_llvm/src/typetree.rs index 48959a0ae6739..6707ef004dec4 100644 --- a/compiler/rustc_codegen_llvm/src/typetree.rs +++ b/compiler/rustc_codegen_llvm/src/typetree.rs @@ -12,7 +12,7 @@ fn to_enzyme_typetree<'ll>( llcx: llvm::Context<'ll>, ) -> (llvm::TypeTree, Vec) { let mut enzyme_tt = llvm::TypeTree::new(); - let extra_ints = process_typetree_recursive(&mut enzyme_tt, &rust_typetree, &[], llcx); + let extra_ints = process_typetree_recursive(&mut enzyme_tt, rust_typetree, &[], llcx); let mut int_vec = vec![]; for _ in 0..extra_ints { @@ -105,7 +105,7 @@ pub(crate) fn add_tt<'tcx, 'll>(cx: &FullCx<'ll, 'tcx>, fn_def: Value<'ll>, tt: let mut offset = 0; for (i, input) in inputs.iter().enumerate() { - let (enzyme_tt, extra_ints) = to_enzyme_typetree(&input, llvm_data_layout, llcx); + let (enzyme_tt, extra_ints) = to_enzyme_typetree(input, llvm_data_layout, llcx); // This scope is just a visual reminder that we *must* drop the enzyme_wrapper before // we drop any typetrees (mainly enzyme_tt and extra_ints). Drop calls can not accept @@ -116,7 +116,7 @@ pub(crate) fn add_tt<'tcx, 'll>(cx: &FullCx<'ll, 'tcx>, fn_def: Value<'ll>, tt: let enzyme_wrapper = EnzymeWrapper::get_instance(); let c_str = enzyme_wrapper.tree_to_cstr(enzyme_tt.inner); - let attr = llvm::CreateAttrStringValueFromCStr(llcx, &c_attr_name, &c_str); + let attr = llvm::CreateAttrStringValueFromCStr(llcx, &c_attr_name, c_str); let arg_pos = llvm::AttributePlace::Argument(i as u32 + offset); // FIXME(autodiff): We currently know that this is correct for all the cases in which we // call this function. But we should make it more robust for the future. @@ -132,7 +132,7 @@ pub(crate) fn add_tt<'tcx, 'll>(cx: &FullCx<'ll, 'tcx>, fn_def: Value<'ll>, tt: for v in &extra_ints { offset += 1; let c_str = enzyme_wrapper.tree_to_cstr(v.inner); - let int_attr = llvm::CreateAttrStringValueFromCStr(llcx, &c_attr_name, &c_str); + let int_attr = llvm::CreateAttrStringValueFromCStr(llcx, &c_attr_name, c_str); let arg_pos = llvm::AttributePlace::Argument(i as u32 + offset); match tt_location { TTLocation::Definition => { @@ -165,7 +165,7 @@ pub(crate) fn add_tt<'tcx, 'll>(cx: &FullCx<'ll, 'tcx>, fn_def: Value<'ll>, tt: if ret_tt != RustTypeTree::new() { let enzyme_wrapper = EnzymeWrapper::get_instance(); let c_str = enzyme_wrapper.tree_to_cstr(enzyme_tt.inner); - let ret_attr = llvm::CreateAttrStringValueFromCStr(llcx, &c_attr_name, &c_str); + let ret_attr = llvm::CreateAttrStringValueFromCStr(llcx, &c_attr_name, c_str); let arg_pos = llvm::AttributePlace::ReturnValue; match tt_location { TTLocation::Definition => { From 7dc2ea1671a6cdc27795e58ab551c6dfe4e404c3 Mon Sep 17 00:00:00 2001 From: malezjaa Date: Sun, 8 Nov 2026 10:46:17 +0100 Subject: [PATCH 34/39] 6/n: match/if chains changes --- compiler/rustc_codegen_llvm/src/context.rs | 25 +++++++++-------- compiler/rustc_codegen_llvm/src/llvm_util.rs | 28 +++++++------------- 2 files changed, 22 insertions(+), 31 deletions(-) diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 3f6d3e9b412f3..9bef854b940f8 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -516,20 +516,19 @@ fn init_module<'ll, 'tcx>(tcx: TyCtxt<'tcx>, llcx: llvm::Context<'ll>, llmod: ll ); } - match (sess.opts.unstable_opts.small_data_threshold, sess.target.small_data_threshold_support()) + // Set up the small-data optimization limit for architectures that use + // an LLVM module flag to control this. + if let Some(threshold) = sess.opts.unstable_opts.small_data_threshold + && let SmallDataThresholdSupport::LlvmModuleFlag(flag) = + sess.target.small_data_threshold_support() { - // Set up the small-data optimization limit for architectures that use - // an LLVM module flag to control this. - (Some(threshold), SmallDataThresholdSupport::LlvmModuleFlag(flag)) => { - llvm::add_module_flag_u32( - llmod, - llvm::ModuleFlagMergeBehavior::Error, - &flag, - threshold as u32, - ); - } - _ => (), - }; + llvm::add_module_flag_u32( + llmod, + llvm::ModuleFlagMergeBehavior::Error, + &flag, + threshold as u32, + ); + } // Insert `llvm.ident` metadata. // diff --git a/compiler/rustc_codegen_llvm/src/llvm_util.rs b/compiler/rustc_codegen_llvm/src/llvm_util.rs index e054eacce5143..ac0d31fb78b49 100644 --- a/compiler/rustc_codegen_llvm/src/llvm_util.rs +++ b/compiler/rustc_codegen_llvm/src/llvm_util.rs @@ -147,17 +147,14 @@ unsafe fn configure_llvm(sess: &EarlySession) { add(arg, true); } - match ( - sess.opts.unstable_opts.small_data_threshold, - sess.target.small_data_threshold_support(), - ) { - // Set up the small-data optimization limit for architectures that use - // an LLVM argument to control this. - (Some(threshold), SmallDataThresholdSupport::LlvmArg(arg)) => { - add(&format!("--{arg}={threshold}"), false) - } - _ => (), - }; + // Set up the small-data optimization limit for architectures that use + // an LLVM argument to control this. + if let Some(threshold) = sess.opts.unstable_opts.small_data_threshold + && let SmallDataThresholdSupport::LlvmArg(arg) = + sess.target.small_data_threshold_support() + { + add(&format!("--{arg}={threshold}"), false); + } } if sess.opts.unstable_opts.llvm_time_trace { @@ -345,13 +342,8 @@ pub(crate) fn target_config(sess: &EarlySession) -> TargetConfig { // do *not* consider the `-Ctarget-feature`s here (that's why we passed `for_cfg: true` // to `global_llvm_features` above) because that will be handled later in // `internal_target_features`. - if let Some(feat) = to_llvm_features(&sess.target, feature) - && mc_subtarget_info.has_features(feat) - { - true - } else { - false - } + to_llvm_features(&sess.target, feature) + .is_some_and(|feat| mc_subtarget_info.has_features(feat)) }, ); From 1b6892c976747a19b8bb67bd56896a3f09c96257 Mon Sep 17 00:00:00 2001 From: Abhinav Srivastav Date: Tue, 10 Nov 2026 15:18:40 +0530 Subject: [PATCH 35/39] tests: cover MSVC ThinLTO exported symbol preservation --- .../run-make/msvc-lto-preserve-symbols/lib.rs | 21 +++++++ .../msvc-lto-preserve-symbols/rmake.rs | 59 +++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 tests/run-make/msvc-lto-preserve-symbols/lib.rs create mode 100644 tests/run-make/msvc-lto-preserve-symbols/rmake.rs diff --git a/tests/run-make/msvc-lto-preserve-symbols/lib.rs b/tests/run-make/msvc-lto-preserve-symbols/lib.rs new file mode 100644 index 0000000000000..43d55de9a1802 --- /dev/null +++ b/tests/run-make/msvc-lto-preserve-symbols/lib.rs @@ -0,0 +1,21 @@ +#![feature(no_core)] +#![no_core] + +extern crate minicore; + +// Ordinary exported names must not be replaced with their COFF linker +// spellings in the LTO preservation list. +#[no_mangle] +pub extern "C" fn __rust_lto_preserve_plain(x: u32) -> u32 { + x +} + +// Explicit calling-convention decoration must survive both ordinary LTO +// internalization and ThinLTO GUID-based preservation. +#[no_mangle] +pub extern "stdcall" fn rust_lto_preserve_stdcall(a: u32, _: u32) -> u32 { + a +} + +#[no_mangle] +pub static RUST_LTO_PRESERVE_DATA: u32 = 42; diff --git a/tests/run-make/msvc-lto-preserve-symbols/rmake.rs b/tests/run-make/msvc-lto-preserve-symbols/rmake.rs new file mode 100644 index 0000000000000..5eacd7685e1a9 --- /dev/null +++ b/tests/run-make/msvc-lto-preserve-symbols/rmake.rs @@ -0,0 +1,59 @@ +//@ needs-llvm-components: x86 +//@ ignore-backends: gcc + +// Verify that ThinLTO preserves both ordinary LLVM IR names and explicitly +// decorated MSVC symbols. Compile for i686 without requiring the i686 std +// sysroot by using the shared minicore test fixture. + +use std::collections::HashSet; + +use run_make_support::object::read::archive::ArchiveFile; +use run_make_support::object::{File, Object, ObjectSymbol}; +use run_make_support::{path, rfs, rustc, rustc_minicore}; + +fn main() { + rustc_minicore().target("i686-pc-windows-msvc").output("libminicore.rlib").run(); + + rustc() + .input("lib.rs") + .crate_type("staticlib") + .target("i686-pc-windows-msvc") + .extern_("minicore", path("libminicore.rlib")) + .arg("-Clto=thin") + .codegen_units(16) + .arg("-Cpanic=abort") + .opt() + .output("preserve.lib") + .run(); + + let data = rfs::read("preserve.lib"); + let archive = ArchiveFile::parse(&*data).unwrap(); + let mut defined = HashSet::new(); + + for member in archive.members() { + let member = member.unwrap(); + let Ok(bytes) = member.data(&*data) else { + continue; + }; + let Ok(file) = File::parse(bytes) else { + continue; + }; + + for symbol in file.symbols() { + if symbol.is_definition() && symbol.is_global() { + if let Ok(name) = symbol.name() { + defined.insert(name.to_owned()); + } + } + } + } + + for expected in + ["___rust_lto_preserve_plain", "_rust_lto_preserve_stdcall@8", "_RUST_LTO_PRESERVE_DATA"] + { + assert!( + defined.contains(expected), + "ThinLTO did not preserve exported symbol `{expected}`" + ); + } +} From 2160f341b3f49d82d4f3ec73670a9661ed91fea3 Mon Sep 17 00:00:00 2001 From: Bee Date: Thu, 12 Nov 2026 17:55:59 +0000 Subject: [PATCH 36/39] Remove dead code for returning `BackendRepr::Memory` with `PassMode::Direct` --- compiler/rustc_codegen_ssa/src/mir/block.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/compiler/rustc_codegen_ssa/src/mir/block.rs b/compiler/rustc_codegen_ssa/src/mir/block.rs index f5a6575e3c848..2be5ffbe09d1f 100644 --- a/compiler/rustc_codegen_ssa/src/mir/block.rs +++ b/compiler/rustc_codegen_ssa/src/mir/block.rs @@ -603,11 +603,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> { PassMode::Direct(_) | PassMode::Pair(..) => { let op = self.codegen_consume(bx, mir::Place::return_place().as_ref()); - if let Ref(place_val) = op.val { - bx.load_from_place(bx.backend_type(op.layout), place_val) - } else { - op.immediate_or_packed_pair(bx) - } + op.immediate_or_packed_pair(bx) } PassMode::Cast { cast: cast_ty, pad_i32_count: _ } => { From 063cf4cf5ca26aa7d8eb05f12c1cc4421c16fdeb Mon Sep 17 00:00:00 2001 From: Romain Perier Date: Wed, 28 Oct 2026 09:26:41 +0100 Subject: [PATCH 37/39] Reconsider color usage for highlights Currently, we use magenta for highlighting parts of messages: associated-types, some symbols, etc. Switch to BrightCyan, it is the color already used to highlight the help messages, it is also more consistent with the other colors and more visible. --- compiler/rustc_errors/src/emitter.rs | 2 +- .../long-type-E0308.short-color.svg | 14 +++++++------- .../long-type-E0308.shortest-color.svg | 14 +++++++------- tests/ui/error-emitter/E0308-clarification.svg | 10 +++++----- tests/ui/error-emitter/highlighting.rs | 2 +- tests/ui/error-emitter/highlighting.svg | 6 +++--- tests/ui/error-emitter/unicode-output.svg | 6 +++--- ...ence-between-expected-trait-and-found-trait.svg | 7 +++---- ...ighlight-symbols-after-fragment-issue-156458.rs | 4 ++-- ...ghlight-symbols-after-fragment-issue-156458.svg | 4 ++-- 10 files changed, 34 insertions(+), 35 deletions(-) diff --git a/compiler/rustc_errors/src/emitter.rs b/compiler/rustc_errors/src/emitter.rs index b546a15a90be9..e8041796a6195 100644 --- a/compiler/rustc_errors/src/emitter.rs +++ b/compiler/rustc_errors/src/emitter.rs @@ -590,7 +590,7 @@ impl Style { pub(crate) fn anstyle(&self) -> anstyle::Style { match self { Style::NoStyle => anstyle::Style::new(), - Style::Highlight => AnsiColor::Magenta.on_default().effects(Effects::BOLD), + Style::Highlight => AnsiColor::BrightCyan.on_default().effects(Effects::BOLD), } } } diff --git a/tests/ui/associated-types/long-type-E0308.short-color.svg b/tests/ui/associated-types/long-type-E0308.short-color.svg index 203029828b044..a5d29fb21b874 100644 --- a/tests/ui/associated-types/long-type-E0308.short-color.svg +++ b/tests/ui/associated-types/long-type-E0308.short-color.svg @@ -3,8 +3,8 @@ .fg { fill: #AAAAAA } .bg { fill: #000000 } .fg-bright-blue { fill: #5555FF } + .fg-bright-cyan { fill: #55FFFF } .fg-bright-red { fill: #FF5555 } - .fg-magenta { fill: #AA00AA } .container { padding: 0 10px; line-height: 18px; @@ -48,9 +48,9 @@ | - = note: expected associated type `<<<<_ as FooBar>::Wrapper<_> as FooBar>::Assoc as FooBar>::Assoc as FooBar>::Wrapper<_>` + = note: expected associated type `<<<<_ as FooBar>::Wrapper<_> as FooBar>::Assoc as FooBar>::Assoc as FooBar>::Wrapper<_>` - found associated type `<<<<_ as FooBar>::Assoc as FooBar>::Assoc as FooBar>::Assoc as FooBar>::Wrapper<_>` + found associated type `<<<<_ as FooBar>::Assoc as FooBar>::Assoc as FooBar>::Assoc as FooBar>::Wrapper<_>` = note: an associated type was expected, but a different one was found @@ -78,9 +78,9 @@ | - = note: expected associated type `<_ as Bar<u16>>::Assoc` + = note: expected associated type `<_ as Bar<u16>>::Assoc` - found associated type `<_ as Bar<u8>>::Assoc` + found associated type `<_ as Bar<u8>>::Assoc` = note: an associated type was expected, but a different one was found @@ -104,9 +104,9 @@ | - = note: expected associated type `<_ as Qux>::Assoc<u16>` + = note: expected associated type `<_ as Qux>::Assoc<u16>` - found associated type `<_ as Qux>::Assoc<u8>` + found associated type `<_ as Qux>::Assoc<u8>` = note: an associated type was expected, but a different one was found diff --git a/tests/ui/associated-types/long-type-E0308.shortest-color.svg b/tests/ui/associated-types/long-type-E0308.shortest-color.svg index 6812f1ff92186..b864615c43fdf 100644 --- a/tests/ui/associated-types/long-type-E0308.shortest-color.svg +++ b/tests/ui/associated-types/long-type-E0308.shortest-color.svg @@ -3,8 +3,8 @@ .fg { fill: #AAAAAA } .bg { fill: #000000 } .fg-bright-blue { fill: #5555FF } + .fg-bright-cyan { fill: #55FFFF } .fg-bright-red { fill: #FF5555 } - .fg-magenta { fill: #AA00AA } .container { padding: 0 10px; line-height: 18px; @@ -48,9 +48,9 @@ | - = note: expected associated type `<<<<_ as FooBar>::Wrapper<_> as...per<_>` + = note: expected associated type `<<<<_ as FooBar>::Wrapper<_> as...per<_>` - found associated type `<<<<_ as FooBar>::Assoc as Fo...per<_>` + found associated type `<<<<_ as FooBar>::Assoc as Fo...per<_>` = note: an associated type was expected, but a different one was found @@ -78,9 +78,9 @@ | - = note: expected associated type `<_ as Bar<u16>>::Assoc` + = note: expected associated type `<_ as Bar<u16>>::Assoc` - found associated type `<_ as Bar<u8>>::Assoc` + found associated type `<_ as Bar<u8>>::Assoc` = note: an associated type was expected, but a different one was found @@ -104,9 +104,9 @@ | - = note: expected associated type `<_ as Qux>::Assoc<u16>` + = note: expected associated type `<_ as Qux>::Assoc<u16>` - found associated type `<_ as Qux>::Assoc<u8>` + found associated type `<_ as Qux>::Assoc<u8>` = note: an associated type was expected, but a different one was found diff --git a/tests/ui/error-emitter/E0308-clarification.svg b/tests/ui/error-emitter/E0308-clarification.svg index 13ee2fe1a880d..c1191081d601e 100644 --- a/tests/ui/error-emitter/E0308-clarification.svg +++ b/tests/ui/error-emitter/E0308-clarification.svg @@ -3,8 +3,8 @@ .fg { fill: #AAAAAA } .bg { fill: #000000 } .fg-bright-blue { fill: #5555FF } + .fg-bright-cyan { fill: #55FFFF } .fg-bright-red { fill: #FF5555 } - .fg-magenta { fill: #AA00AA } .container { padding: 0 10px; line-height: 18px; @@ -44,9 +44,9 @@ │ - ├ note: expected opaque type `impl Foo` (`u32`) + ├ note: expected opaque type `impl Foo` (`u32`) - │ found opaque type `impl Foo` (`i32`) + │ found opaque type `impl Foo` (`i32`) ╰ note: distinct uses of `impl Trait` result in different opaque types @@ -76,9 +76,9 @@ │ - ├ note: expected opaque type `impl Foo` (`i32`) + ├ note: expected opaque type `impl Foo` (`i32`) - │ found opaque type `impl Foo` (`u32`) + │ found opaque type `impl Foo` (`u32`) ╰ note: distinct uses of `impl Trait` result in different opaque types diff --git a/tests/ui/error-emitter/highlighting.rs b/tests/ui/error-emitter/highlighting.rs index d7a0c9d224665..d49f166866c45 100644 --- a/tests/ui/error-emitter/highlighting.rs +++ b/tests/ui/error-emitter/highlighting.rs @@ -21,4 +21,4 @@ fn main() { query(wrapped_fn); } -//~? RAW for<'a>  +//~? RAW for<'a>  diff --git a/tests/ui/error-emitter/highlighting.svg b/tests/ui/error-emitter/highlighting.svg index c82c7a168643f..23f911a15fc02 100644 --- a/tests/ui/error-emitter/highlighting.svg +++ b/tests/ui/error-emitter/highlighting.svg @@ -3,9 +3,9 @@ .fg { fill: #AAAAAA } .bg { fill: #000000 } .fg-bright-blue { fill: #5555FF } + .fg-bright-cyan { fill: #55FFFF } .fg-bright-green { fill: #55FF55 } .fg-bright-red { fill: #FF5555 } - .fg-magenta { fill: #AA00AA } .container { padding: 0 10px; line-height: 18px; @@ -37,9 +37,9 @@ | - = note: expected fn pointer `for<'a> fn(Box<(dyn Any + Send + 'a)>) -> Pin<_>` + = note: expected fn pointer `for<'a> fn(Box<(dyn Any + Send + 'a)>) -> Pin<_>` - found fn item `fn(Box<(dyn Any + Send + 'static)>) -> Pin<_> {wrapped_fn}` + found fn item `fn(Box<(dyn Any + Send + 'static)>) -> Pin<_> {wrapped_fn}` note: function defined here diff --git a/tests/ui/error-emitter/unicode-output.svg b/tests/ui/error-emitter/unicode-output.svg index 5623421ab7886..6c95b6d23623a 100644 --- a/tests/ui/error-emitter/unicode-output.svg +++ b/tests/ui/error-emitter/unicode-output.svg @@ -3,9 +3,9 @@ .fg { fill: #AAAAAA } .bg { fill: #000000 } .fg-bright-blue { fill: #5555FF } + .fg-bright-cyan { fill: #55FFFF } .fg-bright-green { fill: #55FF55 } .fg-bright-red { fill: #FF5555 } - .fg-magenta { fill: #AA00AA } .container { padding: 0 10px; line-height: 18px; @@ -37,9 +37,9 @@ │ - ╰ note: expected fn pointer `for<'a> fn(Box<(dyn Any + Send + 'a)>) -> Pin<_>` + ╰ note: expected fn pointer `for<'a> fn(Box<(dyn Any + Send + 'a)>) -> Pin<_>` - found fn item `fn(Box<(dyn Any + Send + 'static)>) -> Pin<_> {wrapped_fn}` + found fn item `fn(Box<(dyn Any + Send + 'static)>) -> Pin<_> {wrapped_fn}` note: function defined here diff --git a/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg index e3faf4315ff98..f8be2e7f1d4ab 100644 --- a/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg +++ b/tests/ui/impl-trait/diagnostics/highlight-difference-between-expected-trait-and-found-trait.svg @@ -6,7 +6,6 @@ .fg-bright-cyan { fill: #55FFFF } .fg-bright-green { fill: #55FF55 } .fg-bright-red { fill: #FF5555 } - .fg-magenta { fill: #AA00AA } .container { padding: 0 10px; line-height: 18px; @@ -38,9 +37,9 @@ | - help: the trait `Bar<i32>` is not implemented for `Struct` + help: the trait `Bar<i32>` is not implemented for `Struct` - but trait `Bar<()>` is implemented for it + but trait `Bar<()>` is implemented for it --> $DIR/highlight-difference-between-expected-trait-and-found-trait.rs:13:1 @@ -50,7 +49,7 @@ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ - = help: for that trait implementation, expected `()`, found `i32` + = help: for that trait implementation, expected `()`, found `i32` note: required for `Struct` to implement `Foo<i32>` diff --git a/tests/ui/macros/highlight-symbols-after-fragment-issue-156458.rs b/tests/ui/macros/highlight-symbols-after-fragment-issue-156458.rs index 98de393cc81aa..fdc00cd66980b 100644 --- a/tests/ui/macros/highlight-symbols-after-fragment-issue-156458.rs +++ b/tests/ui/macros/highlight-symbols-after-fragment-issue-156458.rs @@ -1,4 +1,4 @@ -// Make sure accepted characters in the macro syntax warning message is highlighted in magenta. +// Make sure accepted characters in the macro syntax warning message is highlighted in bright cyan. //@ compile-flags: --error-format=human --color=always //@ edition:2018 @@ -9,4 +9,4 @@ macro_rules! m { fn main() {} -//~? RAW `=>`, `,` or `;` +//~? RAW `=>`, `,` or `;` diff --git a/tests/ui/macros/highlight-symbols-after-fragment-issue-156458.svg b/tests/ui/macros/highlight-symbols-after-fragment-issue-156458.svg index 9b665a1c45aea..3b6bcf9c2f452 100644 --- a/tests/ui/macros/highlight-symbols-after-fragment-issue-156458.svg +++ b/tests/ui/macros/highlight-symbols-after-fragment-issue-156458.svg @@ -3,8 +3,8 @@ .fg { fill: #AAAAAA } .bg { fill: #000000 } .fg-bright-blue { fill: #5555FF } + .fg-bright-cyan { fill: #55FFFF } .fg-bright-red { fill: #FF5555 } - .fg-magenta { fill: #AA00AA } .container { padding: 0 10px; line-height: 18px; @@ -32,7 +32,7 @@ | - = note: allowed there are: `=>`, `,` or `;` + = note: allowed there are: `=>`, `,` or `;` From ec75541c7162b734b43d38ae421a708e192e3867 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Wed, 11 Nov 2026 17:29:35 +0000 Subject: [PATCH 38/39] Tweak crate errors wording --- compiler/rustc_metadata/src/creader.rs | 12 +- compiler/rustc_metadata/src/diagnostics.rs | 166 ++++++++++++------ compiler/rustc_metadata/src/locator.rs | 3 - tests/run-make/export/extern-opt/rmake.rs | 2 +- tests/ui/allocator/two-allocators2.rs | 2 +- tests/ui/allocator/two-allocators2.stderr | 2 +- tests/ui/allocator/two-allocators3.rs | 2 +- tests/ui/allocator/two-allocators3.stderr | 2 +- .../async-drop-run-without-feature.stderr | 4 +- .../async-drop/dependency-dropped.rs | 2 +- .../dependency-dropped.without_feature.stderr | 4 +- tests/ui/error-codes/E0462.stderr | 4 +- tests/ui/error-codes/E0519.stderr | 4 +- .../ui/errors/issue-104621-extern-bad-file.rs | 6 +- .../issue-104621-extern-bad-file.stderr | 10 +- .../ui/errors/issue-104621-extern-not-file.rs | 2 +- .../issue-104621-extern-not-file.stderr | 2 +- tests/ui/extern-flag/empty-extern-arg.rs | 2 +- tests/ui/extern-flag/empty-extern-arg.stderr | 2 +- tests/ui/imports/resolve-other-libc.rs | 2 +- tests/ui/imports/resolve-other-libc.stderr | 2 +- tests/ui/missing/missing-allocator.stderr | 4 +- 22 files changed, 144 insertions(+), 97 deletions(-) diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 70302bbef51cb..a8de7356669b4 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -818,13 +818,10 @@ impl CStore { } Err(err) => { debug!("failed to resolve crate {} {:?}", name, dep_kind); - // crate maybe injrected with `standard_library_imports::inject`, their span is dummy. - // we ignore compiler-injected prelude/sysroot loads here so they don't suppress - // unrelated diagnostics, such as `unsupported targets for std library` etc, - // these maybe helpful for users to resolve crate loading failure. - if !tcx.sess.dcx().has_errors().is_some() && !span.is_dummy() { - self.has_crate_resolve_with_fail = true; - } + // Crate maybe injected with `standard_library_imports::inject`, its span is + // dummy. We ignore compiler-injected prelude/sysroot loads here so they don't + // suppress unrelated diagnostics, such as "unsupported targets for std library" + // etc., these may be helpful for users to resolve crate loading failure. let missing_core = self .maybe_resolve_crate( tcx, @@ -1213,6 +1210,7 @@ impl CStore { tcx.dcx().emit_err(diagnostics::ConflictingGlobalAlloc { crate_name: data.name(), other_crate_name: other_crate, + this_crate: other_crate == this_crate, }); } None => global_allocator = Some(data.name()), diff --git a/compiler/rustc_metadata/src/diagnostics.rs b/compiler/rustc_metadata/src/diagnostics.rs index 1060423523e5c..21091ef70d3c8 100644 --- a/compiler/rustc_metadata/src/diagnostics.rs +++ b/compiler/rustc_metadata/src/diagnostics.rs @@ -72,7 +72,8 @@ pub(crate) struct BadPanicStrategy { #[derive(Diagnostic)] #[diag( - "the crate `{$crate_name}` requires panic strategy `{$found_strategy}` which is incompatible with this crate's strategy of `{$desired_strategy}`" + "the crate `{$crate_name}` requires panic strategy `{$found_strategy}` which is incompatible \ + with this crate's strategy of `{$desired_strategy}`" )] pub(crate) struct RequiredPanicStrategy { pub crate_name: Symbol, @@ -82,7 +83,8 @@ pub(crate) struct RequiredPanicStrategy { #[derive(Diagnostic)] #[diag( - "the crate `{$crate_name}` was compiled with a panic strategy which is incompatible with `immediate-abort`" + "the crate `{$crate_name}` was compiled with a panic strategy which is incompatible with \ + `immediate-abort`" )] pub(crate) struct IncompatibleWithImmediateAbort { pub crate_name: Symbol, @@ -90,13 +92,15 @@ pub(crate) struct IncompatibleWithImmediateAbort { #[derive(Diagnostic)] #[diag( - "the crate `core` was compiled with a panic strategy which is incompatible with `immediate-abort`" + "the crate `core` was compiled with a panic strategy which is incompatible with \ + `immediate-abort`" )] pub(crate) struct IncompatibleWithImmediateAbortCore; #[derive(Diagnostic)] #[diag( - "the crate `{$crate_name}` is compiled with the panic-in-drop strategy `{$found_strategy}` which is incompatible with this crate's strategy of `{$desired_strategy}`" + "the crate `{$crate_name}` is compiled with the panic-in-drop strategy `{$found_strategy}` \ + which is incompatible with this crate's strategy of `{$desired_strategy}`" )] pub(crate) struct IncompatiblePanicInDropStrategy { pub crate_name: Symbol, @@ -123,7 +127,8 @@ pub(crate) struct EmptyRenamingTarget<'a> { #[derive(Diagnostic)] #[diag( - "renaming of the library `{$lib_name}` was specified, however this crate contains no `#[link(...)]` attributes referencing this library" + "renaming of the library `{$lib_name}` was specified, however this crate contains no \ + `#[link(...)]` attributes referencing this library" )] pub(crate) struct RenamingNoLink<'a> { pub lib_name: &'a str, @@ -211,16 +216,21 @@ pub(crate) struct NoMultipleAllocErrorHandler { #[derive(Diagnostic)] #[diag( - "the `#[global_allocator]` in {$other_crate_name} conflicts with global allocator in: {$crate_name}" + "the `#[global_allocator]` in {$this_crate -> + [true] this crate + *[false] `{$other_crate_name}` + } conflicts with global allocator in `{$crate_name}`" )] pub(crate) struct ConflictingGlobalAlloc { pub crate_name: Symbol, pub other_crate_name: Symbol, + pub this_crate: bool, } #[derive(Diagnostic)] #[diag( - "the `#[alloc_error_handler]` in {$other_crate_name} conflicts with allocation error handler in: {$crate_name}" + "the `#[alloc_error_handler]` in `{$other_crate_name}` conflicts with allocation error handler \ + in `{$crate_name}`" )] pub(crate) struct ConflictingAllocErrorHandler { pub crate_name: Symbol, @@ -228,20 +238,22 @@ pub(crate) struct ConflictingAllocErrorHandler { } #[derive(Diagnostic)] -#[diag( - "no global memory allocator found but one is required; link to std or add `#[global_allocator]` to a static item that implements the GlobalAlloc trait" +#[diag("no global memory allocator found but one is required")] +#[help( + "link to std or add `#[global_allocator]` to a static item that implements the `GlobalAlloc` \ + trait" )] pub(crate) struct GlobalAllocRequired; #[derive(Diagnostic)] -#[diag("failed to write {$filename}: {$err}")] +#[diag("failed to write `{$filename}`: {$err}")] pub(crate) struct FailedWriteError { pub filename: PathBuf, pub err: Error, } #[derive(Diagnostic)] -#[diag("failed to copy {$filename} to stdout: {$err}")] +#[diag("failed to copy `{$filename}` to stdout: {$err}")] pub(crate) struct FailedCopyToStdout { pub filename: PathBuf, pub err: Error, @@ -249,7 +261,8 @@ pub(crate) struct FailedCopyToStdout { #[derive(Diagnostic)] #[diag( - "option `-o` or `--emit` is used to write binary output type `metadata` to stdout, but stdout is a tty" + "option `-o` or `--emit` is used to write binary output type `metadata` to stdout, but stdout \ + is a tty" )] pub(crate) struct BinaryOutputToTty; @@ -260,7 +273,7 @@ pub(crate) struct FailedCreateTempdir { } #[derive(Diagnostic)] -#[diag("failed to create the file {$filename}: {$err}")] +#[diag("failed to create the file `{$filename}`: {$err}")] pub(crate) struct FailedCreateFile<'a> { pub filename: &'a Path, pub err: Error, @@ -281,7 +294,7 @@ pub(crate) struct NonAsciiName { } #[derive(Diagnostic)] -#[diag("extern location for {$crate_name} does not exist: {$location}")] +#[diag("extern location for `{$crate_name}` does not exist at `{$location}`")] pub(crate) struct ExternLocationNotExist<'a> { #[primary_span] pub span: Span, @@ -290,7 +303,7 @@ pub(crate) struct ExternLocationNotExist<'a> { } #[derive(Diagnostic)] -#[diag("extern location for {$crate_name} is not a file: {$location}")] +#[diag("extern location for `{$crate_name}` is not a file: `{$location}`")] pub(crate) struct ExternLocationNotFile<'a> { #[primary_span] pub span: Span, @@ -324,9 +337,8 @@ impl Diagnostic<'_> for MultipleCandidates { } #[derive(Diagnostic)] -#[diag( - "only metadata stub found for `{$flavor}` dependency `{$crate_name}`. Please provide path to the corresponding .rmeta file with full metadata" -)] +#[diag("only metadata stub found for `{$flavor}` dependency `{$crate_name}`")] +#[help("provide path to the corresponding `.rmeta` file with full metadata")] pub(crate) struct FullMetadataNotFound { #[primary_span] pub span: Span, @@ -335,7 +347,11 @@ pub(crate) struct FullMetadataNotFound { } #[derive(Diagnostic)] -#[diag("the current crate is indistinguishable from one of its dependencies: it has the same crate-name `{$crate_name}` and was compiled with the same `-C metadata` arguments, so this will result in symbol conflicts between the two", code = E0519)] +#[diag("the current crate is indistinguishable from one of its dependencies", code = E0519)] +#[note( + "it has the same name `{$crate_name}` and was compiled with the same `-C metadata` arguments, \ + so this will result in symbol conflicts between the two" +)] pub(crate) struct SymbolConflictsCurrent { #[primary_span] pub span: Span, @@ -343,7 +359,7 @@ pub(crate) struct SymbolConflictsCurrent { } #[derive(Diagnostic)] -#[diag("found crates (`{$crate_name0}` and `{$crate_name1}`) with colliding StableCrateId values")] +#[diag("found crates `{$crate_name0}` and `{$crate_name1}` with colliding `StableCrateId` values")] pub(crate) struct StableCrateIdCollision { #[primary_span] pub span: Span, @@ -373,7 +389,10 @@ pub(crate) struct NewerCrateVersion { } #[derive(Diagnostic)] -#[diag("couldn't find crate `{$crate_name}` with expected target triple {$locator_triple}{$add_info}", code = E0461)] +#[diag( + "couldn't find crate `{$crate_name}` with expected target triple {$locator_triple}{$add_info}", + code = E0461 +)] #[note("the following crate versions were found:{$found_crates}")] pub(crate) struct NoCrateWithTriple<'a> { #[primary_span] @@ -385,9 +404,9 @@ pub(crate) struct NoCrateWithTriple<'a> { } #[derive(Diagnostic)] -#[diag("found staticlib `{$crate_name}` instead of rlib or dylib{$add_info}", code = E0462)] +#[diag("found staticlib `{$crate_name}` instead of `rlib` or `dylib`{$add_info}", code = E0462)] #[note("the following crate versions were found:{$found_crates}")] -#[help("please recompile that crate using --crate-type lib")] +#[help("please recompile that crate using `--crate-type lib`")] pub(crate) struct FoundStaticlib { #[primary_span] pub span: Span, @@ -397,10 +416,14 @@ pub(crate) struct FoundStaticlib { } #[derive(Diagnostic)] -#[diag("found crate `{$crate_name}` compiled by an incompatible version of rustc{$add_info}", code = E0514)] +#[diag( + "found crate `{$crate_name}` compiled by an incompatible version of rustc{$add_info}", + code = E0514 +)] #[note("the following crate versions were found:{$found_crates}")] #[help( - "please recompile that crate using this compiler ({$rustc_version}) (consider running `cargo clean` first)" + "please recompile that crate using this compiler ({$rustc_version}) \ + (consider running `cargo clean` first)" )] pub(crate) struct IncompatibleRustc { #[primary_span] @@ -475,7 +498,10 @@ impl Diagnostic<'_> for CannotFindCrate { if self.missing_core { if env!("CFG_RELEASE_CHANNEL") == "dev" && !self.is_ui_testing { // Note: Emits the nicer suggestion only for the dev channel. - diag.help(msg!("consider adding the standard library to the sysroot with `x build library --target {$locator_triple}`")); + diag.help(msg!( + "consider adding the standard library to the sysroot with \ + `x build library --target {$locator_triple}`" + )); } else if has_precompiled_std { // NOTE: this suggests using rustup, even though the user may not have it installed. // That's because they could choose to install it; or this may give them a hint which @@ -491,17 +517,31 @@ impl Diagnostic<'_> for CannotFindCrate { // If it's not a dummy, that means someone added `extern crate std` explicitly and // `#![no_std]` won't help. if !self.missing_core && self.span.is_dummy() { - diag.note(msg!("`std` is required by `{$current_crate}` because it does not declare `#![no_std]`")); + diag.note(msg!( + "`std` is required by `{$current_crate}` because it does not declare \ + `#![no_std]`" + )); } // Recommend -Zbuild-std even on stable builds for Tier 3 targets because // it's the recommended way to use the target, the user should switch to nightly. if self.is_nightly_build || !has_precompiled_std { - diag.help(msg!("consider building the standard library from source with `cargo build -Zbuild-std`")); + diag.help(msg!( + "consider building the standard library from source with \ + `cargo build -Zbuild-std`" + )); } } else if self.crate_name == self.profiler_runtime { diag.note(msg!("the compiler may have been built without the profiler runtime")); } else if self.crate_name.as_str().starts_with("rustc_") { - diag.help(msg!("maybe you need to install the missing components with: `rustup component add rust-src rustc-dev llvm-tools-preview`")); + diag.help(msg!( + "maybe you need to install the missing components with: \ + `rustup component add rust-src rustc-dev llvm-tools-preview`" + )); + } else if rustc_session::utils::was_invoked_from_cargo() { + diag.note(msg!( + "check the `[dependencies]` section in `Cargo.toml` for the missing crate or use \ + `cargo add {$crate_name}` to add it to your `Cargo.toml`" + )); } diag.span_label(self.span, msg!("can't find crate")); diag @@ -509,26 +549,21 @@ impl Diagnostic<'_> for CannotFindCrate { } #[derive(Diagnostic)] -#[diag("extern location for {$crate_name} is of an unknown type: {$path}")] +#[diag("extern location for `{$crate_name}` is of an unknown type at `{$path}`")] +#[help("file name should be `lib*.rlib` or `{$dll_prefix}*{$dll_suffix}`")] pub(crate) struct CrateLocationUnknownType<'a> { #[primary_span] pub span: Span, pub path: &'a Path, pub crate_name: Symbol, -} - -#[derive(Diagnostic)] -#[diag("file name should be lib*.rlib or {$dll_prefix}*{$dll_suffix}")] -pub(crate) struct LibFilenameForm<'a> { - #[primary_span] - pub span: Span, pub dll_prefix: &'a str, pub dll_suffix: &'a str, } #[derive(Diagnostic)] #[diag( - "older versions of the `wasm-bindgen` crate are incompatible with current versions of Rust; please update to `wasm-bindgen` v0.2.88" + "older versions of the `wasm-bindgen` crate are incompatible with current versions of Rust; \ + please update to `wasm-bindgen` v0.2.88" )] pub(crate) struct WasmCAbi { #[primary_span] @@ -538,16 +573,20 @@ pub(crate) struct WasmCAbi { #[derive(Diagnostic)] #[diag("mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}`")] #[help( - "the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely" + "the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different \ + values of this flag cannot be used together safely" )] #[note( - "`{$flag_name_prefixed}={$local_value}` in this crate is incompatible with `{$flag_name_prefixed}={$extern_value}` in dependency `{$extern_crate}`" + "`{$flag_name_prefixed}={$local_value}` in this crate is incompatible with \ + `{$flag_name_prefixed}={$extern_value}` in dependency `{$extern_crate}`" )] #[help( - "set `{$flag_name_prefixed}={$extern_value}` in this crate or `{$flag_name_prefixed}={$local_value}` in `{$extern_crate}`" + "set `{$flag_name_prefixed}={$extern_value}` in this crate or \ + `{$flag_name_prefixed}={$local_value}` in `{$extern_crate}`" )] #[help( - "if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error" + "if you are sure this will not cause problems, you may use \ + `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error" )] pub(crate) struct IncompatibleTargetModifiers { pub extern_crate: Symbol, @@ -561,7 +600,8 @@ pub(crate) struct IncompatibleTargetModifiers { #[derive(Diagnostic)] #[diag("mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}`")] #[help( - "the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely" + "the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different \ + values of this flag cannot be used together safely" )] #[note( "`{$flag_name_prefixed}` is unset in this crate which is incompatible with {$has_extern_value -> @@ -576,7 +616,8 @@ pub(crate) struct IncompatibleTargetModifiers { } in this crate or unset `{$flag_name_prefixed}` in `{$extern_crate}`" )] #[help( - "if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error" + "if you are sure this will not cause problems, you may use \ + `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error" )] pub(crate) struct IncompatibleTargetModifiersLMissed { pub extern_crate: Symbol, @@ -590,13 +631,15 @@ pub(crate) struct IncompatibleTargetModifiersLMissed { #[derive(Diagnostic)] #[diag("mixing `{$flag_name_prefixed}` will cause an ABI mismatch in crate `{$local_crate}`")] #[help( - "the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different values of this flag cannot be used together safely" + "the `{$flag_name_prefixed}` flag modifies the ABI so Rust crates compiled with different \ + values of this flag cannot be used together safely" )] #[note( "{$has_local_value -> [false] `{$flag_name_prefixed}` being set *[other] `{$flag_name_prefixed}={$local_value}` - } in this crate is incompatible with `{$flag_name_prefixed}` being unset in dependency `{$extern_crate}`" + } in this crate is incompatible with `{$flag_name_prefixed}` being unset in dependency \ + `{$extern_crate}`" )] #[help( "unset `{$flag_name_prefixed}` in this crate or set {$has_local_value -> @@ -605,7 +648,8 @@ pub(crate) struct IncompatibleTargetModifiersLMissed { } in `{$extern_crate}`" )] #[help( - "if you are sure this will not cause problems, you may use `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error" + "if you are sure this will not cause problems, you may use \ + `-Cunsafe-allow-abi-mismatch={$flag_name}` to silence this error" )] pub(crate) struct IncompatibleTargetModifiersRMissed { pub extern_crate: Symbol, @@ -618,7 +662,8 @@ pub(crate) struct IncompatibleTargetModifiersRMissed { #[derive(Diagnostic)] #[diag( - "unknown target modifier `{$flag_name}`, requested by `-Cunsafe-allow-abi-mismatch={$flag_name}`" + "unknown target modifier `{$flag_name}`, requested by \ + `-Cunsafe-allow-abi-mismatch={$flag_name}`" )] pub(crate) struct UnknownTargetModifierUnsafeAllowed { pub flag_name: String, @@ -626,10 +671,12 @@ pub(crate) struct UnknownTargetModifierUnsafeAllowed { #[derive(Diagnostic)] #[diag( - "found async drop types in dependency `{$extern_crate}`, but async_drop feature is disabled for `{$local_crate}`" + "found async drop types in dependency `{$extern_crate}`, but `async_drop` feature is disabled \ + for `{$local_crate}`" )] #[help( - "if async drop type will be dropped in a crate without `feature(async_drop)`, sync Drop will be used" + "if async drop type will be dropped in a crate without `feature(async_drop)`, sync `Drop` will \ + be used" )] pub(crate) struct AsyncDropTypesInDependency { #[primary_span] @@ -655,13 +702,17 @@ pub(crate) struct UnusedCrateDependency { #[derive(Diagnostic)] #[diag( - "your program uses the crate `{$extern_crate}`, that is not compiled with `{$mitigation_name}{$mitigation_level}` enabled" + "your program uses the crate `{$extern_crate}`, that is not compiled with \ + `{$mitigation_name}{$mitigation_level}` enabled" )] #[note( - "recompile `{$extern_crate}` with `{$mitigation_name}{$mitigation_level}` enabled, or use `-Z allow-partial-mitigations={$mitigation_name}` to allow creating an artifact that has the mitigation partially enabled " + "recompile `{$extern_crate}` with `{$mitigation_name}{$mitigation_level}` enabled, or use \ + `-Z allow-partial-mitigations={$mitigation_name}` to allow creating an artifact that has the \ + mitigation partially enabled" )] #[help( - "it is possible to disable `-Z allow-partial-mitigations={$mitigation_name}` via `-Z deny-partial-mitigations={$mitigation_name}`" + "it is possible to disable `-Z allow-partial-mitigations={$mitigation_name}` via \ + `-Z deny-partial-mitigations={$mitigation_name}`" )] pub(crate) struct MitigationLessStrictInDependency { pub mitigation_name: String, @@ -671,15 +722,16 @@ pub(crate) struct MitigationLessStrictInDependency { #[derive(Diagnostic)] pub(crate) enum StaticLinkingNotSupported<'a> { - #[diag( - "static linking of `{$lib_name}` is not supported on `{$target}`; using dynamic linking instead" - )] + #[diag("static linking of `{$lib_name}` is not supported on `{$target}`")] + #[note("using dynamic linking instead")] #[help("remove `kind = \"static\"` and ensure a shared library is available")] UserRequested { lib_name: Symbol, target: &'a str }, #[diag( - "library `{$lib_name}` is linked statically by a dependency, but `{$target}` requires dynamic linking; using dynamic linking instead" + "library `{$lib_name}` is linked statically by a dependency, but `{$target}` requires \ + dynamic linking" )] + #[note("using dynamic linking instead")] #[help("ensure a shared library is available")] FromDependency { lib_name: Symbol, target: &'a str }, } diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 38da6561ecb38..67eab19521cb0 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -1138,9 +1138,6 @@ impl CrateError { span, path, crate_name, - }); - dcx.emit_err(diagnostics::LibFilenameForm { - span, dll_prefix: &locator.dll_prefix, dll_suffix: &locator.dll_suffix, }); diff --git a/tests/run-make/export/extern-opt/rmake.rs b/tests/run-make/export/extern-opt/rmake.rs index 2e3a70b251c65..142a8cff7a850 100644 --- a/tests/run-make/export/extern-opt/rmake.rs +++ b/tests/run-make/export/extern-opt/rmake.rs @@ -21,5 +21,5 @@ fn main() { .extern_("libr", "interface.rs") // wrong interface format .extern_("libr", dynamic_lib_name("libr")) .run_fail() - .assert_stderr_contains("extern location for libr does not exist"); + .assert_stderr_contains("extern location for `libr` does not exist"); } diff --git a/tests/ui/allocator/two-allocators2.rs b/tests/ui/allocator/two-allocators2.rs index 6efb297054bca..20a0f6aef860b 100644 --- a/tests/ui/allocator/two-allocators2.rs +++ b/tests/ui/allocator/two-allocators2.rs @@ -10,4 +10,4 @@ static A: System = System; fn main() {} -//~? ERROR the `#[global_allocator]` in this crate conflicts with global allocator in: system_allocator +//~? ERROR the `#[global_allocator]` in this crate conflicts with global allocator in `system_allocator` diff --git a/tests/ui/allocator/two-allocators2.stderr b/tests/ui/allocator/two-allocators2.stderr index f1e4b093cc6db..a1aefb80248e9 100644 --- a/tests/ui/allocator/two-allocators2.stderr +++ b/tests/ui/allocator/two-allocators2.stderr @@ -1,4 +1,4 @@ -error: the `#[global_allocator]` in this crate conflicts with global allocator in: system_allocator +error: the `#[global_allocator]` in this crate conflicts with global allocator in `system_allocator` error: aborting due to 1 previous error diff --git a/tests/ui/allocator/two-allocators3.rs b/tests/ui/allocator/two-allocators3.rs index 3aba96068de9c..6be7cbae51c13 100644 --- a/tests/ui/allocator/two-allocators3.rs +++ b/tests/ui/allocator/two-allocators3.rs @@ -7,4 +7,4 @@ extern crate system_allocator2; fn main() {} -//~? ERROR the `#[global_allocator]` in system_allocator conflicts with global allocator in: system_allocator2 +//~? ERROR the `#[global_allocator]` in `system_allocator` conflicts with global allocator in `system_allocator2` diff --git a/tests/ui/allocator/two-allocators3.stderr b/tests/ui/allocator/two-allocators3.stderr index bf0f3a7c637a8..991e8f8beaded 100644 --- a/tests/ui/allocator/two-allocators3.stderr +++ b/tests/ui/allocator/two-allocators3.stderr @@ -1,4 +1,4 @@ -error: the `#[global_allocator]` in system_allocator conflicts with global allocator in: system_allocator2 +error: the `#[global_allocator]` in `system_allocator` conflicts with global allocator in `system_allocator2` error: aborting due to 1 previous error diff --git a/tests/ui/async-await/async-drop/async-drop-run-without-feature/async-drop-run-without-feature.stderr b/tests/ui/async-await/async-drop/async-drop-run-without-feature/async-drop-run-without-feature.stderr index 70eca25edcbc0..8ed58f62da319 100644 --- a/tests/ui/async-await/async-drop/async-drop-run-without-feature/async-drop-run-without-feature.stderr +++ b/tests/ui/async-await/async-drop/async-drop-run-without-feature/async-drop-run-without-feature.stderr @@ -1,10 +1,10 @@ -warning: found async drop types in dependency `async_drop_crate_dep`, but async_drop feature is disabled for `async_drop_run_without_feature` +warning: found async drop types in dependency `async_drop_crate_dep`, but `async_drop` feature is disabled for `async_drop_run_without_feature` --> $DIR/async-drop-run-without-feature.rs:6:1 | LL | use std::{ | ^ | - = help: if async drop type will be dropped in a crate without `feature(async_drop)`, sync Drop will be used + = help: if async drop type will be dropped in a crate without `feature(async_drop)`, sync `Drop` will be used warning: 1 warning emitted diff --git a/tests/ui/async-await/async-drop/dependency-dropped.rs b/tests/ui/async-await/async-drop/dependency-dropped.rs index d7f415e19aadf..d6543c80b2aa8 100644 --- a/tests/ui/async-await/async-drop/dependency-dropped.rs +++ b/tests/ui/async-await/async-drop/dependency-dropped.rs @@ -5,7 +5,7 @@ //@ edition:2021 #![cfg_attr(with_feature, feature(async_drop))] -//[without_feature]~^ WARN found async drop types in dependency `async_drop_dep`, but async_drop feature is disabled for `dependency_dropped` +//[without_feature]~^ WARN found async drop types in dependency `async_drop_dep`, but `async_drop` feature is disabled for `dependency_dropped` #![allow(incomplete_features)] diff --git a/tests/ui/async-await/async-drop/dependency-dropped.without_feature.stderr b/tests/ui/async-await/async-drop/dependency-dropped.without_feature.stderr index 96a4572055c60..9d8b449bb4c43 100644 --- a/tests/ui/async-await/async-drop/dependency-dropped.without_feature.stderr +++ b/tests/ui/async-await/async-drop/dependency-dropped.without_feature.stderr @@ -1,10 +1,10 @@ -warning: found async drop types in dependency `async_drop_dep`, but async_drop feature is disabled for `dependency_dropped` +warning: found async drop types in dependency `async_drop_dep`, but `async_drop` feature is disabled for `dependency_dropped` --> $DIR/dependency-dropped.rs:7:1 | LL | #![cfg_attr(with_feature, feature(async_drop))] | ^ | - = help: if async drop type will be dropped in a crate without `feature(async_drop)`, sync Drop will be used + = help: if async drop type will be dropped in a crate without `feature(async_drop)`, sync `Drop` will be used warning: 1 warning emitted diff --git a/tests/ui/error-codes/E0462.stderr b/tests/ui/error-codes/E0462.stderr index be32001fad46f..69085eeee1c4c 100644 --- a/tests/ui/error-codes/E0462.stderr +++ b/tests/ui/error-codes/E0462.stderr @@ -1,4 +1,4 @@ -error[E0462]: found staticlib `found_staticlib` instead of rlib or dylib +error[E0462]: found staticlib `found_staticlib` instead of `rlib` or `dylib` --> $DIR/E0462.rs:7:1 | LL | extern crate found_staticlib; @@ -6,7 +6,7 @@ LL | extern crate found_staticlib; | = note: the following crate versions were found: crate `found_staticlib`: $TEST_BUILD_DIR/auxiliary/libfound_staticlib.somelib - = help: please recompile that crate using --crate-type lib + = help: please recompile that crate using `--crate-type lib` error: aborting due to 1 previous error diff --git a/tests/ui/error-codes/E0519.stderr b/tests/ui/error-codes/E0519.stderr index a814277cafae2..54765fd6066a0 100644 --- a/tests/ui/error-codes/E0519.stderr +++ b/tests/ui/error-codes/E0519.stderr @@ -1,8 +1,10 @@ -error[E0519]: the current crate is indistinguishable from one of its dependencies: it has the same crate-name `crateresolve1` and was compiled with the same `-C metadata` arguments, so this will result in symbol conflicts between the two +error[E0519]: the current crate is indistinguishable from one of its dependencies --> $DIR/E0519.rs:8:1 | LL | extern crate crateresolve1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | + = note: it has the same name `crateresolve1` and was compiled with the same `-C metadata` arguments, so this will result in symbol conflicts between the two error: aborting due to 1 previous error diff --git a/tests/ui/errors/issue-104621-extern-bad-file.rs b/tests/ui/errors/issue-104621-extern-bad-file.rs index f675a4a3a4fec..a47244cbfaf26 100644 --- a/tests/ui/errors/issue-104621-extern-bad-file.rs +++ b/tests/ui/errors/issue-104621-extern-bad-file.rs @@ -2,7 +2,7 @@ //@ only-linux extern crate foo; -//~^ ERROR extern location for foo is of an unknown type -//~| ERROR file name should be lib*.rlib or lib*.so -//~| ERROR can't find crate for `foo` [E0463] +//~^ ERROR: extern location for `foo` is of an unknown type +//~| HELP: file name should be `lib*.rlib` or `lib*.so` +//~| ERROR: can't find crate for `foo` [E0463] fn main() {} diff --git a/tests/ui/errors/issue-104621-extern-bad-file.stderr b/tests/ui/errors/issue-104621-extern-bad-file.stderr index b8500ad0e045b..cb7927b410d20 100644 --- a/tests/ui/errors/issue-104621-extern-bad-file.stderr +++ b/tests/ui/errors/issue-104621-extern-bad-file.stderr @@ -1,14 +1,10 @@ -error: extern location for foo is of an unknown type: $DIR/issue-104621-extern-bad-file.rs +error: extern location for `foo` is of an unknown type at `$DIR/issue-104621-extern-bad-file.rs` --> $DIR/issue-104621-extern-bad-file.rs:4:1 | LL | extern crate foo; | ^^^^^^^^^^^^^^^^^ - -error: file name should be lib*.rlib or lib*.so - --> $DIR/issue-104621-extern-bad-file.rs:4:1 | -LL | extern crate foo; - | ^^^^^^^^^^^^^^^^^ + = help: file name should be `lib*.rlib` or `lib*.so` error[E0463]: can't find crate for `foo` --> $DIR/issue-104621-extern-bad-file.rs:4:1 @@ -16,6 +12,6 @@ error[E0463]: can't find crate for `foo` LL | extern crate foo; | ^^^^^^^^^^^^^^^^^ can't find crate -error: aborting due to 3 previous errors +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0463`. diff --git a/tests/ui/errors/issue-104621-extern-not-file.rs b/tests/ui/errors/issue-104621-extern-not-file.rs index 50806df15f7ad..3a715151ba10e 100644 --- a/tests/ui/errors/issue-104621-extern-not-file.rs +++ b/tests/ui/errors/issue-104621-extern-not-file.rs @@ -1,4 +1,4 @@ //@ compile-flags: --extern foo=. -extern crate foo; //~ ERROR extern location for foo is not a file: . +extern crate foo; //~ ERROR: extern location for `foo` is not a file: `.` fn main() {} diff --git a/tests/ui/errors/issue-104621-extern-not-file.stderr b/tests/ui/errors/issue-104621-extern-not-file.stderr index 61496e5b57b3c..afe6713dc461a 100644 --- a/tests/ui/errors/issue-104621-extern-not-file.stderr +++ b/tests/ui/errors/issue-104621-extern-not-file.stderr @@ -1,4 +1,4 @@ -error: extern location for foo is not a file: . +error: extern location for `foo` is not a file: `.` --> $DIR/issue-104621-extern-not-file.rs:3:1 | LL | extern crate foo; diff --git a/tests/ui/extern-flag/empty-extern-arg.rs b/tests/ui/extern-flag/empty-extern-arg.rs index d57edc6041247..d5ab19cc38e43 100644 --- a/tests/ui/extern-flag/empty-extern-arg.rs +++ b/tests/ui/extern-flag/empty-extern-arg.rs @@ -1,4 +1,4 @@ -//~ ERROR extern location for std does not exist +//~ ERROR extern location for `std` does not exist at `` //~^ ERROR cannot resolve a prelude import //@ compile-flags: --extern std= //@ needs-unwind since it affects the error output diff --git a/tests/ui/extern-flag/empty-extern-arg.stderr b/tests/ui/extern-flag/empty-extern-arg.stderr index 3e0a0d6cd5f86..8c90749a2ee64 100644 --- a/tests/ui/extern-flag/empty-extern-arg.stderr +++ b/tests/ui/extern-flag/empty-extern-arg.stderr @@ -1,4 +1,4 @@ -error: extern location for std does not exist: +error: extern location for `std` does not exist at `` error: cannot resolve a prelude import diff --git a/tests/ui/imports/resolve-other-libc.rs b/tests/ui/imports/resolve-other-libc.rs index e23083276ce2b..c1a2e4bf90ab9 100644 --- a/tests/ui/imports/resolve-other-libc.rs +++ b/tests/ui/imports/resolve-other-libc.rs @@ -9,6 +9,6 @@ // error[E0658]: use of unstable library feature `rustc_private`: \ // this crate is being loaded from the sysroot // -extern crate libc; //~ ERROR: extern location for libc does not exist: test.rlib +extern crate libc; //~ ERROR: extern location for `libc` does not exist at `test.rlib` fn main() {} diff --git a/tests/ui/imports/resolve-other-libc.stderr b/tests/ui/imports/resolve-other-libc.stderr index 81fe1294671d7..2f9d544dadb1f 100644 --- a/tests/ui/imports/resolve-other-libc.stderr +++ b/tests/ui/imports/resolve-other-libc.stderr @@ -1,4 +1,4 @@ -error: extern location for libc does not exist: test.rlib +error: extern location for `libc` does not exist at `test.rlib` --> $DIR/resolve-other-libc.rs:12:1 | LL | extern crate libc; diff --git a/tests/ui/missing/missing-allocator.stderr b/tests/ui/missing/missing-allocator.stderr index 007c488c9d95f..7b4e292314ffe 100644 --- a/tests/ui/missing/missing-allocator.stderr +++ b/tests/ui/missing/missing-allocator.stderr @@ -1,4 +1,6 @@ -error: no global memory allocator found but one is required; link to std or add `#[global_allocator]` to a static item that implements the GlobalAlloc trait +error: no global memory allocator found but one is required + | + = help: link to std or add `#[global_allocator]` to a static item that implements the `GlobalAlloc` trait error: aborting due to 1 previous error From 26312b9d5dcc62326803f9994750c2cd9daa6093 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Wed, 11 Nov 2026 17:33:13 +0000 Subject: [PATCH 39/39] Do not continue compilation past crate metadata errors Reduce the verbosity of compiler output by refusing to advance to later stages when a crate could not be imported. --- compiler/rustc_metadata/src/creader.rs | 10 +++++++++- compiler/rustc_metadata/src/locator.rs | 12 ++--------- .../rustc_resolve/src/build_reduced_graph.rs | 5 ++++- tests/ui/attributes/malformed-attrs.rs | 3 +-- tests/ui/attributes/malformed-attrs.stderr | 20 +++++++------------ .../missing-target-no-std-error.rs | 4 ++-- .../missing-target-no-std-error.stderr | 8 +++++++- tests/ui/extern-flag/empty-extern-arg.rs | 4 ---- tests/ui/extern-flag/empty-extern-arg.stderr | 11 +--------- 9 files changed, 33 insertions(+), 44 deletions(-) diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index a8de7356669b4..9f410b0e950b8 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -822,6 +822,7 @@ impl CStore { // dummy. We ignore compiler-injected prelude/sysroot loads here so they don't // suppress unrelated diagnostics, such as "unsupported targets for std library" // etc., these may be helpful for users to resolve crate loading failure. + self.has_crate_resolve_with_fail = true; let missing_core = self .maybe_resolve_crate( tcx, @@ -1472,7 +1473,14 @@ impl CStore { } pub fn maybe_process_path_extern(&mut self, tcx: TyCtxt<'_>, name: Symbol) -> Option { - self.maybe_resolve_crate(tcx, name, CrateDepKind::Unconditional, CrateOrigin::Extern).ok() + match self.maybe_resolve_crate(tcx, name, CrateDepKind::Unconditional, CrateOrigin::Extern) + { + Ok(cnum) => Some(cnum), + Err(_) => { + self.has_crate_resolve_with_fail = true; + None + } + } } } diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 67eab19521cb0..c7abbda002a87 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -1247,11 +1247,7 @@ impl CrateError { }; // The diagnostic for missing core is very good, but it is followed by a lot of // other diagnostics that do not add information. - if missing_core { - dcx.emit_fatal(error); - } else { - dcx.emit_err(error); - } + dcx.emit_err(error); } } CrateError::NotFound(crate_name) => { @@ -1273,11 +1269,7 @@ impl CrateError { }; // The diagnostic for missing core is very good, but it is followed by a lot of // other diagnostics that do not add information. - if missing_core { - dcx.emit_fatal(error); - } else { - dcx.emit_err(error); - } + dcx.emit_err(error); } } } diff --git a/compiler/rustc_resolve/src/build_reduced_graph.rs b/compiler/rustc_resolve/src/build_reduced_graph.rs index 1eb438933e489..53bf60d038123 100644 --- a/compiler/rustc_resolve/src/build_reduced_graph.rs +++ b/compiler/rustc_resolve/src/build_reduced_graph.rs @@ -752,7 +752,10 @@ impl<'a, 'ra, 'tcx> DefCollector<'a, 'ra, 'tcx> { if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = path_res { self.r.prelude = Some(module); } else { - self.r.dcx().span_err(use_tree.span(), "cannot resolve a prelude import"); + // We already emitted: "error[E0463]: can't find crate for `std`/`core`" + self.r + .dcx() + .span_delayed_bug(use_tree.span(), "cannot resolve a prelude import"); } } } diff --git a/tests/ui/attributes/malformed-attrs.rs b/tests/ui/attributes/malformed-attrs.rs index 6b66f05c03888..500f4eacc2c59 100644 --- a/tests/ui/attributes/malformed-attrs.rs +++ b/tests/ui/attributes/malformed-attrs.rs @@ -212,8 +212,7 @@ static mut TLS: u8 = 42; //~| WARN this was previously accepted by the compiler #[macro_use = 1] //~^ ERROR malformed -extern crate wloop; -//~^ ERROR can't find crate for `wloop` [E0463] +extern crate core; #[macro_export = 18] //~^ ERROR malformed diff --git a/tests/ui/attributes/malformed-attrs.stderr b/tests/ui/attributes/malformed-attrs.stderr index b982facaf2abb..8e9049f26a2eb 100644 --- a/tests/ui/attributes/malformed-attrs.stderr +++ b/tests/ui/attributes/malformed-attrs.stderr @@ -22,12 +22,6 @@ help: must be of the form LL | #[cfg_attr(predicate, attr1, attr2, ...)] | ++++++++++++++++++++++++++++++ -error[E0463]: can't find crate for `wloop` - --> $DIR/malformed-attrs.rs:215:1 - | -LL | extern crate wloop; - | ^^^^^^^^^^^^^^^^^^^ can't find crate - error: the `proc_macro` attribute is only usable with crates of the `proc-macro` crate type --> $DIR/malformed-attrs.rs:106:3 | @@ -825,7 +819,7 @@ LL + #[macro_use(name1, name2, ...)] | error[E0539]: malformed `macro_export` attribute input - --> $DIR/malformed-attrs.rs:218:3 + --> $DIR/malformed-attrs.rs:217:3 | LL | #[macro_export = 18] | ^^^^^^^^^^^^^---- @@ -842,7 +836,7 @@ LL + #[macro_export(local_inner_macros)] | error[E0658]: the `allow_internal_unsafe` attribute side-steps the `unsafe_code` lint - --> $DIR/malformed-attrs.rs:220:3 + --> $DIR/malformed-attrs.rs:219:3 | LL | #[allow_internal_unsafe = 1] | ^^^^^^^^^^^^^^^^^^^^^ @@ -851,7 +845,7 @@ LL | #[allow_internal_unsafe = 1] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date error[E0565]: malformed `allow_internal_unsafe` attribute input - --> $DIR/malformed-attrs.rs:220:3 + --> $DIR/malformed-attrs.rs:219:3 | LL | #[allow_internal_unsafe = 1] | ^^^^^^^^^^^^^^^^^^^^^^--- @@ -995,7 +989,7 @@ LL | #[no_link()] = note: `#[deny(no_link_attributes)]` (part of `#[deny(future_incompatible)]`) on by default error: valid forms for the attribute are `ignore` and `ignore = "reason"` - --> $DIR/malformed-attrs.rs:227:3 + --> $DIR/malformed-attrs.rs:226:3 | LL | #[ignore = 1] | ^^^^^^^^^^ @@ -1014,9 +1008,9 @@ LL | #[coroutine = 63] || {} = note: expected unit type `()` found coroutine `{coroutine@$DIR/malformed-attrs.rs:118:23: 118:25}` -error: aborting due to 76 previous errors; 8 warnings emitted +error: aborting due to 75 previous errors; 8 warnings emitted -Some errors have detailed explanations: E0308, E0433, E0463, E0539, E0565, E0658, E0805. +Some errors have detailed explanations: E0308, E0433, E0539, E0565, E0658, E0805. For more information about an error, try `rustc --explain E0308`. Future incompatibility report: Future breakage diagnostic: error: valid forms for the attribute are `inline`, `inline(always)`, and `inline(never)` @@ -1053,7 +1047,7 @@ LL | #[no_link()] Future breakage diagnostic: error: valid forms for the attribute are `ignore` and `ignore = "reason"` - --> $DIR/malformed-attrs.rs:227:3 + --> $DIR/malformed-attrs.rs:226:3 | LL | #[ignore = 1] | ^^^^^^^^^^ diff --git a/tests/ui/crate-loading/missing-target-no-std-error.rs b/tests/ui/crate-loading/missing-target-no-std-error.rs index 6c337aa02b3bd..83d922dcfa92e 100644 --- a/tests/ui/crate-loading/missing-target-no-std-error.rs +++ b/tests/ui/crate-loading/missing-target-no-std-error.rs @@ -1,7 +1,7 @@ //! Regression test for . //! Test compiling for a target which is not installed with `no_std` //! results in a helpful error message. -//~^^^ ERROR can't find crate for `core` +//~^^^ ERROR: can't find crate for `core` //@ compile-flags: --target thumbv7em-none-eabihf //@ needs-llvm-components: arm @@ -9,6 +9,6 @@ #![deny(warnings)] #![no_std] -extern crate cortex_m; +extern crate cortex_m; //~ ERROR: can't find crate for `cortex_m` fn main() {} diff --git a/tests/ui/crate-loading/missing-target-no-std-error.stderr b/tests/ui/crate-loading/missing-target-no-std-error.stderr index 1cd65a1b68c88..11c856f844fc8 100644 --- a/tests/ui/crate-loading/missing-target-no-std-error.stderr +++ b/tests/ui/crate-loading/missing-target-no-std-error.stderr @@ -4,6 +4,12 @@ error[E0463]: can't find crate for `core` = help: consider downloading the target with `rustup target add thumbv7em-none-eabihf` = help: consider building the standard library from source with `cargo build -Zbuild-std` -error: aborting due to 1 previous error +error[E0463]: can't find crate for `cortex_m` + --> $DIR/missing-target-no-std-error.rs:12:1 + | +LL | extern crate cortex_m; + | ^^^^^^^^^^^^^^^^^^^^^^ can't find crate + +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0463`. diff --git a/tests/ui/extern-flag/empty-extern-arg.rs b/tests/ui/extern-flag/empty-extern-arg.rs index d5ab19cc38e43..8cd3831592621 100644 --- a/tests/ui/extern-flag/empty-extern-arg.rs +++ b/tests/ui/extern-flag/empty-extern-arg.rs @@ -1,9 +1,5 @@ //~ ERROR extern location for `std` does not exist at `` -//~^ ERROR cannot resolve a prelude import //@ compile-flags: --extern std= //@ needs-unwind since it affects the error output fn main() {} - -//~? ERROR `#[panic_handler]` function required, but not found -//~? ERROR unwinding panics are not supported without std diff --git a/tests/ui/extern-flag/empty-extern-arg.stderr b/tests/ui/extern-flag/empty-extern-arg.stderr index 8c90749a2ee64..d9029072040de 100644 --- a/tests/ui/extern-flag/empty-extern-arg.stderr +++ b/tests/ui/extern-flag/empty-extern-arg.stderr @@ -1,13 +1,4 @@ error: extern location for `std` does not exist at `` -error: cannot resolve a prelude import - -error: `#[panic_handler]` function required, but not found - -error: unwinding panics are not supported without std - | - = help: using nightly cargo, use -Zbuild-std with panic="abort" to avoid unwinding - = note: since the core library is usually precompiled with panic="unwind", rebuilding your crate with panic="abort" may not be enough to fix the problem - -error: aborting due to 4 previous errors +error: aborting due to 1 previous error