From dcf3a6e49f5ec9e999efbcdacd8d1411964e33f3 Mon Sep 17 00:00:00 2001 From: A4-Tacks Date: Thu, 22 Oct 2026 17:04:25 +0800 Subject: [PATCH 01/48] feat: show custom iter adapter in chaining inlayHints Example --- **Before this PR** ```rust use itertools::Itertools; fn main() { [1, 2, 3].into_iter() // <- IntoIter .merge_by([2, 4, 6], |a,b|a, IntoIter, impl FnMut(&i32, &i32) -> bool> .next(); } ``` **After this PR** ```rust use itertools::Itertools; fn main() { [1, 2, 3].into_iter() // <- IntoIter .merge_by([2, 4, 6], |a,b|a .next(); } ``` --- .../crates/ide/src/inlay_hints.rs | 20 +-- .../crates/ide/src/inlay_hints/chaining.rs | 119 ++++++++++++++++++ 2 files changed, 132 insertions(+), 7 deletions(-) diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs index 98d5efb0f34d7..48297ee70a002 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints.rs @@ -861,16 +861,22 @@ fn hint_iterator<'db>( let db = sema.db; let strukt = ty.strip_references().as_adt()?; let krate = strukt.module(db).krate(db); - if krate != famous_defs.core()? { - return None; - } let iter_trait = famous_defs.core_iter_Iterator()?; let iter_mod = famous_defs.core_iter()?; - // Assert that this struct comes from `core::iter`. - if !(strukt.visibility(db) == hir::Visibility::Public - && strukt.module(db).path_to_root(db).contains(&iter_mod)) - { + let is_core_adapter = Some(krate) == famous_defs.core() + && strukt.visibility(db) == hir::Visibility::Public + && strukt.module(db).path_to_root(db).contains(&iter_mod); + let is_custom_adapter = || { + let params = hir::GenericDef::Adt(strukt).type_or_const_params(db); + params + .iter() + .filter_map(|it| it.as_type_param(db)) + .any(|it| it.trait_bounds(db).contains(&iter_trait)) + }; + + // Assert that this struct iterator adapter, excludes like `Range`. + if !is_core_adapter && !is_custom_adapter() { return None; } diff --git a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs index e008a7b940662..c818a1ef5fe10 100644 --- a/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs +++ b/src/tools/rust-analyzer/crates/ide/src/inlay_hints/chaining.rs @@ -775,4 +775,123 @@ fn make() -> Foo { "#]], ); } + + #[test] + fn custom_iterator_adapter_chaining() { + check_expect_clear_loc( + InlayHintsConfig { chaining_hints: true, ..DISABLED_CONFIG }, + r#" +//- minicore: iterators +fn main() { + [1, 2, 3].into_iter() + .merge_by([2, 4, 6], |a,b|a { + left: I, + right: J, + cmp_fn: F, +} +impl Iterator for MergeBy +where + I: Iterator, + J: Iterator, + F: FnMut(&I::Item, &J::Item) -> bool, +{ + type Item = I::Item; + + fn next(&mut self) -> Option { loop {} } +} + +trait Itertools: Iterator { + fn merge_by(self, other: J, is_first: F) -> MergeBy + where + Self: Sized, + J: IntoIterator, + F: FnMut(&Self::Item, &Self::Item) -> bool, + { + MergeBy { left: self, right: other.into_iter(), cmp_fn: is_first } + } +} +impl Itertools for I {} +"#, + expect![[r#" + [ + ( + 16..76, + [ + "impl ", + InlayHintLabelPart { + text: "Iterator", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + "<", + InlayHintLabelPart { + text: "Item", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + " = i32>", + ], + ), + ( + 16..37, + [ + "impl ", + InlayHintLabelPart { + text: "Iterator", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + "<", + InlayHintLabelPart { + text: "Item", + linked_location: Some( + Computed( + FileRangeWrapper { + file_id: FileId( + 1, + ), + range: 0..0, + }, + ), + ), + tooltip: "", + }, + " = i32>", + ], + ), + ] + "#]], + ); + } } From 21ab4d59a7a5c1975de69973efb52d33f6d8f0d1 Mon Sep 17 00:00:00 2001 From: Nicolas Guichard Date: Tue, 13 Oct 2026 15:31:14 +0200 Subject: [PATCH 02/48] Introduce StoredTerm This is the stored variant of Term, just like StoredGenericArg is the stored variant of GenericArg. --- .../hir-ty/src/next_solver/generic_arg.rs | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs index 81d36c2bb037c..db93276f7e32f 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/generic_arg.rs @@ -280,6 +280,57 @@ impl<'db> From> for GenericArg<'db> { } } +#[derive(PartialEq, Eq, Hash)] +pub struct StoredTerm { + ptr: GenericArgImpl<'static>, +} + +impl Clone for StoredTerm { + #[inline] + fn clone(&self) -> Self { + match self.ptr.term_kind() { + TermKind::Ty(it) => std::mem::forget(it.interned.to_owned()), + TermKind::Const(it) => std::mem::forget(it.interned.to_owned()), + } + Self { ptr: self.ptr } + } +} + +impl Drop for StoredTerm { + #[inline] + fn drop(&mut self) { + unsafe { + match self.ptr.term_kind() { + TermKind::Ty(it) => it.interned.decrement_refcount(), + TermKind::Const(it) => it.interned.decrement_refcount(), + } + } + } +} + +impl StoredTerm { + #[inline] + fn new(value: Term<'_>) -> Self { + let result = Self { ptr: GenericArgImpl { ptr: value.ptr.ptr, _marker: PhantomData } }; + // Increase refcount. + std::mem::forget(result.clone()); + result + } + + #[inline] + pub fn as_ref<'db>(&self) -> Term<'db> { + Term { ptr: self.ptr } + } +} + +impl std::fmt::Debug for StoredTerm { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.as_ref().fmt(f) + } +} + +impl_foldable_for_stored_type!(StoredTerm); + #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub struct Term<'db> { ptr: GenericArgImpl<'db>, @@ -295,6 +346,11 @@ impl<'db> std::fmt::Debug for Term<'db> { } impl<'db> Term<'db> { + #[inline] + pub fn store(self) -> StoredTerm { + StoredTerm::new(self) + } + #[inline] pub fn kind(self) -> TermKind<'db> { self.ptr.term_kind() From e786ac208852db2bcd401e3de8e5192b10839ead Mon Sep 17 00:00:00 2001 From: Nicolas Guichard Date: Mon, 22 Sep 2025 20:07:48 +0200 Subject: [PATCH 03/48] Introduce hir_ty::next_solver::TermRefId and TermRefIdPacked This is heavily inspired from hir_def::hir::ExprOrPatId and its packed variant, to wrap either a TypeRefId or a ConstRef. --- .../crates/hir-ty/src/next_solver/def_id.rs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs index c45387b6894bc..dc609b0cff26d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/def_id.rs @@ -4,10 +4,12 @@ use hir_def::{ AdtId, AttrDefId, BuiltinDeriveImplId, CallableDefId, ConstId, DefWithBodyId, EnumId, EnumVariantId, ExpressionStoreOwnerId, FunctionId, GenericDefId, ImplId, StaticId, StructId, TraitId, TypeAliasId, UnionId, VariantId, + hir::ExprId, signatures::{ ConstSignature, EnumSignature, FunctionSignature, StaticSignature, StructSignature, TraitSignature, TypeAliasSignature, UnionSignature, }, + type_ref::{ConstRef, TypeRefId}, }; use rustc_type_ir::inherent; use salsa::SalsaValue; @@ -541,6 +543,58 @@ impl<'db> From for SolverDefId<'db> { } } +#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] +pub enum TermRefId { + TypeRefId(TypeRefId), + ConstRef(ConstRef), +} +impl_from!(TypeRefId, ConstRef for TermRefId); + +#[derive(Copy, Clone, Hash, PartialEq, Eq)] +pub struct TermRefIdPacked(u32); + +const _: () = assert!(std::mem::size_of::() == std::mem::size_of::()); + +impl TermRefIdPacked { + const CONST_REF_BIT: u32 = 1 << (u32::BITS - 1); + const INDEX_MASK: u32 = !Self::CONST_REF_BIT; + + pub fn unpack(self) -> TermRefId { + let is_const_ref = self.0 & Self::CONST_REF_BIT != 0; + match is_const_ref { + true => { + let expr = ExprId::from_raw((self.0 & Self::INDEX_MASK).into()); + TermRefId::ConstRef(ConstRef { expr }) + } + false => TermRefId::TypeRefId(TypeRefId::from_raw(self.0.into())), + } + } +} + +impl std::fmt::Debug for TermRefIdPacked { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.unpack().fmt(f) + } +} + +impl From for TermRefIdPacked { + fn from(value: TypeRefId) -> Self { + let value = value.into_raw().into_u32(); + // virtually impossible to have IDs that high + debug_assert_eq!(value & Self::CONST_REF_BIT, 0); + Self(value) + } +} + +impl From for TermRefIdPacked { + fn from(value: ConstRef) -> Self { + let value = value.expr.into_raw().into_u32(); + // virtually impossible to have IDs that high + debug_assert_eq!(value & Self::CONST_REF_BIT, 0); + Self(value | Self::CONST_REF_BIT) + } +} + #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct GeneralConstIdWrapper<'db>(pub GeneralConstId<'db>); From a234c72b3cc2c08296c14ad1e5216f4549baf850 Mon Sep 17 00:00:00 2001 From: Nicolas Guichard Date: Mon, 22 Sep 2025 20:07:48 +0200 Subject: [PATCH 04/48] Record inferred const for type or const placeholders This replaces InferenceResult::type_of_type_placeholder with term_of_term_placeholder to additionally record which const a given const or type placeholder gets resolved to. Note that while surprising, TypeRef::Placeholder may indeed resolve to a const because, except for arrays, the parser doesn't know ahead of time if a _ will resolve to a type or a const. In the case of an array, we have an Expr::Underscore: ``` let a: [_; _] = [4, 5, 6]; //^ TypeRef::Placeholder which resolves to the type i32 //^ Expr::Underscore which resolves to the const 3 ``` But for a struct we have a TypeRef::Placeholder: ``` struct S([T; N]); let s: S<_, _> = S([1, 2, 3]); //^ TypeRef::Placeholder which resolves to the type i32 //^ TypeRef::Placeholder which resolves to the const 3 ``` --- .../rust-analyzer/crates/hir-ide/src/tests.rs | 31 +++++++++++++----- .../hir-ide/src/tests/display_source_code.rs | 22 +++++++------ .../rust-analyzer/crates/hir-ty/src/infer.rs | 32 ++++++++++--------- .../crates/hir-ty/src/infer/diagnostics.rs | 23 ++++++++++--- .../crates/hir-ty/src/infer/path.rs | 2 +- .../crates/hir/src/source_analyzer.rs | 19 +++++------ 6 files changed, 81 insertions(+), 48 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs b/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs index 7db1e8c947665..52b9a79684268 100644 --- a/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs +++ b/src/tools/rust-analyzer/crates/hir-ide/src/tests.rs @@ -44,7 +44,7 @@ use crate::{ Adjustment, InferBodyId, InferenceDiagnostic, InferenceResult, db::{AnonConstId, HirDatabase}, display::{DisplayTarget, HirDisplay}, - next_solver::Ty, + next_solver::{TermRefId, Ty}, setup_tracing, test_db::TestDB, }; @@ -196,6 +196,7 @@ fn check_impl( let mut had_annotations = false; let mut mismatches = FxHashMap::default(); let mut types = FxHashMap::default(); + let mut consts = FxHashMap::default(); let mut adjustments = FxHashMap::default(); for (file_id, annotations) in db.extract_annotations() { for (range, expected) in annotations { @@ -204,6 +205,8 @@ fn check_impl( types.insert(file_range, expected); } else if let Some(ty) = expected.strip_prefix("type: ") { types.insert(file_range, ty.to_owned()); + } else if let Some(const_) = expected.strip_prefix("const: ") { + consts.insert(file_range, const_.to_owned()); } else if expected.starts_with("expected") { mismatches.insert(file_range, expected); } else if let Some(adjs) = expected.strip_prefix("adjustments:") { @@ -300,21 +303,27 @@ fn check_impl( } } - for (type_ref, ty) in inference_result.placeholder_types() { - let node = match type_node(source_map, type_ref, &db) { - Some(value) => value, - None => continue, + for (term_ref, term) in inference_result.term_of_term_placeholders() { + let node = match term_ref.unpack() { + TermRefId::TypeRefId(type_ref) => type_node(source_map, type_ref, &db), + TermRefId::ConstRef(const_ref) => expr_node(source_map, const_ref.expr, &db), }; + let Some(node) = node else { continue }; let range = node.as_ref().original_file_range_rooted(&db); - if let Some(expected) = types.remove(&range) { + if let Some(expected) = types.remove(&range).or_else(|| consts.remove(&range)) { let actual = salsa::attach(&db, || { if display_source { - ty.display_source_code(&db, def.module(&db), true).unwrap() + term.display_source_code(&db, def.module(&db), true).unwrap() } else { - ty.display_test(&db, display_target).to_string() + term.display_test(&db, display_target).to_string() } }); assert_eq!(actual, expected, "type annotation differs at {:#?}", range.range); + assert_eq!( + actual, expected, + "placeholder annotation differs at {:#?}", + range.range + ); } } } @@ -335,6 +344,12 @@ fn check_impl( format_to!(buf, "{:?}: type {}\n", t.0.range, t.1); } } + if !consts.is_empty() { + format_to!(buf, "Unchecked const annotations:\n"); + for c in consts { + format_to!(buf, "{:?}: const {}\n", c.0.range, c.1); + } + } if !adjustments.is_empty() { format_to!(buf, "Unchecked adjustments annotations:\n"); for t in adjustments { diff --git a/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs b/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs index db21c4cf949aa..bee40d74f5298 100644 --- a/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs +++ b/src/tools/rust-analyzer/crates/hir-ide/src/tests/display_source_code.rs @@ -1,4 +1,4 @@ -use super::check_types_source_code; +use super::{check, check_types_source_code}; #[test] fn qualify_path_to_submodule() { @@ -261,19 +261,21 @@ fn test() { } #[test] -fn type_placeholder_type() { - check_types_source_code( +fn term_placeholders() { + check( r#" -struct S(T); +struct S([T; N]); fn test() { - let f: S<_> = S(3); - //^ i32 + let f: S<_, _> = S([1, 2]); + //^ type: i32 + //^ const: 2 let f: [_; _] = [4_u32, 5, 6]; - //^ u32 + //^ type: u32 + //^ const: 3 let f: (_, _, _) = (1_u32, 1_i32, false); - //^ u32 - //^ i32 - //^ bool + //^ type: u32 + //^ type: i32 + //^ type: bool } "#, ); diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs index 55125a29033f1..c98567adb2d32 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer.rs @@ -102,7 +102,7 @@ use crate::{ method_resolution::CandidateId, next_solver::{ AliasTy, Const, ConstKind, DbInterner, GenericArgs, Region, StoredFnSig, StoredGenericArg, - StoredGenericArgs, StoredTy, StoredTys, Term, Ty, TyKind, Tys, + StoredGenericArgs, StoredTerm, StoredTy, StoredTys, Term, TermRefIdPacked, Ty, TyKind, Tys, abi::Safety, default_types, infer::{InferCtxt, ObligationInspector, traits::ObligationCause}, @@ -768,7 +768,7 @@ pub struct InferenceResult<'db> { /// unresolved or missing subpatterns or subpatterns of mismatched types. pub type_of_pat: ArenaMap, pub type_of_binding: ArenaMap, - pub type_of_type_placeholder: ThinFxHashMap, + pub term_of_term_placeholders: ThinFxHashMap, pub type_of_opaque: ThinFxHashMap, StoredTy>, /// Whether there are any type-mismatching errors in the result. @@ -1124,7 +1124,7 @@ impl<'db> InferenceResult<'db> { type_of_expr: Default::default(), type_of_pat: Default::default(), type_of_binding: Default::default(), - type_of_type_placeholder: Default::default(), + term_of_term_placeholders: Default::default(), type_of_opaque: Default::default(), skipped_ref_pats: Default::default(), has_errors: Default::default(), @@ -1191,11 +1191,13 @@ impl<'db> InferenceResult<'db> { pub fn has_type_mismatches(&self) -> bool { !self.nodes_with_type_mismatches.is_empty() } - pub fn placeholder_types<'a>(&self) -> impl Iterator)> { - self.type_of_type_placeholder.iter().map(|(&type_ref, ty)| (type_ref, ty.as_ref())) + pub fn term_of_term_placeholders<'a>( + &self, + ) -> impl Iterator)> { + self.term_of_term_placeholders.iter().map(|(&term_ref, term)| (term_ref, term.as_ref())) } - pub fn type_of_type_placeholder<'a>(&self, type_ref: TypeRefId) -> Option> { - self.type_of_type_placeholder.get(&type_ref).map(|ty| ty.as_ref()) + pub fn term_of_term_placeholder<'a>(&self, term_ref: TermRefIdPacked) -> Option> { + self.term_of_term_placeholders.get(&term_ref).map(|term| term.as_ref()) } pub fn type_of_expr_or_pat<'a>(&self, id: ExprOrPatId) -> Option> { match id { @@ -1474,7 +1476,7 @@ impl<'db> InferenceContext<'db> { type_of_expr, type_of_pat, type_of_binding, - type_of_type_placeholder, + term_of_term_placeholders: placeholders, type_of_opaque, has_errors: _, diagnostics: _, @@ -1504,7 +1506,7 @@ impl<'db> InferenceContext<'db> { merge_arena_maps(type_of_expr, &other.type_of_expr); merge_arena_maps(type_of_pat, &other.type_of_pat); merge_arena_maps(type_of_binding, &other.type_of_binding); - merge_thin_hash_maps(type_of_type_placeholder, &other.type_of_type_placeholder); + merge_thin_hash_maps(placeholders, &other.term_of_term_placeholders); merge_thin_hash_maps(type_of_opaque, &other.type_of_opaque); merge_hash_maps(expr_adjustments, &other.expr_adjustments); merge_thin_hash_maps(pat_adjustments, &other.pat_adjustments); @@ -1652,7 +1654,7 @@ impl<'db> InferenceContext<'db> { type_of_expr, type_of_pat, type_of_binding, - type_of_type_placeholder, + term_of_term_placeholders, type_of_opaque, skipped_ref_pats, closures_data, @@ -1686,10 +1688,10 @@ impl<'db> InferenceContext<'db> { resolver.resolve_completely(ty); } type_of_binding.shrink_to_fit(); - for ty in type_of_type_placeholder.values_mut() { - resolver.resolve_completely(ty); + for term in term_of_term_placeholders.values_mut() { + resolver.resolve_completely(term); } - type_of_type_placeholder.shrink_to_fit(); + term_of_term_placeholders.shrink_to_fit(); type_of_opaque.shrink_to_fit(); if !nodes_with_type_mismatches.is_empty() { @@ -1945,7 +1947,7 @@ impl<'db> InferenceContext<'db> { fn with_ty_lowering(&mut self, f: impl FnOnce(&mut TyLoweringContext<'db, '_>) -> R) -> R { let mut infer_vars = InferenceTyLoweringVarsCtx { table: &mut self.table, - type_of_type_placeholder: &mut self.result.type_of_type_placeholder, + term_of_term_placeholders: &mut self.result.term_of_term_placeholders, }; let mut ctx = TyLoweringContext::new( self.db, @@ -2252,7 +2254,7 @@ impl<'db> InferenceContext<'db> { let interner = self.interner(); let mut vars_ctx = InferenceTyLoweringVarsCtx { table: &mut self.table, - type_of_type_placeholder: &mut self.result.type_of_type_placeholder, + term_of_term_placeholders: &mut self.result.term_of_term_placeholders, }; let mut ctx = TyLoweringContext::new( self.db, diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs index f3bea3a653c8c..965ff8954106d 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/diagnostics.rs @@ -6,9 +6,10 @@ use std::cell::{OnceCell, RefCell}; use std::ops::{Deref, DerefMut}; use either::Either; +use hir_def::expr_store::ExpressionStore; use hir_def::expr_store::path::Path; +use hir_def::type_ref::ConstRef; use hir_def::{ExpressionStoreOwnerId, GenericDefId}; -use hir_def::{expr_store::ExpressionStore, type_ref::TypeRefId}; use hir_def::{ hir::{ExprId, ExprOrPatIdPacked}, resolver::Resolver, @@ -16,6 +17,7 @@ use hir_def::{ use la_arena::RawIdx; use thin_vec::ThinVec; +use crate::next_solver::{StoredTerm, Term}; use crate::{ InferenceDiagnostic, Span, ThinFxHashMap, TyLoweringDiagnostic, db::{AnonConstId, HirDatabase}, @@ -26,7 +28,7 @@ use crate::{ TyLoweringInferVarsCtx, path::{PathDiagnosticCallback, PathLoweringContext}, }, - next_solver::{Const, Region, StoredTy, Ty}, + next_solver::{Const, Region, TermRefIdPacked, Ty}, }; // Unfortunately, this struct needs to use interior mutability (but we encapsulate it) @@ -63,7 +65,7 @@ pub(crate) struct PathDiagnosticCallbackData<'a> { pub(super) struct InferenceTyLoweringVarsCtx<'a, 'db> { pub(super) table: &'a mut InferenceTable<'db>, - pub(super) type_of_type_placeholder: &'a mut ThinFxHashMap, + pub(super) term_of_term_placeholders: &'a mut ThinFxHashMap, } impl<'db> TyLoweringInferVarsCtx<'db> for InferenceTyLoweringVarsCtx<'_, 'db> { @@ -71,13 +73,24 @@ impl<'db> TyLoweringInferVarsCtx<'db> for InferenceTyLoweringVarsCtx<'_, 'db> { let ty = self.table.infer_ctxt.next_ty_var(span); if let Span::TypeRefId(type_ref) = span { - self.type_of_type_placeholder.insert(type_ref, ty.store()); + self.term_of_term_placeholders.insert(type_ref.into(), Term::from(ty).store()); } ty } fn next_const_var(&mut self, span: Span) -> Const<'db> { - self.table.infer_ctxt.next_const_var(span) + let const_ = self.table.infer_ctxt.next_const_var(span); + + let term_ref = match span { + Span::ExprId(expr) => Some(ConstRef { expr }.into()), + Span::TypeRefId(type_ref) => Some(type_ref.into()), + _ => None, + }; + if let Some(key) = term_ref { + self.term_of_term_placeholders.insert(key, Term::from(const_).store()); + } + + const_ } fn next_region_var(&mut self, span: Span) -> Region<'db> { self.table.infer_ctxt.next_region_var(span) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs index ec0788b43b573..47c06891202bf 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/infer/path.rs @@ -152,7 +152,7 @@ impl<'db> InferenceContext<'db> { // Don't use `self.make_ty()` here as we need `orig_ns`. let mut vars_ctx = InferenceTyLoweringVarsCtx { table: &mut self.table, - type_of_type_placeholder: &mut self.result.type_of_type_placeholder, + term_of_term_placeholders: &mut self.result.term_of_term_placeholders, }; let mut ctx = TyLoweringContext::new( self.db, diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index ff9fa659a928e..4c092b06e0a58 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -53,7 +53,7 @@ use itertools::Itertools; use rustc_hash::FxHashSet; use rustc_type_ir::{ AliasTyKind, - inherent::{IntoKind, Ty as _}, + inherent::{IntoKind, Term as _, Ty as _}, }; use smallvec::SmallVec; use stdx::never; @@ -481,14 +481,15 @@ impl<'db> SourceAnalyzer<'db> { impl<'db> TyLoweringInferVarsCtx<'db> for VarsCtx<'_, 'db> { fn next_ty_var(&mut self, span: hir_ide::Span) -> Ty<'db> { - if let hir_ide::Span::TypeRefId(type_ref) = span - && let Some(ty) = - self.infer.and_then(|infer| infer.type_of_type_placeholder(type_ref)) - { - ty - } else { - self.types.types.error - } + let term_ref = match span { + hir_ide::Span::TypeRefId(type_ref) => type_ref.into(), + _ => return self.types.types.error, + }; + + self.infer + .and_then(|infer| infer.term_of_term_placeholder(term_ref)) + .and_then(|term| term.as_type()) + .unwrap_or(self.types.types.error) } fn next_const_var(&mut self, _span: hir_ide::Span) -> hir_ide::next_solver::Const<'db> { self.types.consts.error From 86bcadcf871cbc35694cdfa8e20140d2a531ba09 Mon Sep 17 00:00:00 2001 From: Nicolas Guichard Date: Mon, 22 Sep 2025 20:07:48 +0200 Subject: [PATCH 05/48] Fix extract_type_alias with const generics This fixes SourceAnalyzer::type_of_type to replace const infer vars in types with their resolved value. --- .../crates/hir/src/source_analyzer.rs | 15 +++++-- .../src/handlers/extract_type_alias.rs | 42 +++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs index 4c092b06e0a58..888a4ca84dd66 100644 --- a/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs +++ b/src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs @@ -25,7 +25,7 @@ use hir_def::{ lang_item::LangItems, nameres::MacroSubNs, resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs, resolver_for_scope}, - type_ref::{Mutability, TypeRefId}, + type_ref::{ConstRef, Mutability, TypeRefId}, visibility::Visibility, }; use hir_expand::{ @@ -491,8 +491,17 @@ impl<'db> SourceAnalyzer<'db> { .and_then(|term| term.as_type()) .unwrap_or(self.types.types.error) } - fn next_const_var(&mut self, _span: hir_ide::Span) -> hir_ide::next_solver::Const<'db> { - self.types.consts.error + fn next_const_var(&mut self, span: hir_ide::Span) -> hir_ide::next_solver::Const<'db> { + let term_ref = match span { + hir_ide::Span::TypeRefId(type_ref) => type_ref.into(), + hir_ide::Span::ExprId(expr) => ConstRef { expr }.into(), + _ => return self.types.consts.error, + }; + + self.infer + .and_then(|infer| infer.term_of_term_placeholder(term_ref)) + .and_then(|generic_arg| generic_arg.as_const()) + .unwrap_or(self.types.consts.error) } fn next_region_var(&mut self, _span: hir_ide::Span) -> Region<'db> { self.types.regions.error diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs index a378256b598aa..b95fab4fe88c8 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/extract_type_alias.rs @@ -426,6 +426,48 @@ fn main() { ) } + #[test] + fn inferred_array_length() { + check_assist( + extract_type_alias, + r#" +fn main() { + let a: $0[i32; _]$0 = [1, 2, 3]; +} + "#, + r#" +type $0Type = [i32; 3]; + +fn main() { + let a: Type = [1, 2, 3]; +} + "#, + ) + } + + #[test] + fn inferred_generic_const_parameter() { + check_assist( + extract_type_alias, + r#" +struct Wrap([i32; N]); + +fn main() { + let wrap: $0Wrap<_>$0 = Wrap([1, 2, 3]); +} + "#, + r#" +struct Wrap([i32; N]); + +type $0Type = Wrap<3>; + +fn main() { + let wrap: Type = Wrap([1, 2, 3]); +} + "#, + ) + } + #[test] fn inferred_type() { check_assist( From 8c918701022e20fcca1e37e0fa291f4137b3cf58 Mon Sep 17 00:00:00 2001 From: Benjamin Brienen Date: Mon, 16 Nov 2026 10:23:43 +0100 Subject: [PATCH 06/48] add tests for `Pool` and fix atomic ordering issue --- .../crates/stdx/src/thread/pool.rs | 133 +++++++++++++++++- 1 file changed, 130 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs b/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs index 1ef6954e5a6ce..932dec3b37d85 100644 --- a/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs +++ b/src/tools/rust-analyzer/crates/stdx/src/thread/pool.rs @@ -37,6 +37,7 @@ pub struct Pool { struct Job { requested_intent: ThreadIntent, f: Box, + wg: Option, } impl Pool { @@ -67,6 +68,7 @@ impl Pool { // discard the panic, we should've logged the backtrace already drop(panic::catch_unwind(job.f)); extant_tasks.fetch_sub(1, Ordering::SeqCst); + drop(job.wg); } } }) @@ -89,7 +91,7 @@ impl Pool { f(); }); - let job = Job { requested_intent: intent, f }; + let job = Job { requested_intent: intent, f, wg: None }; self.extant_tasks.fetch_add(1, Ordering::SeqCst); self.job_sender.send(job).unwrap(); } @@ -127,15 +129,14 @@ impl<'scope> Scope<'_, 'scope> { where F: 'scope + FnOnce() + Send + UnwindSafe, { - let wg = self.wg.clone(); let f = Box::new(move || { if cfg!(debug_assertions) { intent.assert_is_used_on_current_thread(); } f(); - drop(wg); }); + let wg = self.wg.clone(); let job = Job { requested_intent: intent, f: unsafe { @@ -144,8 +145,134 @@ impl<'scope> Scope<'_, 'scope> { Box, >(f) }, + wg: Some(wg), }; self.pool.extant_tasks.fetch_add(1, Ordering::SeqCst); self.pool.job_sender.send(job).unwrap(); } } + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }; + + fn spawn_scoped_worker(pool: &Pool) { + pool.scoped(|scope| scope.spawn(ThreadIntent::Worker, || {})); + } + + #[test] + fn new_creates_empty_pool() { + let pool = Pool::new(2); + assert_eq!(pool.len(), 0); + assert!(pool.is_empty()); + } + + #[test] + fn spawn_executes_function() { + let pool = Pool::new(1); + let executed = Arc::new(AtomicBool::new(false)); + let executed_clone = Arc::clone(&executed); + pool.spawn(ThreadIntent::Worker, move || { + executed_clone.store(true, Ordering::SeqCst); + }); + spawn_scoped_worker(&pool); + assert!(executed.load(Ordering::SeqCst)); + } + + #[test] + fn spawn_changes_thread_intent() { + let pool = Pool::new(1); + let count = Arc::new(AtomicUsize::new(0)); + let first = Arc::clone(&count); + pool.spawn(ThreadIntent::Worker, move || { + first.fetch_add(669, Ordering::SeqCst); + }); + let second = Arc::clone(&count); + pool.spawn(ThreadIntent::LatencySensitive, move || { + second.fetch_add(668, Ordering::SeqCst); + }); + spawn_scoped_worker(&pool); + assert_eq!(count.load(Ordering::SeqCst), 1337); + } + + #[test] + fn spawn_handles_panicking_function() { + let pool = Pool::new(1); + pool.spawn(ThreadIntent::Worker, || panic!()); + let executed = Arc::new(AtomicBool::new(false)); + let executed_clone = Arc::clone(&executed); + pool.spawn(ThreadIntent::Worker, move || { + executed_clone.store(true, Ordering::SeqCst); + }); + spawn_scoped_worker(&pool); + assert!(executed.load(Ordering::SeqCst)); + } + + #[test] + fn scoped_executes_borrowing_function() { + let pool = Pool::new(1); + let value = 42; + let ran = AtomicBool::new(false); + let result = pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || { + ran.store(true, Ordering::SeqCst); + }); + value + 1 + }); + assert_eq!(result, 43); + assert!(ran.load(Ordering::SeqCst)); + } + + #[test] + fn scoped_executes_multiple_functions() { + let pool = Pool::new(2); + let value = AtomicUsize::new(0); + pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || { + value.fetch_add(9, Ordering::SeqCst); + }); + scope.spawn(ThreadIntent::LatencySensitive, || { + value.fetch_add(10, Ordering::SeqCst); + }); + }); + assert_eq!(value.load(Ordering::SeqCst), 19); + } + + #[test] + fn scoped_handles_panicking_function() { + let pool = Pool::new(1); + pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || panic!()); + }); + let ran = AtomicBool::new(false); + pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || ran.store(true, Ordering::SeqCst)); + }); + assert!(ran.load(Ordering::SeqCst)); + } + + #[test] + fn scoped_returns_result_after_tasks_finish() { + let pool = Pool::new(2); + let value = AtomicUsize::new(0); + let result = pool.scoped(|scope| { + scope.spawn(ThreadIntent::Worker, || { + value.store(19991005, Ordering::SeqCst); + }); + 0xC0FFEE + }); + assert_eq!(result, 0xC0FFEE); + assert_eq!(value.load(Ordering::SeqCst), 19991005); + } + + #[test] + fn zero_thread_pool_starts_empty() { + let pool = Pool::new(0); + assert_eq!(pool.len(), 0); + assert!(pool.is_empty()); + } +} From fde3f54635d85899f22ef78e10d12d09b32a61d7 Mon Sep 17 00:00:00 2001 From: Benjamin Brienen Date: Fri, 13 Nov 2026 20:17:40 +0100 Subject: [PATCH 07/48] use trusted publishing --- .../rust-analyzer/.github/workflows/release.yaml | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 29a4020baf743..38326577399b9 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -10,6 +10,8 @@ on: - release - trigger-nightly +permissions: {} + env: CARGO_INCREMENTAL: 0 CARGO_NET_RETRY: 10 @@ -201,6 +203,8 @@ jobs: publish: if: ${{ github.repository == 'rust-lang/rust-analyzer' || github.event_name == 'workflow_dispatch' }} runs-on: ubuntu-latest + permissions: + contents: write needs: ["dist", "dist-x86_64-unknown-linux-musl"] steps: - name: Checkout repository @@ -248,12 +252,18 @@ jobs: name: publish-extension (${{ matrix.cmd }}) runs-on: ubuntu-latest needs: publish + environment: publish-extension + permissions: + contents: read + id-token: write strategy: fail-fast: false matrix: include: - cmd: vsce + authentication: --oidc - cmd: ovsx + authentication: --trusted-publishing steps: - name: Install Nodejs uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 @@ -276,8 +286,6 @@ jobs: - name: Publish Extension if: github.repository == 'rust-lang/rust-analyzer' - env: - PUBLISH_PAT: ${{ (matrix.cmd == 'vsce' && secrets.MARKETPLACE_TOKEN) || (matrix.cmd == 'ovsx' && secrets.OPENVSX_TOKEN) }} working-directory: ./editors/code - run: npx ${{ matrix.cmd }} publish --skip-duplicate --pat "$PUBLISH_PAT" --packagePath ../../dist/rust-analyzer-*.vsix ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} + run: npx ${{ matrix.cmd }} publish --skip-duplicate ${{ matrix.authentication }} --packagePath ../../dist/rust-analyzer-*.vsix ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} timeout-minutes: 2 From 217ada18aa1619c5cf38976d2053a0dac5860cf2 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Sat, 31 Oct 2026 22:17:38 +0000 Subject: [PATCH 08/48] ops: Disable credential persistence Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- .../.github/workflows/autopublish.yaml | 1 + .../rust-analyzer/.github/workflows/ci.yaml | 17 +++++++++++++++++ .../.github/workflows/coverage.yaml | 2 ++ .../rust-analyzer/.github/workflows/fuzz.yml | 1 + .../.github/workflows/metrics.yaml | 6 ++++++ .../.github/workflows/publish-libs.yaml | 1 + .../.github/workflows/release.yaml | 4 ++++ .../.github/workflows/rustdoc.yaml | 2 ++ .../.github/workflows/update-generated.yml | 2 ++ 9 files changed, 36 insertions(+) diff --git a/src/tools/rust-analyzer/.github/workflows/autopublish.yaml b/src/tools/rust-analyzer/.github/workflows/autopublish.yaml index ec5671b10bf37..56cbde5ef5cb9 100644 --- a/src/tools/rust-analyzer/.github/workflows/autopublish.yaml +++ b/src/tools/rust-analyzer/.github/workflows/autopublish.yaml @@ -23,6 +23,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 + persist-credentials: false # https://github.com/jlumbroso/free-disk-space/blob/main/action.yml - name: Free up some disk space diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index eb8863ce783bd..46c20aa8b09fa 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -31,6 +31,8 @@ jobs: typescript: ${{ steps.filter.outputs.typescript }} steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1 id: filter with: @@ -52,6 +54,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false - name: Install rustup-toolchain-install-master run: cargo install --locked rustup-toolchain-install-master@1.11.0 @@ -95,6 +98,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false - name: Install Rust toolchain run: | @@ -145,6 +149,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -173,6 +179,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -189,6 +197,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false # Note that clippy output is currently dependent on whether rust-src is installed, # https://github.com/rust-lang/rust-clippy/issues/14625 @@ -211,6 +221,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -241,6 +253,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | @@ -269,6 +283,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Nodejs uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 @@ -330,6 +346,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.pull_request.head.sha }} + persist-credentials: false - name: check for typos run: typos diff --git a/src/tools/rust-analyzer/.github/workflows/coverage.yaml b/src/tools/rust-analyzer/.github/workflows/coverage.yaml index 19a132a496778..875335bccac51 100644 --- a/src/tools/rust-analyzer/.github/workflows/coverage.yaml +++ b/src/tools/rust-analyzer/.github/workflows/coverage.yaml @@ -16,6 +16,8 @@ jobs: RUSTC_BOOTSTRAP: 1 steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: | diff --git a/src/tools/rust-analyzer/.github/workflows/fuzz.yml b/src/tools/rust-analyzer/.github/workflows/fuzz.yml index 8742cdf6103a3..15ac3007d7bab 100644 --- a/src/tools/rust-analyzer/.github/workflows/fuzz.yml +++ b/src/tools/rust-analyzer/.github/workflows/fuzz.yml @@ -31,6 +31,7 @@ jobs: with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 1 + persist-credentials: false - name: Install Rust toolchain run: | diff --git a/src/tools/rust-analyzer/.github/workflows/metrics.yaml b/src/tools/rust-analyzer/.github/workflows/metrics.yaml index 413e97dadad6d..a2eb9e247d507 100644 --- a/src/tools/rust-analyzer/.github/workflows/metrics.yaml +++ b/src/tools/rust-analyzer/.github/workflows/metrics.yaml @@ -24,6 +24,8 @@ jobs: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Cache cargo uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 @@ -67,6 +69,8 @@ jobs: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Restore target cache uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 @@ -90,6 +94,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Download metrics uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 diff --git a/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml b/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml index 4b459d6a96704..2c11073bfa95f 100644 --- a/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml +++ b/src/tools/rust-analyzer/.github/workflows/publish-libs.yaml @@ -21,6 +21,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: 0 + persist-credentials: false - name: Install Rust toolchain run: rustup update --no-self-update stable diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 38326577399b9..6095b5225e45c 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -83,6 +83,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - name: Install target dependencies if: ${{ matrix.target == 'arm-unknown-linux-gnueabihf' }} @@ -175,6 +176,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - name: Dist run: cargo xtask dist --client-patch-version ${{ github.run_number }} --jemalloc @@ -211,6 +213,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - name: Set release tag run: | @@ -274,6 +277,7 @@ jobs: uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: fetch-depth: ${{ env.FETCH_DEPTH }} + persist-credentials: false - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: diff --git a/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml b/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml index 29f03ffcc92fb..2458f64caed70 100644 --- a/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml +++ b/src/tools/rust-analyzer/.github/workflows/rustdoc.yaml @@ -22,6 +22,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install Rust toolchain run: rustup update --no-self-update stable diff --git a/src/tools/rust-analyzer/.github/workflows/update-generated.yml b/src/tools/rust-analyzer/.github/workflows/update-generated.yml index 611d7d40bc6a2..963645b02d7be 100644 --- a/src/tools/rust-analyzer/.github/workflows/update-generated.yml +++ b/src/tools/rust-analyzer/.github/workflows/update-generated.yml @@ -19,6 +19,8 @@ jobs: steps: - name: Checkout repository uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + persist-credentials: false - name: Install nightly run: rustup default nightly From 8ca56dbfdd3e336eeff2e09a57b2d6d7ff6ba516 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Sun, 1 Nov 2026 21:50:30 +0000 Subject: [PATCH 09/48] ops: Prefer `GITHUB_REF` over `github.ref` This environment variable is provided by default. See: https://docs.github.com/en/actions/reference/workflows-and-actions/variables#default-environment-variables Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 6095b5225e45c..28db5da39b9ed 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -217,7 +217,7 @@ jobs: - name: Set release tag run: | - if [ "${{ github.ref }}" = "refs/heads/release" ]; then + if [ "${GITHUB_REF}" = "refs/heads/release" ]; then git fetch --tags today=$(date --iso -u) last_tag=$(git tag -l "${today}*" | sort -V | tail -n1) From 2d1616c891c7c0a2e668cd537b7877c3bc6ba038 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:42:14 +0000 Subject: [PATCH 10/48] ops: Prefer `GITHUB_RUN_ID` over `github.run_id` This environment variable is provided by default. See: https://docs.github.com/en/actions/reference/workflows-and-actions/variables#default-environment-variables Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index 46c20aa8b09fa..7c944989fa62f 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -397,4 +397,4 @@ jobs: -H "Accept: application/vnd.github.v3+json" \ -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \ -H "X-GitHub-Api-Version: 2022-11-28" \ - https://api.github.com/repos/${{ github.repository }}/actions/runs/${{ github.run_id }}/cancel + "https://api.github.com/repos/${{ github.repository }}/actions/runs/${GITHUB_RUN_ID}/cancel" From 5dd5cfbe3e54da07f95694e7f4bd407c8036d8de Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:36:11 +0000 Subject: [PATCH 11/48] ops: Prefer `GITHUB_RUN_NUMBER` over `github.run_number` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/release.yaml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 28db5da39b9ed..dc93e0347e1f7 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -74,6 +74,10 @@ jobs: runs-on: ${{ matrix.os }} container: ${{ matrix.container }} + defaults: + run: + shell: bash + env: RA_TARGET: ${{ matrix.target }} ALLOCATOR_FLAG: ${{ matrix.allocator != 'system' && format('--{0}', matrix.allocator) || '' }} @@ -113,7 +117,7 @@ jobs: rustup target add ${{ matrix.target }} - name: Dist - run: cargo xtask dist --client-patch-version ${{ github.run_number }} ${{ env.ALLOCATOR_FLAG }} ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} + run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} ${{ env.ALLOCATOR_FLAG }} ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} - run: npm ci working-directory: editors/code @@ -179,7 +183,7 @@ jobs: persist-credentials: false - name: Dist - run: cargo xtask dist --client-patch-version ${{ github.run_number }} --jemalloc + run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} --jemalloc - run: npm ci working-directory: editors/code From c76f9d588d0977475a594c996b9822902d4ab406 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:57:30 +0000 Subject: [PATCH 12/48] ops: Prefer `GITHUB_REPOSITORY` over `github.repository` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index 7c944989fa62f..d283f8f9f75bd 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -397,4 +397,4 @@ jobs: -H "Accept: application/vnd.github.v3+json" \ -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \ -H "X-GitHub-Api-Version: 2022-11-28" \ - "https://api.github.com/repos/${{ github.repository }}/actions/runs/${GITHUB_RUN_ID}/cancel" + "https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/cancel" From 892e0c24ac734190985c4afac8afee1c2712ff6b Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:59:16 +0000 Subject: [PATCH 13/48] ops: Prefer shell expansion over template expansion Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index dc93e0347e1f7..c2a65e0157f8b 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -117,7 +117,7 @@ jobs: rustup target add ${{ matrix.target }} - name: Dist - run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} ${{ env.ALLOCATOR_FLAG }} ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} + run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} ${ALLOCATOR_FLAG} ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} - run: npm ci working-directory: editors/code From 3ab2eaa034922fd47fd26e9b7b9000c63461f55c Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:50:09 +0000 Subject: [PATCH 14/48] ops: Expand `matrix.target` in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/ci.yaml | 12 +++++++++--- .../rust-analyzer/.github/workflows/release.yaml | 11 ++++++++--- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index d283f8f9f75bd..846b8656d34bc 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -259,15 +259,21 @@ jobs: - name: Install Rust toolchain run: | rustup update --no-self-update stable - rustup target add ${{ matrix.target }} + rustup target add ${TARGET} + env: + TARGET: ${{ matrix.target }} # - name: Cache Dependencies # uses: Swatinem/rust-cache@9d47c6ad4b02e050fd481d890b2ea34778fd09d6 - - run: cargo check --target=${{ matrix.target }} --all-targets -p ide + - run: cargo check --target=${TARGET} --all-targets -p ide if: ${{ matrix.ide-only }} - - run: cargo check --target=${{ matrix.target }} --all-targets + env: + TARGET: ${{ matrix.target }} + - run: cargo check --target=${TARGET} --all-targets if: ${{ !matrix.ide-only }} + env: + TARGET: ${{ matrix.target }} typescript: needs: changes diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index c2a65e0157f8b..552fa60dfa403 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -114,7 +114,9 @@ jobs: rustup update --no-self-update stable # llvm-tools contain the llvm-profdata tool which is needed for PGO rustup component add rust-src ${{ matrix.pgo && 'llvm-tools' || '' }} - rustup target add ${{ matrix.target }} + rustup target add ${TARGET} + env: + TARGET: ${{ matrix.target }} - name: Dist run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} ${ALLOCATOR_FLAG} ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} @@ -145,13 +147,16 @@ jobs: - name: Run analysis-stats on rust-analyzer if: matrix.target == 'x86_64-unknown-linux-gnu' - run: target/${{ matrix.target }}/release/rust-analyzer analysis-stats . -q + run: target/${TARGET}/release/rust-analyzer analysis-stats . -q + env: + TARGET: ${{ matrix.target }} - name: Run analysis-stats on rust std library if: matrix.target == 'x86_64-unknown-linux-gnu' env: + TARGET: ${{ matrix.target }} RUSTC_BOOTSTRAP: 1 - run: target/${{ matrix.target }}/release/rust-analyzer analysis-stats --with-deps --no-sysroot --no-test $(rustc --print sysroot)/lib/rustlib/src/rust/library/std -q + run: target/${TARGET}/release/rust-analyzer analysis-stats --with-deps --no-sysroot --no-test $(rustc --print sysroot)/lib/rustlib/src/rust/library/std -q - name: Upload artifacts uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 From 2c5f92baa32bd634f9bc9e7a8ae811e6c07efe3c Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:03:39 +0000 Subject: [PATCH 15/48] ops: Expand `matrix.code-target` in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/release.yaml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 552fa60dfa403..95e02c0039621 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -126,12 +126,16 @@ jobs: - name: Package Extension (release) if: github.ref == 'refs/heads/release' && matrix.code-target - run: npx vsce package -o "../../dist/rust-analyzer-${{ matrix.code-target }}.vsix" --target ${{ matrix.code-target }} + run: npx vsce package -o "../../dist/rust-analyzer-${CODE_TARGET}.vsix" --target ${CODE_TARGET} + env: + CODE_TARGET: ${{ matrix.code-target }} working-directory: editors/code - name: Package Extension (nightly) if: github.ref != 'refs/heads/release' && matrix.code-target - run: npx vsce package -o "../../dist/rust-analyzer-${{ matrix.code-target }}.vsix" --target ${{ matrix.code-target }} --pre-release + run: npx vsce package -o "../../dist/rust-analyzer-${CODE_TARGET}.vsix" --target ${CODE_TARGET} --pre-release + env: + CODE_TARGET: ${{ matrix.code-target }} working-directory: editors/code - if: matrix.target == 'x86_64-unknown-linux-gnu' From 3843e7a84949a163459ee73222be9c1874038be7 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:05:39 +0000 Subject: [PATCH 16/48] ops: Expand `matrix.names` in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/metrics.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/metrics.yaml b/src/tools/rust-analyzer/.github/workflows/metrics.yaml index a2eb9e247d507..fa2e5d5dc048f 100644 --- a/src/tools/rust-analyzer/.github/workflows/metrics.yaml +++ b/src/tools/rust-analyzer/.github/workflows/metrics.yaml @@ -79,7 +79,9 @@ jobs: key: ${{ runner.os }}-target-${{ github.sha }} - name: Collect metrics - run: cargo xtask metrics "${{ matrix.names }}" + run: cargo xtask metrics "${NAMES}" + env: + NAMES: ${{ matrix.names }} - name: Upload metrics uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 From b2d81934e3b797a0c41f68bf95ceb551211279bd Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:10:32 +0000 Subject: [PATCH 17/48] ops: Expand `secrets.GITHUB_TOKEN` in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/ci.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index 846b8656d34bc..d8b58a2a04014 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -401,6 +401,8 @@ jobs: curl -L \ -X POST \ -H "Accept: application/vnd.github.v3+json" \ - -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \ + -H "Authorization: Bearer ${GITHUB_TOKEN}" \ -H "X-GitHub-Api-Version: 2022-11-28" \ "https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/cancel" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From ff75e737907a4ca52ad11a030f36cb44cc300990 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:13:50 +0000 Subject: [PATCH 18/48] ops: Expand `secrets.METRICS_DEPLOY_KEY` in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/metrics.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/metrics.yaml b/src/tools/rust-analyzer/.github/workflows/metrics.yaml index fa2e5d5dc048f..d75455c628e74 100644 --- a/src/tools/rust-analyzer/.github/workflows/metrics.yaml +++ b/src/tools/rust-analyzer/.github/workflows/metrics.yaml @@ -108,7 +108,7 @@ jobs: - name: Combine json run: | mkdir ~/.ssh - echo "${{ secrets.METRICS_DEPLOY_KEY }}" > ~/.ssh/id_ed25519 + echo "${METRICS_DEPLOY_KEY}" > ~/.ssh/id_ed25519 chmod 600 ~/.ssh/id_ed25519 chmod 700 ~/.ssh @@ -118,3 +118,5 @@ jobs: git add . git -c user.name=Bot -c user.email=dummy@example.com commit --message 📈 git push origin master + env: + METRICS_DEPLOY_KEY: ${{ secrets.METRICS_DEPLOY_KEY }} From 2ae94098b806bee4b470956888598146cdf61118 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:18:04 +0000 Subject: [PATCH 19/48] ops: Expand `matrix.cmd` in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/release.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 95e02c0039621..c716db9e18b48 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -303,6 +303,8 @@ jobs: - name: Publish Extension if: github.repository == 'rust-lang/rust-analyzer' + env: + COMMAND: ${{ matrix.cmd }} working-directory: ./editors/code - run: npx ${{ matrix.cmd }} publish --skip-duplicate ${{ matrix.authentication }} --packagePath ../../dist/rust-analyzer-*.vsix ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} + run: npx ${COMMAND} publish --skip-duplicate ${{ matrix.authentication }} --packagePath ../../dist/rust-analyzer-*.vsix ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} timeout-minutes: 2 From 2a6e8c8c2d7acd46526f1988f5fe06e0e26c91c0 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:20:48 +0000 Subject: [PATCH 20/48] ops: Expand pre-release flag check in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/release.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index c716db9e18b48..30a5e8b36346f 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -305,6 +305,7 @@ jobs: if: github.repository == 'rust-lang/rust-analyzer' env: COMMAND: ${{ matrix.cmd }} + MAYBE_PRE_RELEASE: ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} working-directory: ./editors/code - run: npx ${COMMAND} publish --skip-duplicate ${{ matrix.authentication }} --packagePath ../../dist/rust-analyzer-*.vsix ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} + run: npx ${COMMAND} publish --skip-duplicate ${{ matrix.authentication }} --packagePath ../../dist/rust-analyzer-*.vsix ${MAYBE_PRE_RELEASE} timeout-minutes: 2 From ec2e3dcde875eb2b5dee955e0f76a8cd32425a15 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:23:59 +0000 Subject: [PATCH 21/48] ops: Expand `llvm-tools` component optional in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/release.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 30a5e8b36346f..877f3d6a205d2 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -113,10 +113,11 @@ jobs: run: | rustup update --no-self-update stable # llvm-tools contain the llvm-profdata tool which is needed for PGO - rustup component add rust-src ${{ matrix.pgo && 'llvm-tools' || '' }} + rustup component add rust-src ${MAYBE_LLVM_TOOLS} rustup target add ${TARGET} env: TARGET: ${{ matrix.target }} + MAYBE_LLVM_TOOLS: ${{ matrix.pgo && 'llvm-tools' || '' }} - name: Dist run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} ${ALLOCATOR_FLAG} ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} From 84455d4cf470b7e3289cf2dfcb05989cd1d9a95b Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:25:52 +0000 Subject: [PATCH 22/48] ops: Expand PGO optional in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/release.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index 877f3d6a205d2..ab915610ed85c 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -120,7 +120,9 @@ jobs: MAYBE_LLVM_TOOLS: ${{ matrix.pgo && 'llvm-tools' || '' }} - name: Dist - run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} ${ALLOCATOR_FLAG} ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} + run: cargo xtask dist --client-patch-version ${GITHUB_RUN_NUMBER} ${ALLOCATOR_FLAG} ${MAYBE_PGO} + env: + MAYBE_PGO: ${{ matrix.pgo && format('--pgo {0}', matrix.pgo) || ''}} - run: npm ci working-directory: editors/code From 3d06c34f9deec1a1c329bd68dee70e1fbf821e22 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:29:17 +0000 Subject: [PATCH 23/48] ops: Expand `toJson(needs)` in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/ci.yaml | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/tools/rust-analyzer/.github/workflows/ci.yaml b/src/tools/rust-analyzer/.github/workflows/ci.yaml index d8b58a2a04014..02440e0ea109d 100644 --- a/src/tools/rust-analyzer/.github/workflows/ci.yaml +++ b/src/tools/rust-analyzer/.github/workflows/ci.yaml @@ -383,9 +383,11 @@ jobs: - name: Conclusion run: | # Print the dependent jobs to see them in the CI log - jq -C <<< '${{ toJson(needs) }}' + jq -C <<< "${JSON_NEEDS}" # Check if all jobs that we depend on (in the needs array) were successful (or have been skipped). - jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< '${{ toJson(needs) }}' + jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< "${JSON_NEEDS}" + env: + JSON_NEEDS: ${{ toJson(needs) }} cancel-if-matrix-failed: needs: rust @@ -394,7 +396,7 @@ jobs: steps: - name: Cancel parallel jobs run: | - if jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< '${{ toJson(needs) }}'; then + if jq --exit-status 'all(.result == "success" or .result == "skipped")' <<< "${JSON_NEEDS}"; then exit 0 fi # https://docs.github.com/en/rest/actions/workflow-runs?apiVersion=2022-11-28#cancel-a-workflow-run @@ -405,4 +407,5 @@ jobs: -H "X-GitHub-Api-Version: 2022-11-28" \ "https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/cancel" env: + JSON_NEEDS: ${{ toJson(needs) }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From c3e6cc66edaa0838b4bed33ecf8679584b239a01 Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Wed, 4 Nov 2026 18:10:09 +0000 Subject: [PATCH 24/48] ops: Deduplicate environment variables a bit Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- .../rust-analyzer/.github/workflows/release.yaml | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index ab915610ed85c..f32d7f1958cd2 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -80,6 +80,7 @@ jobs: env: RA_TARGET: ${{ matrix.target }} + CODE_TARGET: ${{ matrix.code-target }} ALLOCATOR_FLAG: ${{ matrix.allocator != 'system' && format('--{0}', matrix.allocator) || '' }} steps: @@ -114,9 +115,8 @@ jobs: rustup update --no-self-update stable # llvm-tools contain the llvm-profdata tool which is needed for PGO rustup component add rust-src ${MAYBE_LLVM_TOOLS} - rustup target add ${TARGET} + rustup target add ${RA_TARGET} env: - TARGET: ${{ matrix.target }} MAYBE_LLVM_TOOLS: ${{ matrix.pgo && 'llvm-tools' || '' }} - name: Dist @@ -130,15 +130,11 @@ jobs: - name: Package Extension (release) if: github.ref == 'refs/heads/release' && matrix.code-target run: npx vsce package -o "../../dist/rust-analyzer-${CODE_TARGET}.vsix" --target ${CODE_TARGET} - env: - CODE_TARGET: ${{ matrix.code-target }} working-directory: editors/code - name: Package Extension (nightly) if: github.ref != 'refs/heads/release' && matrix.code-target run: npx vsce package -o "../../dist/rust-analyzer-${CODE_TARGET}.vsix" --target ${CODE_TARGET} --pre-release - env: - CODE_TARGET: ${{ matrix.code-target }} working-directory: editors/code - if: matrix.target == 'x86_64-unknown-linux-gnu' @@ -154,16 +150,13 @@ jobs: - name: Run analysis-stats on rust-analyzer if: matrix.target == 'x86_64-unknown-linux-gnu' - run: target/${TARGET}/release/rust-analyzer analysis-stats . -q - env: - TARGET: ${{ matrix.target }} + run: target/${RA_TARGET}/release/rust-analyzer analysis-stats . -q - name: Run analysis-stats on rust std library if: matrix.target == 'x86_64-unknown-linux-gnu' env: - TARGET: ${{ matrix.target }} RUSTC_BOOTSTRAP: 1 - run: target/${TARGET}/release/rust-analyzer analysis-stats --with-deps --no-sysroot --no-test $(rustc --print sysroot)/lib/rustlib/src/rust/library/std -q + run: target/${RA_TARGET}/release/rust-analyzer analysis-stats --with-deps --no-sysroot --no-test $(rustc --print sysroot)/lib/rustlib/src/rust/library/std -q - name: Upload artifacts uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 From b7198fe32f0d22dc3e57682e13f8c7110c28186f Mon Sep 17 00:00:00 2001 From: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> Date: Tue, 17 Nov 2026 05:53:44 +0000 Subject: [PATCH 25/48] ops: Expand `matrix.authentication` in `env` Signed-off-by: hashcatHitman <155700084+hashcatHitman@users.noreply.github.com> --- src/tools/rust-analyzer/.github/workflows/release.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/.github/workflows/release.yaml b/src/tools/rust-analyzer/.github/workflows/release.yaml index f32d7f1958cd2..88afab204d6ec 100644 --- a/src/tools/rust-analyzer/.github/workflows/release.yaml +++ b/src/tools/rust-analyzer/.github/workflows/release.yaml @@ -302,6 +302,7 @@ jobs: env: COMMAND: ${{ matrix.cmd }} MAYBE_PRE_RELEASE: ${{ github.ref != 'refs/heads/release' && '--pre-release' || '' }} + AUTHENTICATION: ${{ matrix.authentication }} working-directory: ./editors/code - run: npx ${COMMAND} publish --skip-duplicate ${{ matrix.authentication }} --packagePath ../../dist/rust-analyzer-*.vsix ${MAYBE_PRE_RELEASE} + run: npx ${COMMAND} publish --skip-duplicate ${AUTHENTICATION} --packagePath ../../dist/rust-analyzer-*.vsix ${MAYBE_PRE_RELEASE} timeout-minutes: 2 From 68d90efc37d206a6045e9dbccff7fe4c6f386815 Mon Sep 17 00:00:00 2001 From: A4-Tacks Date: Tue, 17 Nov 2026 20:46:17 +0800 Subject: [PATCH 26/48] minor: short too long roots scanned std path Example --- **Before this PR** ```text Roots Scanned 15/16: /home/user/.rustup/toolchains/nightly-aarch64-unknown-linux-gnu/lib/rustlib/src/rust/library/std 93% ``` **After this PR** ```text Roots Scanned 15/16: library/std 93% ``` --- src/tools/rust-analyzer/crates/paths/src/lib.rs | 6 ++++++ .../rust-analyzer/crates/rust-analyzer/src/main_loop.rs | 6 +++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/paths/src/lib.rs b/src/tools/rust-analyzer/crates/paths/src/lib.rs index d6d9ed4676c16..5ded23c149bbb 100644 --- a/src/tools/rust-analyzer/crates/paths/src/lib.rs +++ b/src/tools/rust-analyzer/crates/paths/src/lib.rs @@ -308,6 +308,12 @@ impl AbsPath { self.0.components() } // endregion:delegate-methods + + /// `"/a/b/c/d/e".short_relative_by("b/c")` -> `"d/e"` + pub fn short_relative_by(&self, dummy: impl AsRef) -> Option<&RelPath> { + let prefix = self.0.ancestors().find(|prefix| prefix.ends_with(&dummy))?; + self.strip_prefix(AbsPath::assert(prefix)) + } } impl fmt::Display for AbsPath { diff --git a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs index 3cd7a9ac9282e..68d7164698a2b 100644 --- a/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs +++ b/src/tools/rust-analyzer/crates/rust-analyzer/src/main_loop.rs @@ -1034,11 +1034,15 @@ impl GlobalState { let mut message = format!("{n_done}/{n_total}"); if let Some(dir) = dir { + let common_std = "lib/rustlib/src/rust"; message += &format!( ": {}", match dir.strip_prefix(self.config.workspace_root_for(&dir)) { Some(relative_path) => relative_path.as_utf8_path(), - None => dir.as_ref(), + None => match dir.short_relative_by(common_std) { + Some(short) => short.as_ref(), + None => dir.as_ref(), + }, } ); } From 12af71a473a24d71dac675a943e64b4e8790520e Mon Sep 17 00:00:00 2001 From: Wilfred Hughes Date: Mon, 16 Nov 2026 13:57:33 +0000 Subject: [PATCH 27/48] fix: Accidentally quadratic performance in type inference Previously, r-a didn't implement well-formedness (WF) checks on any types, treating them all as ambiguous. Unfortunately, we try to resolve obligations after essentially every expression: https://github.com/rust-lang/rust-analyzer/blob/ff7105dd728897503481c79727cd6ead881d80a6/crates/hir-ty/src/infer/expr.rs#L867 and when we resolve obligations, we collect all obligations and then re-register ambiguous ones: https://github.com/rust-lang/rust-analyzer/blob/ff7105dd728897503481c79727cd6ead881d80a6/crates/hir-ty/src/next_solver/fulfill.rs#L213 So given N expressions containing closures, we end up doing O(N^2) work (1 obligation after the first expression, 2 obligations after the second expression, etc). Instead, treat all types as well-formed. This also allows normalisation to work in more scenarios, hence one unit test now showing a concrete type instead of `impl Trait`. For reference, the WF implementation in rustc is here: https://github.com/rust-lang/rust/blob/58cf8f9c35b355199727627d07ae34a4e2846d67/compiler/rustc_trait_selection/src/solve/delegate.rs#L338-L352 https://github.com/rust-lang/rust/blob/58cf8f9c35b355199727627d07ae34a4e2846d67/compiler/rustc_trait_selection/src/traits/wf.rs#L93-L125 AI disclosure: Initial investigation and implementation with an LLM, but final implementation and review by me. Comments are written by me or copied from rustc verbatim. --- src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs | 2 +- src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs b/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs index 5332bebae4d0d..f027dd9b223de 100644 --- a/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs +++ b/src/tools/rust-analyzer/crates/hir-ide/src/tests/traits.rs @@ -1422,7 +1422,7 @@ fn foo() -> (impl FnOnce(&str, T), impl Trait) { } "#, expect![[r#" - 134..165 '{ ...(C)) }': (impl FnOnce(&'? str, T), impl Trait) + 134..165 '{ ...(C)) }': (impl FnOnce(&'? str, T), Bar) 140..163 '(|inpu...ar(C))': (impl FnOnce(&'? str, T), Bar) 141..154 '|input, t| {}': impl FnOnce(&'? str, T) 142..147 'input': &'? str diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs index fb652d035eaca..6709da7afb212 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/next_solver/solver.rs @@ -97,7 +97,7 @@ impl<'db> SolverDelegate for SolverContext<'db> { >, > { // FIXME(next-solver): - None + Some(Vec::new()) } fn make_deduplicated_region_constraints( From bf1a91ec773a61845035230883daadf6583d07a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Ber=C3=A1nek?= Date: Wed, 18 Nov 2026 20:04:56 +0100 Subject: [PATCH 28/48] Add `r? @ghost` Josh push PR suffix --- src/tools/rust-analyzer/josh-sync.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/tools/rust-analyzer/josh-sync.toml b/src/tools/rust-analyzer/josh-sync.toml index a12cfa1b5cbd5..5cd30792f9aac 100644 --- a/src/tools/rust-analyzer/josh-sync.toml +++ b/src/tools/rust-analyzer/josh-sync.toml @@ -4,3 +4,6 @@ filter = ":rev(55d9a533b309119c8acd13061581b43ae8840823:prefix=src/tools/rust-an [[post-pull]] cmd = ["cargo", "fmt"] commit-message = "Format code" + +[push-pr] +suffix = "r? @ghost" From 2423345a95002ef659b2bd198566ee87c573751c Mon Sep 17 00:00:00 2001 From: The rustc-josh-sync Cronjob Bot Date: Thu, 19 Nov 2026 04:10:25 +0000 Subject: [PATCH 29/48] Prepare for merging from rust-lang/rust This updates the rust-version file to e3b9a8345a8a58fda3ac9446c532625d5a59acd8. --- src/tools/rust-analyzer/rust-version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/rust-version b/src/tools/rust-analyzer/rust-version index 2ab8919989008..188d50ebbcd66 100644 --- a/src/tools/rust-analyzer/rust-version +++ b/src/tools/rust-analyzer/rust-version @@ -1 +1 @@ -4c46afa63688fb473618f9b3553d70b0c15a88eb +e3b9a8345a8a58fda3ac9446c532625d5a59acd8 From 4f4eae5fc6aa6092ba61fdcaaba17b4a2c9da199 Mon Sep 17 00:00:00 2001 From: A4-Tacks Date: Thu, 19 Nov 2026 16:19:38 +0800 Subject: [PATCH 30/48] fix: allow notable_trait attr args On `rustc 1.102.0-nightly (9c5648833 2026-11-10)`, Some std defs `#[notable_trait]` -> `#[doc(notable_trait(color = "transparent"))]` --- src/tools/rust-analyzer/crates/hir-def/src/attrs.rs | 1 + src/tools/rust-analyzer/crates/ide/src/hover/tests.rs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs b/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs index 84559b46cc5b7..b54fb90b8ec84 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/attrs.rs @@ -1411,6 +1411,7 @@ fn next_doc_expr(it: &mut Peekable) -> Option { return None; } } + Some(NodeOrToken::Node(_)) if name == "notable_trait" => DocAtom::Flag(name), Some(NodeOrToken::Node(subtree)) => { if name != "alias" { return None; diff --git a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs index e14e9d512b7bf..5c35b9e26559c 100644 --- a/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs +++ b/src/tools/rust-analyzer/crates/ide/src/hover/tests.rs @@ -9580,7 +9580,7 @@ fn notable_ranged() { r#" //- minicore: future, iterator struct S; -#[doc(notable_trait)] +#[doc(notable_trait(color = "transparent"))] trait Notable {} impl Notable for S {} impl core::future::Future for S { From d1b11adef25f67ce0f946d6e12ae874d72717838 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Thu, 19 Nov 2026 11:37:38 +0100 Subject: [PATCH 31/48] Enable static-pie on all Musl targets This enables ASLR and I don't see a reason not to enable it outside x86_64. Musl supports it just fine and in fact Alpine Linux already patches rustc to enable it on all Musl targets. --- compiler/rustc_target/src/spec/base/linux_musl.rs | 1 + .../rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_target/src/spec/base/linux_musl.rs b/compiler/rustc_target/src/spec/base/linux_musl.rs index 6d3124b559b11..c7286f79ea124 100644 --- a/compiler/rustc_target/src/spec/base/linux_musl.rs +++ b/compiler/rustc_target/src/spec/base/linux_musl.rs @@ -6,6 +6,7 @@ pub(crate) fn opts() -> TargetOptions { pre_link_objects_self_contained: crt_objects::pre_musl_self_contained(), post_link_objects_self_contained: crt_objects::post_musl_self_contained(), link_self_contained: LinkSelfContainedDefault::InferredForMusl, + static_position_independent_executables: true, ..base::linux::opts() } } diff --git a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs index a664f22479913..8c82639c599ac 100644 --- a/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs +++ b/compiler/rustc_target/src/spec/targets/x86_64_unknown_linux_musl.rs @@ -9,7 +9,6 @@ pub(crate) fn target() -> Target { base.max_atomic_width = Some(64); base.add_pre_link_args(LinkerFlavor::Gnu(Cc::Yes, Lld::No), &["-m64"]); base.stack_probes = StackProbeType::Inline; - base.static_position_independent_executables = true; base.supported_sanitizers = SanitizerSet::ADDRESS | SanitizerSet::CFI | SanitizerSet::LEAK From f110dbb6428cc96652f9f5b37a6b72e9ba035bc8 Mon Sep 17 00:00:00 2001 From: Gary Guo Date: Thu, 19 Nov 2026 15:24:00 +0000 Subject: [PATCH 32/48] fix: make sure copied lock files are writable When rust-analyzer copies a lock file, it will not set `--locked` in FetchMetadata. Currently, rust-analyzer copies with fs::copy which retains permission bits; if the original lock file is not writable (as is the case in Nix), the copied lock file will also not be writable and `FetchMetadata` will fail. Fix it by using read + write. Signed-off-by: Gary Guo --- .../crates/project-model/src/cargo_config_file.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs b/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs index 126c0b41bb9f4..8ad210724cd0b 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/cargo_config_file.rs @@ -196,7 +196,8 @@ pub(crate) fn make_lockfile_copy( let temp_dir = NamedTempDir::new("rust-analyzer").ok()?; let path = temp_dir.path().join("Cargo.lock"); - std::fs::copy(lockfile_path.as_std_path(), &path).ok()?; + // `fs::read` + `fs::write` instead of `fs::copy` to avoid copying permission bits. + std::fs::write(&path, std::fs::read(lockfile_path.as_std_path()).ok()?).ok()?; Some(LockfileCopy { path: Utf8PathBuf::from_path_buf(path).ok()?, usage, _temp_dir: temp_dir }) } From d064780aa48149e42721c86aeb927c1e4bdadc5b Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Thu, 19 Nov 2026 18:49:32 +0200 Subject: [PATCH 33/48] Exclude proc macro crates from lang item computations for their dependencies Since they can have their own sysroot and duplicate lang items are Not Good. --- .../crates/hir-def/src/lang_item.rs | 60 ++++++++++++++++++- 1 file changed, 59 insertions(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs index 01363f5f2105a..7e8c712b88860 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs @@ -2,7 +2,7 @@ //! //! This attribute to tell the compiler about semi built-in std library //! features, such as Fn family of traits. -use base_db::SourceDatabase; +use base_db::{SourceDatabase, TargetKind}; use hir_expand::name::Name; use intern::{Symbol, sym}; use rustc_hash::FxHashMap; @@ -130,6 +130,8 @@ fn crate_extern_prelude(db: &dyn SourceDatabase, start_crate: Crate) -> Box<[Cra // Some crates declares themselves as extern crate like `extern crate self as core`. // Ignore these to prevent cycles. krate != start_crate + // Exclude proc macro dependencies, they have their own sysroot that could conflict. + && krate.data(db).target_kind != TargetKind::Lib { is_proc_macro: true } }) .collect() } @@ -1053,3 +1055,59 @@ language_item_table! { $ LangItems => Index_index, FunctionId; IndexMut_index_mut, FunctionId; } + +#[cfg(test)] +mod tests { + use base_db::all_crates; + use rustc_hash::FxHashMap; + use test_fixture::WithFixture; + + use crate::{test_db::TestDB, unstable_features::UnstableFeatures}; + + /// Ensures each crate can only have up to one transitive dependency with `#![feature(lang_items)]`. + /// + /// In reality there can be multiple (std, alloc, core) but this is a representative of bugs we had. + fn ensure_single_lang_items_owner(#[rust_analyzer::rust_fixture] ra_fixture: &str) { + let mut lang_items_owner_count = FxHashMap::default(); + + let db = TestDB::with_files(ra_fixture); + // `all_crates()` is in topological order, so we can just loop over it. + for &krate in all_crates(&db).iter() { + let mut lang_items_count = u32::from(UnstableFeatures::query(&db, krate).lang_items); + lang_items_count += super::crate_extern_prelude(&db, krate) + .iter() + .map(|dep| lang_items_owner_count[dep]) + .sum::(); + lang_items_owner_count.insert(krate, lang_items_count); + } + + let invalid_crates = lang_items_owner_count + .iter() + .filter(|(_, count)| **count > 1) + .map(|(krate, _)| match &krate.extra_data(&db).display_name { + Some(name) => name.crate_name().to_string(), + None => format!("{krate:?}"), + }) + .collect::>(); + if !invalid_crates.is_empty() { + panic!("crates [{}] have more than one lang items owner", invalid_crates.join(", ")); + } + } + + #[test] + fn proc_macros_not_included() { + ensure_single_lang_items_owner( + r#" +//- /core1.rs crate:core1 +#![feature(lang_items)] + +//- /proc_macro.rs crate:proc-macro:proc_macro deps:core1 + +//- /core2.rs crate:core2 +#![feature(lang_items)] + +//- /main.rs crate:main deps:core2,proc_macro + "#, + ); + } +} From 4956c698849913ea2d4df785e5bf7996669fb603 Mon Sep 17 00:00:00 2001 From: Shoyu Vanilla Date: Fri, 20 Nov 2026 06:41:35 +0000 Subject: [PATCH 34/48] Introduce a hack for `PartialEq` lang item attr change in core lib --- .../crates/hir-def/src/lang_item.rs | 18 +++++++++++++++++- .../crates/intern/src/symbol/symbols.rs | 1 + .../crates/test-utils/src/minicore.rs | 3 ++- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs index 01363f5f2105a..4c6da5813bcc0 100644 --- a/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs +++ b/src/tools/rust-analyzer/crates/hir-def/src/lang_item.rs @@ -108,6 +108,8 @@ pub fn crate_lang_items(db: &dyn SourceDatabase, krate: Crate) -> Option= 1.102.0. + /// See comments on [`LangItems::Rust1_102PartialEqHack`]. + fn rust_1_102_partial_eq_hack(&mut self) { + if self.Rust1_102PartialEqHack.is_none() { + return; + } + self.Eq = self.PartialEq; + self.PartialEq = self.Rust1_102PartialEqHack; + } } #[salsa::tracked(returns(as_deref))] @@ -851,6 +863,10 @@ language_item_table! { $ LangItems => AsyncGenReady, sym::AsyncGenReady, FunctionId; PartialEq, sym::eq, TraitId; + // FIXME: `PartialEq`'s lang item attribute has been changed into `partial_eq` and `eq` has + // been assigned to `Eq` in 1.102.0. Remove this and move `Eq` here once we bump our + // MSRV >= 1.102.0. + Rust1_102PartialEqHack, sym::partial_eq, TraitId; PartialOrd, sym::partial_ord, TraitId; CVoid, sym::c_void, EnumId; @@ -1046,7 +1062,7 @@ language_item_table! { $ LangItems => PartialOrd_ge, FunctionId; PartialOrd_gt, FunctionId; Drop_drop, FunctionId; - Drop_pin_drop, FunctionId; + Drop_pin_drop, FunctionId; Debug_fmt, FunctionId; Deref_deref, FunctionId; DerefMut_deref_mut, FunctionId; diff --git a/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs b/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs index e33446e4a148b..dfa8aef3012b9 100644 --- a/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs +++ b/src/tools/rust-analyzer/crates/intern/src/symbol/symbols.rs @@ -475,6 +475,7 @@ define_symbols! { panic, Param, parse, + partial_eq, partial_ord, PartialEq, PartialOrd, diff --git a/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs b/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs index 7c2ba4d53d913..237bb64e8e771 100644 --- a/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs +++ b/src/tools/rust-analyzer/crates/test-utils/src/minicore.rs @@ -1317,7 +1317,7 @@ pub mod range { pub mod cmp { use crate::marker::PointeeSized; - #[lang = "eq"] + #[lang = "partial_eq"] pub trait PartialEq: PointeeSized { fn eq(&self, other: &Rhs) -> bool; fn ne(&self, other: &Rhs) -> bool { @@ -1325,6 +1325,7 @@ pub mod cmp { } } + #[lang = "eq"] pub trait Eq: PartialEq + PointeeSized {} // region:builtin_impls From ebac75861904d2ccaf3fbffc6ebcc56ef6f49804 Mon Sep 17 00:00:00 2001 From: vsriram Date: Fri, 20 Nov 2026 16:32:01 +0530 Subject: [PATCH 35/48] Add a reason suggestion for malformed lint attributes --- .../rustc_attr_parsing/src/attributes/lint.rs | 9 +++-- .../rustc_attr_parsing/src/diagnostics.rs | 10 +++++ tests/ui/attributes/malformed-lint-reason.rs | 7 ++++ .../attributes/malformed-lint-reason.stderr | 40 +++++++++++++++++++ 4 files changed, 62 insertions(+), 4 deletions(-) create mode 100644 tests/ui/attributes/malformed-lint-reason.rs create mode 100644 tests/ui/attributes/malformed-lint-reason.stderr diff --git a/compiler/rustc_attr_parsing/src/attributes/lint.rs b/compiler/rustc_attr_parsing/src/attributes/lint.rs index 45cbcf4664404..5b619517b08bb 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint.rs @@ -38,15 +38,16 @@ impl LintParser { let nv = p.args().as_name_value()?; if !p.path().word_is(sym::reason) { // FIXME: We should recommend `reason` here + cx.emit_err(MalformedLintAttributeInput { span: p.span(), - help: MalformedLintAttributeInputHelp::Other { kind: kind.sym() }, + help: MalformedLintAttributeInputHelp::Reason { + reason_span: p.path().span(), + }, kind: kind.sym(), }); - } else { - parsers = &parsers[..(parsers.len() - 1)]; } - + parsers = &parsers[..(parsers.len() - 1)]; let reason = nv.expect_string_literal(cx)?; reason }; diff --git a/compiler/rustc_attr_parsing/src/diagnostics.rs b/compiler/rustc_attr_parsing/src/diagnostics.rs index 12b2fe8cff6e8..a4d37b74beb52 100644 --- a/compiler/rustc_attr_parsing/src/diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/diagnostics.rs @@ -2233,6 +2233,16 @@ pub(crate) struct MalformedLintAttributeInput { pub(crate) enum MalformedLintAttributeInputHelp { #[help("try using `#[{$kind}({$sym})]`")] StrLit { sym: Symbol, kind: Symbol }, + #[suggestion( + "to provide a reason, use `reason = \"\"`", + code = "reason", + applicability = "machine-applicable", + style = "verbose" + )] + Reason { + #[primary_span] + reason_span: Span, + }, #[help("for example, write `#[{$kind}(dead_code)]` for `dead_code`")] Other { kind: Symbol }, } diff --git a/tests/ui/attributes/malformed-lint-reason.rs b/tests/ui/attributes/malformed-lint-reason.rs new file mode 100644 index 0000000000000..05d4e5d9c6f89 --- /dev/null +++ b/tests/ui/attributes/malformed-lint-reason.rs @@ -0,0 +1,7 @@ +// Test that an invalid name-value argument suggests `reason`. +#![allow(dead_code, note = "testing")] +//~^ ERROR malformed `allow` attribute input +//~| ERROR malformed `allow` attribute input +//~| ERROR malformed `allow` attribute input + +fn main() {} diff --git a/tests/ui/attributes/malformed-lint-reason.stderr b/tests/ui/attributes/malformed-lint-reason.stderr new file mode 100644 index 0000000000000..c18f9b0ef4729 --- /dev/null +++ b/tests/ui/attributes/malformed-lint-reason.stderr @@ -0,0 +1,40 @@ +error: malformed `allow` attribute input + --> $DIR/malformed-lint-reason.rs:2:21 + | +LL | #![allow(dead_code, note = "testing")] + | ^^^^^^^^^^^^^^^^ not the name of a lint + | +help: to provide a reason, use `reason = ""` + | +LL - #![allow(dead_code, note = "testing")] +LL + #![allow(dead_code, reason = "testing")] + | + +error: malformed `allow` attribute input + --> $DIR/malformed-lint-reason.rs:2:21 + | +LL | #![allow(dead_code, note = "testing")] + | ^^^^^^^^^^^^^^^^ not the name of a lint + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: to provide a reason, use `reason = ""` + | +LL - #![allow(dead_code, note = "testing")] +LL + #![allow(dead_code, reason = "testing")] + | + +error: malformed `allow` attribute input + --> $DIR/malformed-lint-reason.rs:2:21 + | +LL | #![allow(dead_code, note = "testing")] + | ^^^^^^^^^^^^^^^^ not the name of a lint + | + = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: to provide a reason, use `reason = ""` + | +LL - #![allow(dead_code, note = "testing")] +LL + #![allow(dead_code, reason = "testing")] + | + +error: aborting due to 3 previous errors + From 724b27aec833cee51aa9b5af11f133e35570f5ac Mon Sep 17 00:00:00 2001 From: Wilfred Hughes Date: Fri, 20 Nov 2026 11:39:24 +0000 Subject: [PATCH 36/48] fix: Respect is_workspace_member for all crates in rust-project.json Previously we treated sysroot crates as `is_local: false` unconditionally when loading rust-project.json. This is useful in build systems like buck if you're also building the stdlib from source, so you want to treat sysroot crates just like other crates. AI disclosure: Code written with LLM assistance, review and commit message by me. --- src/tools/rust-analyzer/crates/project-model/src/workspace.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs index db3cecb5b2a31..56c1b8ff1acd8 100644 --- a/src/tools/rust-analyzer/crates/project-model/src/workspace.rs +++ b/src/tools/rust-analyzer/crates/project-model/src/workspace.rs @@ -791,7 +791,7 @@ impl ProjectWorkspace { RustLibSrcWorkspace::Json(project_json) => project_json .crates() .map(|(_, krate)| PackageRoot { - is_local: false, + is_local: krate.is_workspace_member, include: krate.include.clone(), exclude: krate.exclude.clone(), }) From 7745f1871474e9060b5e9b47ee0134372dd119de Mon Sep 17 00:00:00 2001 From: vsriram Date: Fri, 20 Nov 2026 20:59:58 +0530 Subject: [PATCH 37/48] Updated UI tests for malformed lint suggestions --- .../rustc_attr_parsing/src/attributes/lint.rs | 2 - tests/ui/error-codes/E0452.rs | 15 ++++--- tests/ui/error-codes/E0452.stderr | 40 ++++++++----------- tests/ui/lint/lint-malformed.rs | 14 +++---- tests/ui/lint/lint-malformed.stderr | 40 ++++++++----------- tests/ui/lint/reasons-erroneous.stderr | 12 +++++- 6 files changed, 58 insertions(+), 65 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/lint.rs b/compiler/rustc_attr_parsing/src/attributes/lint.rs index 5b619517b08bb..bbdd7f39a4166 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint.rs @@ -37,8 +37,6 @@ impl LintParser { let p = parsers.last()?.meta_item()?; let nv = p.args().as_name_value()?; if !p.path().word_is(sym::reason) { - // FIXME: We should recommend `reason` here - cx.emit_err(MalformedLintAttributeInput { span: p.span(), help: MalformedLintAttributeInputHelp::Reason { diff --git a/tests/ui/error-codes/E0452.rs b/tests/ui/error-codes/E0452.rs index 6a0437df7b14e..ecb0e52d9b65c 100644 --- a/tests/ui/error-codes/E0452.rs +++ b/tests/ui/error-codes/E0452.rs @@ -1,8 +1,7 @@ -#![allow(foo = "")] //~ ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed -fn main() { -} +#![allow(foo = "")] +//~^ ERROR malformed +//~| ERROR malformed +//~| ERROR malformed +//~| WARN unused attribute + +fn main() {} diff --git a/tests/ui/error-codes/E0452.stderr b/tests/ui/error-codes/E0452.stderr index c34d9a2a01b28..8d9fe8438e0bc 100644 --- a/tests/ui/error-codes/E0452.stderr +++ b/tests/ui/error-codes/E0452.stderr @@ -4,16 +4,11 @@ error: malformed `allow` attribute input LL | #![allow(foo = "")] | ^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - -error: malformed `allow` attribute input - --> $DIR/E0452.rs:1:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(foo = "")] - | ^^^^^^^^ not the name of a lint +LL - #![allow(foo = "")] +LL + #![allow(reason = "")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: malformed `allow` attribute input --> $DIR/E0452.rs:1:10 @@ -21,17 +16,12 @@ error: malformed `allow` attribute input LL | #![allow(foo = "")] | ^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/E0452.rs:1:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(foo = "")] - | ^^^^^^^^ not the name of a lint +LL - #![allow(foo = "")] +LL + #![allow(reason = "")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: malformed `allow` attribute input --> $DIR/E0452.rs:1:10 @@ -39,17 +29,21 @@ error: malformed `allow` attribute input LL | #![allow(foo = "")] | ^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: to provide a reason, use `reason = ""` + | +LL - #![allow(foo = "")] +LL + #![allow(reason = "")] + | -error: malformed `allow` attribute input - --> $DIR/E0452.rs:1:10 +warning: unused attribute + --> $DIR/E0452.rs:1:1 | LL | #![allow(foo = "")] - | ^^^^^^^^ not the name of a lint + | ^^^^^^^^^^^^^^^^^^^ help: remove this attribute | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: attribute `allow` without any lints has no effect + = note: requested on the command line with `-W unused-attributes` -error: aborting due to 6 previous errors +error: aborting due to 3 previous errors; 1 warning emitted diff --git a/tests/ui/lint/lint-malformed.rs b/tests/ui/lint/lint-malformed.rs index 5fd92170363f0..4daf3fe9808d7 100644 --- a/tests/ui/lint/lint-malformed.rs +++ b/tests/ui/lint/lint-malformed.rs @@ -1,8 +1,8 @@ #![deny = "foo"] //~ ERROR malformed `deny` attribute input -#![allow(bar = "baz")] //~ ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed - //~| ERROR malformed -fn main() { } +#![allow(bar = "baz")] +//~^ ERROR malformed +//~| ERROR malformed +//~| ERROR malformed +//~| WARN unused attribute + +fn main() {} diff --git a/tests/ui/lint/lint-malformed.stderr b/tests/ui/lint/lint-malformed.stderr index ceb7fe105bcd3..4d490b6bab252 100644 --- a/tests/ui/lint/lint-malformed.stderr +++ b/tests/ui/lint/lint-malformed.stderr @@ -4,16 +4,11 @@ error: malformed `allow` attribute input LL | #![allow(bar = "baz")] | ^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - -error: malformed `allow` attribute input - --> $DIR/lint-malformed.rs:2:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^ not the name of a lint +LL - #![allow(bar = "baz")] +LL + #![allow(reason = "baz")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error: malformed `allow` attribute input --> $DIR/lint-malformed.rs:2:10 @@ -21,17 +16,12 @@ error: malformed `allow` attribute input LL | #![allow(bar = "baz")] | ^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: malformed `allow` attribute input - --> $DIR/lint-malformed.rs:2:10 +help: to provide a reason, use `reason = ""` | -LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^ not the name of a lint +LL - #![allow(bar = "baz")] +LL + #![allow(reason = "baz")] | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` error[E0539]: malformed `deny` attribute input --> $DIR/lint-malformed.rs:1:4 @@ -60,18 +50,22 @@ error: malformed `allow` attribute input LL | #![allow(bar = "baz")] | ^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[allow(dead_code)]` for `dead_code` = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` +help: to provide a reason, use `reason = ""` + | +LL - #![allow(bar = "baz")] +LL + #![allow(reason = "baz")] + | -error: malformed `allow` attribute input - --> $DIR/lint-malformed.rs:2:10 +warning: unused attribute + --> $DIR/lint-malformed.rs:2:1 | LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^ not the name of a lint + | ^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute | - = help: for example, write `#[allow(dead_code)]` for `dead_code` - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` + = note: attribute `allow` without any lints has no effect + = note: requested on the command line with `-W unused-attributes` -error: aborting due to 7 previous errors +error: aborting due to 4 previous errors; 1 warning emitted For more information about this error, try `rustc --explain E0539`. diff --git a/tests/ui/lint/reasons-erroneous.stderr b/tests/ui/lint/reasons-erroneous.stderr index 3c52a0d8e25b4..1288a9fa5d601 100644 --- a/tests/ui/lint/reasons-erroneous.stderr +++ b/tests/ui/lint/reasons-erroneous.stderr @@ -35,7 +35,11 @@ error: malformed `warn` attribute input LL | #![warn(bare_trait_objects, reasons = "leaders to no sure land, guides their bearings lost")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[warn(dead_code)]` for `dead_code` +help: to provide a reason, use `reason = ""` + | +LL - #![warn(bare_trait_objects, reasons = "leaders to no sure land, guides their bearings lost")] +LL + #![warn(bare_trait_objects, reason = "leaders to no sure land, guides their bearings lost")] + | error: malformed `warn` attribute input --> $DIR/reasons-erroneous.rs:13:22 @@ -43,7 +47,11 @@ error: malformed `warn` attribute input LL | #![warn(unsafe_code, blerp = "or in league with robbers have reversed the signposts")] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ not the name of a lint | - = help: for example, write `#[warn(dead_code)]` for `dead_code` +help: to provide a reason, use `reason = ""` + | +LL - #![warn(unsafe_code, blerp = "or in league with robbers have reversed the signposts")] +LL + #![warn(unsafe_code, reason = "or in league with robbers have reversed the signposts")] + | error: malformed `warn` attribute input --> $DIR/reasons-erroneous.rs:16:36 From 2a965fd76c30a0e815dce54b39398b9c3e2e2e2c Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Sat, 21 Nov 2026 00:37:09 +0100 Subject: [PATCH 38/48] rm from `Type::instaniate` --- src/tools/rust-analyzer/crates/hir/src/lib.rs | 8 +++-- .../crates/hir/src/term_search/expr.rs | 12 ++++---- .../crates/hir/src/term_search/tactics.rs | 30 ++++++++++++------- .../src/handlers/wrap_return_type.rs | 9 ++++-- .../src/handlers/type_mismatch.rs | 4 +-- 5 files changed, 41 insertions(+), 22 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index b4223a72ad723..e48c0af19d02e 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -4538,8 +4538,12 @@ impl<'db> Type<'db> { } // FIXME: Find some way with const params, maybe even lifetimes? - pub fn instantiate(&self, args: impl IntoIterator>>) -> Type<'db> { - let interner = DbInterner::conjure(); + pub fn instantiate( + &self, + db: &'db dyn HirDatabase, + args: impl IntoIterator>>, + ) -> Type<'db> { + let interner = DbInterner::new_no_crate(db); let (args, owner) = match self.owner { TypeOwnerId::GenericDefId(def) => generic_args_from_tys(interner, def.into(), args), TypeOwnerId::BuiltinDeriveImplId(def) => { diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs index dc6a6b269744c..6ea1f4e2a2b41 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search/expr.rs @@ -310,18 +310,20 @@ impl<'db> Expr<'db> { Expr::Local(it) => it.ty(db), Expr::ConstParam(it) => it.ty(db), Expr::FamousType { ty, .. } => ty.clone(), - Expr::Function { func, generics, .. } => func.ret_type(db).instantiate(generics), + Expr::Function { func, generics, .. } => func.ret_type(db).instantiate(db, generics), Expr::Method { func, generics, target, .. } => func .ret_type(db) - .instantiate(target.ty(db).type_arguments().chain(generics.iter().cloned())), + .instantiate(db, target.ty(db).type_arguments().chain(generics.iter().cloned())), Expr::Variant { variant, generics, .. } => { - Adt::from(variant.parent_enum(db)).ty(db).instantiate(generics) + Adt::from(variant.parent_enum(db)).ty(db).instantiate(db, generics) } Expr::Struct { strukt, generics, .. } => { - Adt::from(*strukt).ty(db).instantiate(generics) + Adt::from(*strukt).ty(db).instantiate(db, generics) } Expr::Tuple { ty, .. } => ty.clone(), - Expr::Field { expr, field } => field.ty(db).instantiate(expr.ty(db).type_arguments()), + Expr::Field { expr, field } => { + field.ty(db).instantiate(db, expr.ty(db).type_arguments()) + } Expr::Reference(it) => it.ty(db), Expr::Many(ty) => ty.clone(), } diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs index dab80c28c4c3b..1c10c1c110064 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs @@ -169,7 +169,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( let param_exprs: Vec>> = fields .into_iter() .map(|field| { - lookup.find(db, &field.ty(db).instantiate(generics.iter().cloned())) + lookup.find(db, &field.ty(db).instantiate(db, generics.iter().cloned())) }) .collect::>()?; @@ -215,7 +215,10 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( .fields(db) .into_iter() .map(|field| { - lookup.find(db, &field.ty(db).instantiate(generics.iter().cloned())) + lookup.find( + db, + &field.ty(db).instantiate(db, generics.iter().cloned()), + ) }) .collect::>()?; @@ -329,7 +332,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( }) .collect::>()?; - let ret_ty = it.ret_type(db).instantiate(generics.iter().cloned()); + let ret_ty = it.ret_type(db).instantiate(db, generics.iter().cloned()); // Filter out private and unsafe functions if !it.is_visible_from(db, module) || it.is_unsafe_to_call( @@ -348,7 +351,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( .params_without_self(db) .into_iter() .map(|field| { - let ty = &field.ty().instantiate(&generics); + let ty = &field.ty().instantiate(db, &generics); match ty.is_mutable_reference() { true => None, false => lookup.find_autoref(db, ty), @@ -459,15 +462,18 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( return None; } - let ret_ty = it.ret_type(db).instantiate(ty.type_arguments()); + let ret_ty = it.ret_type(db).instantiate(db, ty.type_arguments()); // Ignore functions that do not change the type if ty.instantiate_with_errors().could_unify_with_deeply(db, &ret_ty) { return None; } - let self_ty = - it.self_param(db).expect("No self param").ty(db).instantiate(ty.type_arguments()); + let self_ty = it + .self_param(db) + .expect("No self param") + .ty(db) + .instantiate(db, ty.type_arguments()); // Ignore functions that have different self type if !self_ty.autoderef(db).any(|s_ty| ty == s_ty) { @@ -480,7 +486,9 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( let param_exprs: Vec>> = it .params_without_self(db) .into_iter() - .map(|field| lookup.find_autoref(db, &field.ty().instantiate(ty.type_arguments()))) + .map(|field| { + lookup.find_autoref(db, &field.ty().instantiate(db, ty.type_arguments())) + }) .collect::>()?; let generics: Vec<_> = ty.type_arguments().collect(); @@ -654,13 +662,15 @@ pub(super) fn impl_static_method<'a, 'lt, 'db, DB: HirDatabase>( return None; } - let ret_ty = it.ret_type(db).instantiate(ty.type_arguments()); + let ret_ty = it.ret_type(db).instantiate(db, ty.type_arguments()); // Early exit if some param cannot be filled from lookup let param_exprs: Vec>> = it .params_without_self(db) .into_iter() - .map(|field| lookup.find_autoref(db, &field.ty().instantiate(ty.type_arguments()))) + .map(|field| { + lookup.find_autoref(db, &field.ty().instantiate(db, ty.type_arguments())) + }) .collect::>()?; // Note that we need special case for 0 param constructors because of multi cartesian diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs index 032cc28858c29..867d71deb097a 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/wrap_return_type.rs @@ -92,7 +92,9 @@ pub(crate) fn wrap_return_type(acc: &mut Assists, ctx: &AssistContext<'_, '_>) - }; let semantic_ty = ty_constructor .map(|ty_constructor| { - hir::Adt::from(ty_constructor).ty(ctx.db()).instantiate([ty.clone()]) + hir::Adt::from(ty_constructor) + .ty(ctx.db()) + .instantiate(ctx.db(), [ty.clone()]) }) .unwrap_or_else(|| ty.clone()); (ast_ty, semantic_ty) @@ -255,8 +257,9 @@ fn wrapper_alias<'db>( make.path_segment_generics(make.name_ref(name.as_str()), generic_arg_list), ); - let new_ty = - hir::Adt::from(enum_ty).ty(ctx.db()).instantiate([semantic_ret_type.clone()]); + let new_ty = hir::Adt::from(enum_ty) + .ty(ctx.db()) + .instantiate(ctx.db(), [semantic_ret_type.clone()]); Some((make.ty_path(path), new_ty)) }) diff --git a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs index 4256b7dae51c5..af6c9de8fcabc 100644 --- a/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs +++ b/src/tools/rust-analyzer/crates/ide-diagnostics/src/handlers/type_mismatch.rs @@ -198,7 +198,7 @@ fn add_missing_ok_or_some( let variant_name = if Some(expected_enum) == core_result { "Ok" } else { "Some" }; - let wrapped_actual_ty = expected_adt.ty(ctx.db()).instantiate([d.actual.clone()]); + let wrapped_actual_ty = expected_adt.ty(ctx.db()).instantiate(ctx.db(), [d.actual.clone()]); if !d.expected.could_unify_with(ctx.db(), &wrapped_actual_ty) { return None; @@ -296,7 +296,7 @@ fn remove_unnecessary_wrapper( return None; } - let inner_type = variant.fields(db).first()?.ty(db).instantiate(d.actual.type_arguments()); + let inner_type = variant.fields(db).first()?.ty(db).instantiate(db, d.actual.type_arguments()); if !d.expected.could_unify_with(db, &inner_type) { return None; } From af81b91c193ef23779bc18755e5331847df8078b Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Sat, 21 Nov 2026 00:38:07 +0100 Subject: [PATCH 39/48] rm from `Type::instaniate_with_errors` Required storing `db` inside `LookupTable`, which should be fine. --- src/tools/rust-analyzer/crates/hir/src/lib.rs | 9 ++--- .../crates/hir/src/term_search.rs | 29 +++++++++------- .../crates/hir/src/term_search/tactics.rs | 33 +++++++++---------- .../ide-assists/src/handlers/auto_import.rs | 2 +- .../src/handlers/replace_method_eager_lazy.rs | 2 +- .../ide-completion/src/completions/expr.rs | 2 +- .../crates/ide-completion/src/context.rs | 2 +- .../ide-completion/src/context/analysis.rs | 2 +- .../ide-completion/src/render/function.rs | 7 ++-- 9 files changed, 48 insertions(+), 40 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index e48c0af19d02e..d1af9b908400c 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -4524,8 +4524,8 @@ impl<'db> Type<'db> { } /// Replace any generic parameters with error types. - pub fn instantiate_with_errors(&self) -> Self { - let interner = DbInterner::conjure(); + pub fn instantiate_with_errors(&self, db: &'db dyn HirDatabase) -> Self { + let interner = DbInterner::new_no_crate(db); let krate = self.krate(interner.db()); let args = match self.owner { TypeOwnerId::GenericDefId(def) => GenericArgs::error_for_item(interner, def.into()), @@ -4600,7 +4600,7 @@ impl<'db> Type<'db> { db: &'db dyn HirDatabase, rebase_into: &Type<'db>, ) -> Type<'db> { - self.try_rebase_into(db, rebase_into).unwrap_or_else(|| self.instantiate_with_errors()) + self.try_rebase_into(db, rebase_into).unwrap_or_else(|| self.instantiate_with_errors(db)) } pub fn try_rebase_into_owner( @@ -4621,7 +4621,8 @@ impl<'db> Type<'db> { db: &'db dyn HirDatabase, new_owner: GenericDef, ) -> Self { - self.try_rebase_into_owner(db, new_owner).unwrap_or_else(|| self.instantiate_with_errors()) + self.try_rebase_into_owner(db, new_owner) + .unwrap_or_else(|| self.instantiate_with_errors(db)) } pub fn unknown() -> Self { diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search.rs b/src/tools/rust-analyzer/crates/hir/src/term_search.rs index 37cad14ea2d39..072f495f81912 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search.rs @@ -87,8 +87,9 @@ impl<'db> AlternativeExprs<'db> { /// iteration as well as keeping track of which `ScopeDef` items have been used. /// Both of them are to speed up the term search by leaving out types / ScopeDefs that likely do /// not produce any new results. -#[derive(Default, Debug)] +#[derive(Debug)] struct LookupTable<'db> { + db: &'db dyn HirDatabase, /// All the `Expr`s in "value" produce the type of "key" data: FxHashMap, AlternativeExprs<'db>>, /// New types reached since last query by the `NewTypesKey` @@ -101,20 +102,25 @@ struct LookupTable<'db> { impl<'db> LookupTable<'db> { /// Initialize lookup table - fn new(many_threshold: usize, goal: Type<'db>) -> Self { - let mut res = Self { many_threshold, ..Default::default() }; - res.new_types.insert(NewTypesKey::ImplMethod, Vec::new()); - res.new_types.insert(NewTypesKey::StructProjection, Vec::new()); - res.types_wishlist.insert(goal); - res + fn new(db: &'db dyn HirDatabase, many_threshold: usize, goal: Type<'db>) -> Self { + Self { + db, + many_threshold, + data: Default::default(), + types_wishlist: FxHashSet::from_iter([goal]), + new_types: FxHashMap::from_iter([ + (NewTypesKey::ImplMethod, Vec::new()), + (NewTypesKey::StructProjection, Vec::new()), + ]), + } } /// Find all `Expr`s that unify with the `ty` - fn find(&mut self, db: &'db dyn HirDatabase, ty: &Type<'db>) -> Option>> { + fn find(&mut self, ty: &Type<'db>) -> Option>> { let res = self .data .get_key_value(ty) - .or_else(|| self.data.iter().find(|(t, _)| t.could_unify_with_deeply(db, ty))) + .or_else(|| self.data.iter().find(|(t, _)| t.could_unify_with_deeply(self.db, ty))) .map(|(t, tts)| tts.exprs(t)); if res.is_none() { @@ -175,7 +181,7 @@ impl<'db> LookupTable<'db> { /// transitive. For example `Vec` and `FxHashSet` both unify with `Iterator`, /// but they clearly do not unify themselves. fn insert(&mut self, ty: Type<'db>, exprs: impl Iterator>) { - let ty = ty.instantiate_with_errors(); + let ty = ty.instantiate_with_errors(self.db); match self.data.get_mut(&ty) { Some(it) => { it.extend_with_threshold(self.many_threshold, exprs); @@ -271,7 +277,8 @@ pub fn term_search<'db, DB: HirDatabase>(ctx: &TermSearchCtx<'_, 'db, DB>) -> Ve defs.insert(def); }); - let mut lookup = LookupTable::new(ctx.config.many_alternatives_threshold, ctx.goal.clone()); + let mut lookup = + LookupTable::new(ctx.sema.db, ctx.config.many_alternatives_threshold, ctx.goal.clone()); let fuel = std::cell::Cell::new(ctx.config.fuel); let should_continue = &|| { diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs index 1c10c1c110064..b3009646dc29d 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs @@ -57,7 +57,7 @@ pub(super) fn trivial<'a, 'lt, 'db, DB: HirDatabase>( lookup.insert(ty.clone(), std::iter::once(expr.clone())); - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(expr) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(expr) }) } @@ -107,7 +107,7 @@ pub(super) fn assoc_const<'a, 'lt, 'db, DB: HirDatabase>( lookup.insert(ty.clone(), std::iter::once(expr.clone())); - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(expr) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(expr) }) } @@ -169,7 +169,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( let param_exprs: Vec>> = fields .into_iter() .map(|field| { - lookup.find(db, &field.ty(db).instantiate(db, generics.iter().cloned())) + lookup.find(&field.ty(db).instantiate(db, generics.iter().cloned())) }) .collect::>()?; @@ -215,10 +215,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( .fields(db) .into_iter() .map(|field| { - lookup.find( - db, - &field.ty(db).instantiate(db, generics.iter().cloned()), - ) + lookup.find(&field.ty(db).instantiate(db, generics.iter().cloned())) }) .collect::>()?; @@ -252,7 +249,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( Adt::Union(_) => None, }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -386,7 +383,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( }) .flatten() .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -465,7 +462,7 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( let ret_ty = it.ret_type(db).instantiate(db, ty.type_arguments()); // Ignore functions that do not change the type - if ty.instantiate_with_errors().could_unify_with_deeply(db, &ret_ty) { + if ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ret_ty) { return None; } @@ -480,7 +477,7 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( return None; } - let target_type_exprs = lookup.find(db, &ty).expect("Type not in lookup"); + let target_type_exprs = lookup.find(&ty).expect("Type not in lookup"); // Early exit if some param cannot be filled from lookup let param_exprs: Vec>> = it @@ -510,7 +507,7 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( Some((ret_ty, fn_exprs)) }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -538,7 +535,7 @@ pub(super) fn struct_projection<'a, 'lt, 'db, DB: HirDatabase>( lookup .new_types(NewTypesKey::StructProjection) .into_iter() - .map(|ty| (ty.clone(), lookup.find(db, &ty).expect("Expr not in lookup"))) + .map(|ty| (ty.clone(), lookup.find(&ty).expect("Expr not in lookup"))) .filter(|_| should_continue()) .flat_map(move |(ty, targets)| { ty.fields(db).into_iter().filter_map(move |(field, filed_ty)| { @@ -553,7 +550,7 @@ pub(super) fn struct_projection<'a, 'lt, 'db, DB: HirDatabase>( }) }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -588,7 +585,7 @@ pub(super) fn famous_types<'a, 'lt, 'db, DB: HirDatabase>( .inspect(|exprs| { lookup.insert(exprs.ty(db), std::iter::once(exprs.clone())); }) - .filter(|expr| expr.ty(db).instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal)) + .filter(|expr| expr.ty(db).instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal)) } /// # Impl static method (without self type) tactic @@ -691,7 +688,7 @@ pub(super) fn impl_static_method<'a, 'lt, 'db, DB: HirDatabase>( Some((ret_ty, fn_exprs)) }) .filter_map(|(ty, exprs)| { - ty.instantiate_with_errors().could_unify_with_deeply(db, &ctx.goal).then_some(exprs) + ty.instantiate_with_errors(db).could_unify_with_deeply(db, &ctx.goal).then_some(exprs) }) .flatten() } @@ -730,7 +727,7 @@ pub(super) fn make_tuple<'a, 'lt, 'db, DB: HirDatabase>( // Early exit if some param cannot be filled from lookup let param_exprs: Vec>> = - ty.type_arguments().map(|field| lookup.find(db, &field)).collect::>()?; + ty.type_arguments().map(|field| lookup.find(&field)).collect::>()?; let exprs: Vec> = param_exprs .into_iter() @@ -751,7 +748,7 @@ pub(super) fn make_tuple<'a, 'lt, 'db, DB: HirDatabase>( .flatten() .filter_map(|expr| { expr.ty(db) - .instantiate_with_errors() + .instantiate_with_errors(db) .could_unify_with_deeply(db, &ctx.goal) .then_some(expr) }) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs index dd082476d2d62..d713a37a40fff 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs @@ -293,7 +293,7 @@ pub(crate) fn relevance_score( if let Some(ty) = ty { if ty == *expected { score = 100000; - } else if ty.could_unify_with(ctx.db(), &expected.instantiate_with_errors()) { + } else if ty.could_unify_with(ctx.db(), &expected.instantiate_with_errors(ctx.db())) { score = 10000; } } diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs index a414db0a6c8d0..1ccc8917f0c65 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/replace_method_eager_lazy.rs @@ -72,7 +72,7 @@ pub(crate) fn replace_with_lazy_method( .is_some_and(|result| { result .ty(ctx.db()) - .instantiate_with_errors() + .instantiate_with_errors(ctx.db()) .could_unify_with(ctx.db(), &receiver_ty) }), _ => false, diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs b/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs index 6937d241b7b77..a6fd2e8042fd0 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/completions/expr.rs @@ -185,7 +185,7 @@ pub(crate) fn complete_expr_path<'db>( }; // Note: this is not *required* here, we do it to also find methods that require // the type to be instantiated with specific types. - let ty = ty.instantiate_with_errors(); + let ty = ty.instantiate_with_errors(ctx.db); if let Some(hir::Adt::Enum(e)) = ty.as_adt() { cov_mark::hit!(completes_variant_through_alias); diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/context.rs b/src/tools/rust-analyzer/crates/ide-completion/src/context.rs index 80e07ff9323df..e397e95503b13 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/context.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/context.rs @@ -791,7 +791,7 @@ impl<'db> CompletionContext<'_, 'db> { self.scope .generic_def() .and_then(|def| ty.try_rebase_into_owner(self.db, def)) - .unwrap_or_else(|| ty.instantiate_with_errors()) + .unwrap_or_else(|| ty.instantiate_with_errors(self.db)) } } diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs index 9330e70b1cb02..4aed1e514f57f 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/context/analysis.rs @@ -658,7 +658,7 @@ fn expected_type_and_name<'db>( let def = *generic_def .get_or_insert_with(|| sema.scope(&node).and_then(|scope| scope.generic_def())); def.and_then(|def| ty.try_rebase_into_owner(sema.db, def)) - .unwrap_or_else(|| ty.instantiate_with_errors()) + .unwrap_or_else(|| ty.instantiate_with_errors(sema.db)) } }; let (ty, name) = loop { diff --git a/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs b/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs index 0e9b5d0086f84..a4fb3e97d1b86 100644 --- a/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs +++ b/src/tools/rust-analyzer/crates/ide-completion/src/render/function.rs @@ -246,8 +246,11 @@ pub(super) fn add_call_parens<'b>( Some(n) => { let smol_str = n.display_no_db(ctx.edition).to_smolstr(); let text = smol_str.as_str().trim_start_matches('_'); - let ref_ = - ref_of_param(ctx, text, ¶m.ty().instantiate_with_errors()); + let ref_ = ref_of_param( + ctx, + text, + ¶m.ty().instantiate_with_errors(ctx.db), + ); f(&format_args!("${{{}:{ref_}{text}}}", index + offset)) } None => { From 13c67ef010c03ab218aa6bf23c30d55c7861971e Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Sat, 21 Nov 2026 00:52:43 +0100 Subject: [PATCH 40/48] rm from `Type::unknown` --- src/tools/rust-analyzer/crates/hir/src/lib.rs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index d1af9b908400c..3d7a70099aaf3 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -1530,7 +1530,7 @@ impl Function { // because it has not `CallableDefId`. // FIXME: This does not account for replacing `Self`. Do we really need that? let Some(trait_method) = method.trait_method(db, impl_) else { - return Type::unknown(); + return Type::unknown(db); }; Function::from(trait_method).ty(db) } @@ -1551,7 +1551,7 @@ impl Function { // because it has not `CallableDefId`. // FIXME: This does not account for replacing `Self`. Do we really need that? let Some(trait_method) = method.trait_method(db, impl_) else { - return Type::unknown(); + return Type::unknown(db); }; Function::from(trait_method).fn_ptr_type(db) } @@ -4506,7 +4506,7 @@ impl<'db> Type<'db> { fn from_value_def(db: &'db dyn HirDatabase, def: impl Into) -> Self { let def = def.into(); let Some(ty) = db.value_ty(def) else { - return Type::unknown(); + return Type::unknown(db); }; let def = match def { ValueTyDefId::ConstId(it) => GenericDefId::ConstId(it), @@ -4625,12 +4625,9 @@ impl<'db> Type<'db> { .unwrap_or_else(|| self.instantiate_with_errors(db)) } - pub fn unknown() -> Self { - let interner = DbInterner::conjure(); - Type::no_params( - Self::builtin_type_crate(interner.db()), - Ty::new_error(interner, ErrorGuaranteed), - ) + pub fn unknown(db: &'db dyn HirDatabase) -> Self { + let interner = DbInterner::new_no_crate(db); + Type::no_params(Self::builtin_type_crate(db), Ty::new_error(interner, ErrorGuaranteed)) } pub fn new_slice(db: &'db dyn HirDatabase, ty: Self) -> Self { From e2086b9b2a2aa04eac884caed0bf6e9a6b9d1408 Mon Sep 17 00:00:00 2001 From: Ada Alakbarova Date: Sat, 21 Nov 2026 00:53:39 +0100 Subject: [PATCH 41/48] rm from `Type::new_unit` --- src/tools/rust-analyzer/crates/hir/src/lib.rs | 6 +++--- .../rust-analyzer/crates/hir/src/term_search/tactics.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir/src/lib.rs b/src/tools/rust-analyzer/crates/hir/src/lib.rs index 3d7a70099aaf3..68d625b588042 100644 --- a/src/tools/rust-analyzer/crates/hir/src/lib.rs +++ b/src/tools/rust-analyzer/crates/hir/src/lib.rs @@ -4659,9 +4659,9 @@ impl<'db> Type<'db> { Type { owner, ty } } - pub fn new_unit() -> Self { - let interner = DbInterner::conjure(); - Type::no_params(Self::builtin_type_crate(interner.db()), Ty::new_unit(interner)) + pub fn new_unit(db: &'db dyn HirDatabase) -> Self { + let interner = DbInterner::new_no_crate(db); + Type::no_params(Self::builtin_type_crate(db), Ty::new_unit(interner)) } pub fn is_unit(&self) -> bool { diff --git a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs index b3009646dc29d..6059220bb0e00 100644 --- a/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs +++ b/src/tools/rust-analyzer/crates/hir/src/term_search/tactics.rs @@ -575,7 +575,7 @@ pub(super) fn famous_types<'a, 'lt, 'db, DB: HirDatabase>( ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { let db = ctx.sema.db; let bool_ty = BuiltinType::bool().ty(db); - let unit_ty = Type::new_unit(); + let unit_ty = Type::new_unit(db); [ Expr::FamousType { ty: bool_ty.clone(), value: "true" }, Expr::FamousType { ty: bool_ty, value: "false" }, From e0f9933b61cd48967fb7317ecdb5f81711eacd2f Mon Sep 17 00:00:00 2001 From: shulaoda <165626830+shulaoda@users.noreply.github.com> Date: Sun, 22 Nov 2026 06:17:02 +0800 Subject: [PATCH 42/48] minor: add test for auto import carrying a cfg attr from a macro --- .../ide-assists/src/handlers/auto_import.rs | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs index d713a37a40fff..95052faf93d31 100644 --- a/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs +++ b/src/tools/rust-analyzer/crates/ide-assists/src/handlers/auto_import.rs @@ -2093,4 +2093,44 @@ fn main() { "#, ); } + + #[test] + fn carries_cfg_attr_from_macro() { + check_assist( + auto_import, + r#" +//- /lib.rs crate:std +pub mod time { + pub struct Instant; +} + +//- /main.rs crate:main deps:std +// comment comment comment comment + +macro_rules! m { + ($t: path) => { + #[cfg(anything)] + fn f() -> $t {} + }; +} + +m! {Instant$0} +"#, + r#" +// comment comment comment comment + +#[cfg(anything)] +use std::time::Instant; + +macro_rules! m { + ($t: path) => { + #[cfg(anything)] + fn f() -> $t {} + }; +} + +m! {Instant} +"#, + ); + } } From eddfd50f5e26ab59e6561d2928d2b6ea38269e3a Mon Sep 17 00:00:00 2001 From: "workflows-rust-analyzer[bot]" <223433972+workflows-rust-analyzer[bot]@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:55:33 +0000 Subject: [PATCH 43/48] internal: update generated lints and target features --- .../hir-ty/src/target_feature/generated.rs | 2 +- .../crates/ide-db/src/generated/lints.rs | 64 ++++++++++++++----- 2 files changed, 49 insertions(+), 17 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs b/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs index 621eed47be4ec..38e6eb54ba826 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/target_feature/generated.rs @@ -116,7 +116,7 @@ static AARCH64_FEATURES: &[(&str, Stability, ImpliedFeatures)] = &[ &[], ), // FEAT_FP8 - ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["faminmax", "lut", "bf16"]), + ("fp8", Unstable(sym::aarch64_unstable_target_feature), &["neon"]), // FEAT_FP8DOT2 ("fp8dot2", Unstable(sym::aarch64_unstable_target_feature), &["fp8dot4"]), // FEAT_FP8DOT4 diff --git a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs index 119af3ab8615b..3403e41247029 100644 --- a/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs +++ b/src/tools/rust-analyzer/crates/ide-db/src/generated/lints.rs @@ -5403,6 +5403,22 @@ The tracking issue for this feature is: [#87555] [#87555]: https://github.com/rust-lang/rust/issues/87555 +------------------------ +"##, + default_severity: Severity::Allow, + warn_since: None, + deny_since: None, + }, + Lint { + label: "const_abort", + description: r##"# `const_abort` + + + +The tracking issue for this feature is: [#166193] + +[#166193]: https://github.com/rust-lang/rust/issues/166193 + ------------------------ "##, default_severity: Severity::Allow, @@ -8525,6 +8541,22 @@ The tracking issue for this feature is: [#164793] [#164793]: https://github.com/rust-lang/rust/issues/164793 +------------------------ +"##, + default_severity: Severity::Allow, + warn_since: None, + deny_since: None, + }, + Lint { + label: "extern_item_default_impls", + description: r##"# `extern_item_default_impls` + +Externally implementable items with default impls + +The tracking issue for this feature is: [#125418] + +[#125418]: https://github.com/rust-lang/rust/issues/125418 + ------------------------ "##, default_severity: Severity::Allow, @@ -10550,22 +10582,6 @@ The tracking issue for this feature is: [#157081] [#157081]: https://github.com/rust-lang/rust/issues/157081 ------------------------- -"##, - default_severity: Severity::Allow, - warn_since: None, - deny_since: None, - }, - Lint { - label: "int_from_ascii", - description: r##"# `int_from_ascii` - - - -The tracking issue for this feature is: [#134821] - -[#134821]: https://github.com/rust-lang/rust/issues/134821 - ------------------------ "##, default_severity: Severity::Allow, @@ -18119,6 +18135,22 @@ The tracking issue for this feature is: [#148227] [#148227]: https://github.com/rust-lang/rust/issues/148227 +------------------------ +"##, + default_severity: Severity::Allow, + warn_since: None, + deny_since: None, + }, + Lint { + label: "vec_repeat", + description: r##"# `vec_repeat` + + + +The tracking issue for this feature is: [#164215] + +[#164215]: https://github.com/rust-lang/rust/issues/164215 + ------------------------ "##, default_severity: Severity::Allow, From 09d7afc36ae64d5747f6d5597115d1bf8a9341e4 Mon Sep 17 00:00:00 2001 From: Nicolas Guichard Date: Thu, 4 Jun 2026 16:46:19 +0200 Subject: [PATCH 44/48] Reduce code duplication in substs_from_args_and_bindings Instead of copying the `_ => { ... }` arm and referring to it via a comment, we can just use an if guard on the match here. --- .../crates/hir-ty/src/lower/path.rs | 27 +++++++------------ 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs b/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs index 23cf4fbe38599..cf056fdebc03e 100644 --- a/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs +++ b/src/tools/rust-analyzer/crates/hir-ty/src/lower/path.rs @@ -1288,23 +1288,16 @@ pub(crate) fn substs_from_args_and_bindings<'db>( params.next(); force_infer_lt = Some((arg_idx as u32, param_id)); } - (HirGenericArg::Type(type_ref), GenericParamDataRef::ConstParamData(_)) => { - if let Some(konst) = type_looks_like_const(store, *type_ref) { - let GenericParamId::ConstParamId(param_id) = param_id else { - panic!("unmatching param kinds"); - }; - let const_ty = const_param_ty(db, param_id); - substs - .push(ctx.provided_type_like_const(*type_ref, const_ty, konst).into()); - args.next(); - params.next(); - } else { - // See the `_ => { ... }` branch. - if !had_count_error { - ctx.report_arg_mismatch(param_id, arg_idx as u32, has_self_arg); - } - while args.next().is_some() {} - } + (HirGenericArg::Type(type_ref), GenericParamDataRef::ConstParamData(_)) + if let Some(konst) = type_looks_like_const(store, *type_ref) => + { + let GenericParamId::ConstParamId(param_id) = param_id else { + panic!("unmatching param kinds"); + }; + let const_ty = const_param_ty(db, param_id); + substs.push(ctx.provided_type_like_const(*type_ref, const_ty, konst).into()); + args.next(); + params.next(); } _ => { // We expected one kind of parameter, but the user provided From dafb375f86a488bca2176078574ac1e3b1139295 Mon Sep 17 00:00:00 2001 From: Mark Rousskov Date: Sun, 22 Nov 2026 14:10:35 -0500 Subject: [PATCH 45/48] Drop references to codebuild We no longer use AWS CodeBuild for our jobs, so delete or rephrase code that referred to it. --- src/ci/citool/src/jobs.rs | 11 +--- src/ci/citool/src/jobs/tests.rs | 67 ------------------------- src/ci/scripts/free-disk-space-linux.sh | 2 +- 3 files changed, 3 insertions(+), 77 deletions(-) diff --git a/src/ci/citool/src/jobs.rs b/src/ci/citool/src/jobs.rs index b94f12a37cc77..6ca6cd10815ba 100644 --- a/src/ci/citool/src/jobs.rs +++ b/src/ci/citool/src/jobs.rs @@ -29,8 +29,6 @@ pub struct Job { pub free_disk: Option, /// Documentation link to a resource that could help people debug this CI job. pub doc_url: Option, - /// Whether the job is executed on AWS CodeBuild. - pub codebuild: Option, /// Which Python version (if any) is required. On Windows, this is typically required to run /// LLDB. #[serde(default)] @@ -170,7 +168,6 @@ fn validate_job_database(db: &JobDatabase) -> anyhow::Result<()> { only_on_channel, free_disk, doc_url, - codebuild, required_python_version, // Carve-out configs allowed to be different. @@ -183,7 +180,6 @@ fn validate_job_database(db: &JobDatabase) -> anyhow::Result<()> { && *only_on_channel == auto_job.only_on_channel && *free_disk == auto_job.free_disk && *doc_url == auto_job.doc_url - && *codebuild == auto_job.codebuild && *required_python_version == auto_job.required_python_version { Ok(()) @@ -249,14 +245,12 @@ struct GithubActionsJob { #[serde(skip_serializing_if = "Option::is_none")] doc_url: Option, #[serde(skip_serializing_if = "Option::is_none")] - codebuild: Option, - #[serde(skip_serializing_if = "Option::is_none")] required_python_version: Option, } /// Replace GitHub context variables with environment variables in job configs. -/// Used for codebuild jobs like -/// `codebuild-ubuntu-22-8c-$github.run_id-$github.run_attempt` +/// +/// This is used for self-hosted runner jobs to loosely tie an instance to a particular GHA job. fn substitute_github_vars(jobs: Vec) -> anyhow::Result> { let run_id = load_env_var("GITHUB_RUN_ID")?; let run_attempt = load_env_var("GITHUB_RUN_ATTEMPT")?; @@ -382,7 +376,6 @@ fn calculate_jobs( continue_on_error: job.continue_on_error, free_disk: job.free_disk, doc_url: job.doc_url, - codebuild: job.codebuild, required_python_version: job.required_python_version, } }) diff --git a/src/ci/citool/src/jobs/tests.rs b/src/ci/citool/src/jobs/tests.rs index 65990d35d61b1..0179157d85c58 100644 --- a/src/ci/citool/src/jobs/tests.rs +++ b/src/ci/citool/src/jobs/tests.rs @@ -81,73 +81,6 @@ fn check_pattern(db: &JobDatabase, pattern: &str, expected: &[&str]) { assert_eq!(jobs, expected); } -/// Validate that CodeBuild jobs use Docker images from ghcr.io registry. -/// This is needed because otherwise from CodeBuild we get rate limited by Docker Hub. -fn validate_codebuild_image(job: &Job) -> anyhow::Result<()> { - let is_job_on_codebuild = job.codebuild.unwrap_or(false); - if !is_job_on_codebuild { - // Jobs in GitHub Actions don't get rate limited by Docker Hub. - return Ok(()); - } - - let image_name = job.image(); - // we hardcode host-x86_64 here, because in codebuild we only run jobs for this architecture. - let dockerfile_path = - Path::new(DOCKER_DIRECTORY).join("host-x86_64").join(&image_name).join("Dockerfile"); - - if !dockerfile_path.exists() { - return Err(anyhow::anyhow!( - "Dockerfile not found for CodeBuild job '{}' at path: {}", - job.name, - dockerfile_path.display() - )); - } - - let dockerfile_content = utils::read_to_string(&dockerfile_path)?; - - // Check if all FROM statement uses ghcr.io registry - let has_ghcr_from = dockerfile_content - .lines() - .filter(|line| line.trim_start().to_lowercase().starts_with("from ")) - .all(|line| line.contains("ghcr.io")); - - if !has_ghcr_from { - return Err(anyhow::anyhow!( - "CodeBuild job '{}' must use ghcr.io registry in its Dockerfile FROM statement. \ - Dockerfile path: {dockerfile_path:?}", - job.name, - )); - } - - Ok(()) -} - -#[test] -fn validate_jobs() { - let db = { - let default_jobs_file = Path::new(JOBS_YML_PATH); - let db_str = utils::read_to_string(default_jobs_file).unwrap(); - load_job_db(&db_str).expect("Failed to load job database") - }; - - let all_jobs = db - .pr_jobs - .iter() - .chain(db.try_jobs.iter()) - .chain(db.auto_jobs.iter()) - .chain(db.optional_jobs.iter()) - .collect::>(); - - let errors: Vec = - all_jobs.into_iter().filter_map(|job| validate_codebuild_image(job).err()).collect(); - - if !errors.is_empty() { - let error_messages = - errors.into_iter().map(|e| format!("- {e}")).collect::>().join("\n"); - panic!("Job validation failed:\n{error_messages}"); - } -} - #[test] fn pr_job_implies_auto_job() { let db = load_job_db( diff --git a/src/ci/scripts/free-disk-space-linux.sh b/src/ci/scripts/free-disk-space-linux.sh index 1498bc0a24f2c..36c9505327157 100755 --- a/src/ci/scripts/free-disk-space-linux.sh +++ b/src/ci/scripts/free-disk-space-linux.sh @@ -21,7 +21,7 @@ isX86() { } # Check if we're on a GitHub hosted runner. -# In aws codebuild, the variable RUNNER_ENVIRONMENT is "self-hosted". +# In self hosted runners, the variable RUNNER_ENVIRONMENT is "self-hosted". isGitHubRunner() { # `:-` means "use the value of RUNNER_ENVIRONMENT if it exists, otherwise use an empty string". if [[ "${RUNNER_ENVIRONMENT:-}" == "github-hosted" ]]; then From fdccf0a69735ae673276f7b737793fcc05ff0bb1 Mon Sep 17 00:00:00 2001 From: vsriram Date: Mon, 23 Nov 2026 14:01:23 +0530 Subject: [PATCH 46/48] Suppressed a follow up unused lint warning --- compiler/rustc_attr_parsing/src/attributes/lint.rs | 4 +++- tests/ui/error-codes/E0452.rs | 1 - tests/ui/error-codes/E0452.stderr | 11 +---------- tests/ui/lint/lint-malformed.rs | 1 - tests/ui/lint/lint-malformed.stderr | 11 +---------- 5 files changed, 5 insertions(+), 23 deletions(-) diff --git a/compiler/rustc_attr_parsing/src/attributes/lint.rs b/compiler/rustc_attr_parsing/src/attributes/lint.rs index bbdd7f39a4166..bb53dd6995feb 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint.rs @@ -28,6 +28,7 @@ impl LintParser { fn parse(&mut self, kind: LintCheckKind, cx: &mut AcceptContext<'_, '_>, args: &ArgParser) { let attr_span = cx.attr_span; let attr_id = cx.attr_id.expect("no `AttrId` for lint attribute"); + let mut has_invalid_reason_key = false; if let Some(list) = cx.expect_list(args, cx.attr_span) { let mut parsers = list.sub_parsers(); @@ -37,6 +38,7 @@ impl LintParser { let p = parsers.last()?.meta_item()?; let nv = p.args().as_name_value()?; if !p.path().word_is(sym::reason) { + has_invalid_reason_key = true; cx.emit_err(MalformedLintAttributeInput { span: p.span(), help: MalformedLintAttributeInputHelp::Reason { @@ -109,7 +111,7 @@ impl LintParser { // FIXME(164898) Lint attributes are unique because they're parsed twice with `ShouldEmit::ErrorsAndLints` // To avoid emitting the lint twice, we check `cx.parse_filter`, which will be `Some` during AST linting - if parsers.is_empty() && cx.parse_filter.is_none() { + if parsers.is_empty() && cx.parse_filter.is_none() && !has_invalid_reason_key { cx.emit_lint( UNUSED_ATTRIBUTES, diagnostics::Unused { diff --git a/tests/ui/error-codes/E0452.rs b/tests/ui/error-codes/E0452.rs index ecb0e52d9b65c..947f8f1237bf5 100644 --- a/tests/ui/error-codes/E0452.rs +++ b/tests/ui/error-codes/E0452.rs @@ -2,6 +2,5 @@ //~^ ERROR malformed //~| ERROR malformed //~| ERROR malformed -//~| WARN unused attribute fn main() {} diff --git a/tests/ui/error-codes/E0452.stderr b/tests/ui/error-codes/E0452.stderr index 8d9fe8438e0bc..0244de4a7bc81 100644 --- a/tests/ui/error-codes/E0452.stderr +++ b/tests/ui/error-codes/E0452.stderr @@ -36,14 +36,5 @@ LL - #![allow(foo = "")] LL + #![allow(reason = "")] | -warning: unused attribute - --> $DIR/E0452.rs:1:1 - | -LL | #![allow(foo = "")] - | ^^^^^^^^^^^^^^^^^^^ help: remove this attribute - | - = note: attribute `allow` without any lints has no effect - = note: requested on the command line with `-W unused-attributes` - -error: aborting due to 3 previous errors; 1 warning emitted +error: aborting due to 3 previous errors diff --git a/tests/ui/lint/lint-malformed.rs b/tests/ui/lint/lint-malformed.rs index 4daf3fe9808d7..e5a64cbf764f9 100644 --- a/tests/ui/lint/lint-malformed.rs +++ b/tests/ui/lint/lint-malformed.rs @@ -3,6 +3,5 @@ //~^ ERROR malformed //~| ERROR malformed //~| ERROR malformed -//~| WARN unused attribute fn main() {} diff --git a/tests/ui/lint/lint-malformed.stderr b/tests/ui/lint/lint-malformed.stderr index 4d490b6bab252..8afd9ac54e438 100644 --- a/tests/ui/lint/lint-malformed.stderr +++ b/tests/ui/lint/lint-malformed.stderr @@ -57,15 +57,6 @@ LL - #![allow(bar = "baz")] LL + #![allow(reason = "baz")] | -warning: unused attribute - --> $DIR/lint-malformed.rs:2:1 - | -LL | #![allow(bar = "baz")] - | ^^^^^^^^^^^^^^^^^^^^^^ help: remove this attribute - | - = note: attribute `allow` without any lints has no effect - = note: requested on the command line with `-W unused-attributes` - -error: aborting due to 4 previous errors; 1 warning emitted +error: aborting due to 4 previous errors For more information about this error, try `rustc --explain E0539`. From bf55ac776b1fa288cd4b8454012e2c57489cc57c Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Mon, 23 Nov 2026 09:14:27 +0100 Subject: [PATCH 47/48] Undo accidentally introduced duplication checking for attributes on macro calls --- compiler/rustc_expand/src/expand.rs | 41 ++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index e60b1829e56de..fc8cf733136b4 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use std::rc::Rc; use std::sync::Arc; -use std::{iter, mem}; +use std::{iter, mem, slice}; use rustc_ast::mut_visit::*; use rustc_ast::tokenstream::TokenStream; @@ -2228,17 +2228,34 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // Run attributes through the attribute parser // since they will not be detected after macro expansion. fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) { - AttributeParser::parse_limited_all( - self.cx.sess, - attrs, - None, - AstTarget::MacroCall, - call.span(), - self.cx.current_expansion.lint_node_id, - Some(self.cx.ecfg.features), - ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, - Some(self.cx.resolver.registered_attr_tools()), - ); + let parse = |group| { + AttributeParser::parse_limited_all( + self.cx.sess, + group, + None, + AstTarget::MacroCall, + call.span(), + self.cx.current_expansion.lint_node_id, + Some(self.cx.ecfg.features), + ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, + Some(self.cx.resolver.registered_attr_tools()), + ) + }; + + let mut doc_attrs = vec![]; + for attr in attrs { + if matches!(attr.kind, AttrKind::DocComment(..)) { + doc_attrs.push(attr.clone()); + continue; + } + parse(slice::from_ref(attr)); + } + + // Parse all doc comments together in a group, to prevent a group of + // unused doc comments from emitting multiple lints + if !doc_attrs.is_empty() { + parse(doc_attrs.as_slice()); + } } fn expand_cfg_true( From 0df0070ac45cb95b0cb8946d2cb456c70a173f7a Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Mon, 23 Nov 2026 10:10:29 +0100 Subject: [PATCH 48/48] Add regression test --- tests/ui/attributes/attr-on-mac-call.rs | 8 +++++++ tests/ui/attributes/attr-on-mac-call.stderr | 26 ++++++++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/tests/ui/attributes/attr-on-mac-call.rs b/tests/ui/attributes/attr-on-mac-call.rs index da57853f4bddd..514542994d4b1 100644 --- a/tests/ui/attributes/attr-on-mac-call.rs +++ b/tests/ui/attributes/attr-on-mac-call.rs @@ -151,4 +151,12 @@ fn main() { }] //~^^^ ERROR attribute value must be a literal unreachable!(); + + #[deprecated] + //~^ WARN cannot be used on + //~| WARN previously accepted + #[deprecated] + //~^ WARN cannot be used on + //~| WARN previously accepted + unreachable!(); } diff --git a/tests/ui/attributes/attr-on-mac-call.stderr b/tests/ui/attributes/attr-on-mac-call.stderr index d51f3ef574688..816e58608f949 100644 --- a/tests/ui/attributes/attr-on-mac-call.stderr +++ b/tests/ui/attributes/attr-on-mac-call.stderr @@ -436,6 +436,30 @@ LL | unreachable!(); = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion -error: aborting due to 8 previous errors; 30 warnings emitted +warning: the `deprecated` attribute cannot be used on macro calls + --> $DIR/attr-on-mac-call.rs:155:7 + | +LL | #[deprecated] + | ^^^^^^^^^^ +... +LL | unreachable!(); + | + = help: the `deprecated` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, foreign statics, functions, inherent impl blocks, macro defs, modules, statics, struct fields, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion + +warning: the `deprecated` attribute cannot be used on macro calls + --> $DIR/attr-on-mac-call.rs:158:7 + | +LL | #[deprecated] + | ^^^^^^^^^^ +... +LL | unreachable!(); + | + = help: the `deprecated` attribute can be applied to associated consts, associated types, constants, crates, data types, enum variants, foreign statics, functions, inherent impl blocks, macro defs, modules, statics, struct fields, traits, type aliases, and use statements + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion + +error: aborting due to 8 previous errors; 32 warnings emitted For more information about this error, try `rustc --explain E0658`.