From dcf3a6e49f5ec9e999efbcdacd8d1411964e33f3 Mon Sep 17 00:00:00 2001 From: A4-Tacks Date: Thu, 22 Oct 2026 17:04:25 +0800 Subject: [PATCH 01/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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/51] 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 a6a7951780e4a2c611f2970e730ae42a450be175 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sun, 25 Oct 2026 16:07:42 +0100 Subject: [PATCH 44/51] Pass both `attr_tools` and `lint_tools` into the attribute parser We will need the `lint_tools` in the next commits --- compiler/rustc_ast_lowering/src/lib.rs | 1 + compiler/rustc_attr_parsing/src/interface.rs | 17 +++++++++++++++-- compiler/rustc_expand/src/expand.rs | 1 + compiler/rustc_interface/src/limits.rs | 1 + compiler/rustc_lint/src/levels.rs | 1 + compiler/rustc_resolve/src/def_collector.rs | 1 + 6 files changed, 20 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index ae6bdd15853bc..f87ac63d1510b 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -378,6 +378,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { tcx.sess, tcx.features(), tcx.registered_attr_tools(()), + tcx.registered_lint_tools(()), ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, ), } diff --git a/compiler/rustc_attr_parsing/src/interface.rs b/compiler/rustc_attr_parsing/src/interface.rs index 8510b54aa6446..1c712a124241e 100644 --- a/compiler/rustc_attr_parsing/src/interface.rs +++ b/compiler/rustc_attr_parsing/src/interface.rs @@ -41,6 +41,7 @@ pub struct EmitAttribute( /// context, through which all attributes can be lowered. pub struct AttributeParser<'sess> { pub(crate) attr_tools: Option<&'sess RegisteredTools>, + pub(crate) lint_tools: Option<&'sess RegisteredTools>, pub(crate) features: Option<&'sess Features>, pub(crate) sess: &'sess Session, pub(crate) should_emit: ShouldEmit, @@ -116,6 +117,7 @@ impl<'sess> AttributeParser<'sess> { features, should_emit, None, + None, ); assert!(parsed.len() <= 1); parsed.pop() @@ -158,8 +160,10 @@ impl<'sess> AttributeParser<'sess> { features: Option<&'sess Features>, should_emit: ShouldEmit, attr_tools: Option<&'sess RegisteredTools>, + lint_tools: Option<&'sess RegisteredTools>, ) -> Vec { - let mut p = AttributeParser { features, attr_tools, parse_filter, sess, should_emit }; + let mut p = + AttributeParser { features, attr_tools, lint_tools, parse_filter, sess, should_emit }; p.parse_attribute_list( attrs, target_span, @@ -237,7 +241,14 @@ impl<'sess> AttributeParser<'sess> { parse_fn: fn(cx: &mut AcceptContext<'_, '_>, item: &I) -> T, template: &AttributeTemplate, ) -> T { - let mut parser = Self { features, attr_tools: None, parse_filter: None, sess, should_emit }; + let mut parser = Self { + features, + attr_tools: None, + lint_tools: None, + parse_filter: None, + sess, + should_emit, + }; let mut emit_lint = |lint_id: LintId, span: MultiSpan, kind: EmitAttribute| { sess.psess.dyn_buffer_lint_sess(lint_id.lint, span, target_node_id, kind.0) }; @@ -280,11 +291,13 @@ impl<'sess> AttributeParser<'sess> { sess: &'sess Session, features: &'sess Features, attr_tools: &'sess RegisteredTools, + lint_tools: &'sess RegisteredTools, should_emit: ShouldEmit, ) -> Self { Self { features: Some(features), attr_tools: Some(attr_tools), + lint_tools: Some(lint_tools), parse_filter: None, sess, should_emit, diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index d3dea34aff80e..d660082de994c 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -2238,6 +2238,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { Some(self.cx.ecfg.features), ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, Some(self.cx.resolver.registered_attr_tools()), + Some(self.cx.resolver.registered_lint_tools()), ); } diff --git a/compiler/rustc_interface/src/limits.rs b/compiler/rustc_interface/src/limits.rs index 2027ae7ad4bfd..b72d813fbef26 100644 --- a/compiler/rustc_interface/src/limits.rs +++ b/compiler/rustc_interface/src/limits.rs @@ -39,6 +39,7 @@ pub fn get_limits(krate_attrs: &[ast::Attribute], sess: &Session, features: &Fea // So, no lints here to avoid duplicates. ShouldEmit::EarlyFatal { also_emit_lints: false }, None, + None, ); let attrs = &attrs; Limits { diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index fd9a4ee74f5d7..c053d9478247a 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -704,6 +704,7 @@ where CRATE_NODE_ID, Some(self.features), ShouldEmit::ErrorsAndLints { recovery: Recovery::Allowed }, + None, Some(self.registered_lint_tools), ); self.add_hir_inner(&parsed, is_crate_node) diff --git a/compiler/rustc_resolve/src/def_collector.rs b/compiler/rustc_resolve/src/def_collector.rs index 37068c3b55d6d..601245f9e9fec 100644 --- a/compiler/rustc_resolve/src/def_collector.rs +++ b/compiler/rustc_resolve/src/def_collector.rs @@ -177,6 +177,7 @@ impl<'a, 'ra, 'tcx> visit::Visitor<'a> for DefCollector<'a, 'ra, 'tcx> { &self.r.tcx.sess, self.r.features, self.r.tcx().registered_attr_tools(()), + self.r.tcx().registered_lint_tools(()), ShouldEmit::Nothing, ); let attrs = parser.parse_attribute_list( From eb9dba4dd72eb612ef899dd0227aa2ca23c8d0eb Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Wed, 4 Nov 2026 14:19:21 +0100 Subject: [PATCH 45/51] Move lint validation from `Levels::add` to attribute parsing This is a lot of code being moved around, but not much of the logic changes. I changed some stuff though, so I recommend reviewing the logic side by side. --- Cargo.lock | 1 + compiler/rustc_attr_ir/src/lint.rs | 7 +- .../rustc_attr_parsing/src/attributes/lint.rs | 192 +++++++++++++++-- .../rustc_attr_parsing/src/diagnostics.rs | 82 +++++++ compiler/rustc_attr_parsing/src/lib.rs | 4 +- compiler/rustc_lint/src/context.rs | 35 +-- compiler/rustc_lint/src/diagnostics.rs | 82 +------ compiler/rustc_lint/src/levels.rs | 138 +++--------- compiler/rustc_lint/src/lib.rs | 2 +- compiler/rustc_lint_defs/Cargo.toml | 1 + compiler/rustc_lint_defs/src/lib.rs | 24 +++ compiler/rustc_passes/src/check_attr.rs | 8 +- compiler/rustc_session/src/session.rs | 7 + .../clippy/clippy_lints/src/collapsible_if.rs | 4 +- .../src/returns/needless_return.rs | 2 +- tests/pretty/delegation/generics.pp | 2 +- tests/pretty/delegation/inherit-attributes.pp | 2 +- tests/pretty/delegation/inline-attribute.pp | 2 +- tests/pretty/hir-delegation.pp | 2 +- tests/pretty/hir-lifetimes.pp | 2 +- tests/pretty/lint-attrs-filtered-out.pp | 11 + tests/pretty/pin-ergonomics-hir.pp | 4 +- tests/ui/eii/cfg_on_eii.stdout | 2 +- ...eature-gate-strict_provenance_lints.stderr | 28 +-- ...issue-43106-gating-of-builtin-attrs.stderr | 204 +++++++++--------- tests/ui/lint/register-tool-lint.rs | 2 - tests/ui/lint/register-tool-lint.stderr | 11 +- .../ui/lint/renamed-lints-still-apply.stderr | 16 +- tests/ui/tool-attributes/cross-crate.rs | 2 - tests/ui/tool-attributes/cross-crate.stderr | 20 +- tests/ui/tool-attributes/tool_lints.rs | 2 - tests/ui/tool-attributes/tool_lints.stderr | 20 +- .../tool-attributes/unknown-lint-tool-name.rs | 4 - .../unknown-lint-tool-name.stderr | 40 +--- tests/ui/unpretty/exhaustive.hir.stdout | 8 +- ...ct-exprs-tuple-call-pretty-printing.stdout | 2 +- tests/ui/unpretty/unpretty-expr-fn-arg.stdout | 2 +- 37 files changed, 499 insertions(+), 478 deletions(-) create mode 100644 tests/pretty/lint-attrs-filtered-out.pp diff --git a/Cargo.lock b/Cargo.lock index bae8add757e7f..a8d4849f20267 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4347,6 +4347,7 @@ dependencies = [ "rustc_macros", "rustc_serialize", "rustc_span", + "rustc_structures", "serde", ] diff --git a/compiler/rustc_attr_ir/src/lint.rs b/compiler/rustc_attr_ir/src/lint.rs index 2dafadf4cb2a9..163de374d96fb 100644 --- a/compiler/rustc_attr_ir/src/lint.rs +++ b/compiler/rustc_attr_ir/src/lint.rs @@ -45,7 +45,12 @@ impl LintCheckKind { /// ``` #[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)] pub struct LintCheck { - pub lint_name: LintName, + /// The full normalized lint name of an existing lint, including the tool name. + /// This may not be what we user wrote down, in case of renamed lints the new lint name is here. + /// The above implies that `LintStore::find_lints` is guaranteed to find this lint using this symbol. + /// + /// For example, `single_use_lifetime` is changed to `single_use_lifetimes`. + pub lint_name_normalized: LintName, pub kind: LintCheckKind, pub reason: Option, /// Needed by `LintExpectationId` to track fulfilled expectations diff --git a/compiler/rustc_attr_parsing/src/attributes/lint.rs b/compiler/rustc_attr_parsing/src/attributes/lint.rs index 45cbcf4664404..53ebc9953e03c 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint.rs @@ -1,14 +1,20 @@ +use rustc_ast::join_path_syms; use rustc_attr_ir::AttributeKind; use rustc_attr_ir::lint::{LintCheck, LintCheckKind}; use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target}; -use rustc_lint_defs::builtin::UNUSED_ATTRIBUTES; -use rustc_span::sym; +use rustc_lint_defs::builtin::{RENAMED_AND_REMOVED_LINTS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES}; +use rustc_lint_defs::{CheckLintNameResult, LintId}; +use rustc_span::{DUMMY_SP, Span, Symbol, sym}; use rustc_structures::LintName; use thin_vec::ThinVec; use crate::attributes::{AcceptMapping, AttributeParser, AttributeStability}; use crate::context::{AcceptContext, ExpectStringLiteral, FinalizeContext}; -use crate::diagnostics::{MalformedLintAttributeInput, MalformedLintAttributeInputHelp}; +use crate::diagnostics::{ + DeprecatedLintName, MalformedLintAttributeInput, MalformedLintAttributeInputHelp, RemovedLint, + RenamedLint, RenamedLintSuggestion, UnknownLint, UnknownLintSuggestion, + UnknownToolInScopedLint, +}; use crate::parser::{ArgParser, MetaItemOrLitParser}; use crate::target_checking::AllowedTargets; use crate::target_checking::Policy::{Allow, Warn}; @@ -55,21 +61,48 @@ impl LintParser { match item { MetaItemOrLitParser::MetaItemParser(p) => { match p.args() { - ArgParser::NoArgs => self.lints.push(LintCheck { - lint_name: LintName::new( - p.path().0.segments.iter().map(|s| s.ident.name), - ), - kind, - attr_id, - reason, - attr_span, - lint_span: p.span(), - tool_span: if let [tool, _, ..] = &*p.path().0.segments { - Some(tool.span()) + ArgParser::NoArgs => { + let (tool, lint_name) = match &*p.path().0.segments { + [] => unreachable!(), + [lint_name] => (None, lint_name.ident.name), + [tool, lint_name] => (Some(tool.ident), lint_name.ident.name), + // Not reachable for any builtin lints, + // but reachable using `register_tool`. + [tool, multi_segment_lint_name @ ..] => ( + Some(tool.ident), + Symbol::intern(&join_path_syms( + multi_segment_lint_name + .iter() + .map(|seg| seg.ident.name), + )), + ), + }; + let lint_name = + LintName { tool: tool.map(|tool| tool.name), name: lint_name }; + + let lint_name_normalized = if let Some((_lint_ids, new_lint_name)) = + Self::check_lint_name( + lint_name, + tool.map(|tool| tool.span), + p.span(), + cx, + ) { + new_lint_name } else { - None - }, - }), + // Discard lint attributes with unknown lints in them + continue; + }; + + self.lints.push(LintCheck { + lint_name_normalized, + lint_span: p.span(), + kind, + attr_id, + reason, + attr_span, + tool_span: tool.map(|tool| tool.span), + }) + } // We've found a `reason = "reason"` but we're not the last element. ArgParser::NameValue(nv) if p.path().word_is(sym::reason) => { cx.emit_err(diagnostics::MalformedAttribute { @@ -126,6 +159,131 @@ impl LintParser { } } } + + fn check_lint_name<'a>( + lint_name: LintName, + tool_span: Option, + lint_span: Span, + cx: &mut AcceptContext<'_, 'a>, + ) -> Option<(&'a [LintId], LintName)> { + let lint_result = + cx.sess.lint_store.as_ref().unwrap().check_lint_name(lint_name, cx.lint_tools.unwrap()); + + // FIXME(164898) Lint attributes are parsed twice, once on the AST and once on the HIR + // Both times emit diagnostics, for historic reasons + // We only want to emit these lints once, on the HIR. + // On the AST `target_span` will be `DUMMY_SP`, which we use to detect which instance we are. + // #164898 will fix this, after that PR this check can be removed + let should_lint = cx.target_span != DUMMY_SP; + + let (ids, name) = match lint_result { + CheckLintNameResult::Ok(ids) => (ids, lint_name), + + CheckLintNameResult::Tool(ids, new_lint_name) => { + let name = match new_lint_name { + None => lint_name, + Some(replacement) => { + if should_lint { + cx.emit_lint( + RENAMED_AND_REMOVED_LINTS, + DeprecatedLintName { + lint_name, + suggestion: lint_span, + replacement, + }, + lint_span, + ); + } + replacement + } + }; + (ids, name) + } + + CheckLintNameResult::MissingTool => { + // If `MissingTool` is returned, then either the lint does not + // exist in the tool or the code was not compiled with the tool and + // therefore the lint was never added to the `LintStore`. To detect + // this is the responsibility of the lint tool. + return None; + } + + CheckLintNameResult::NoTool(tool_name) => { + if should_lint { + cx.emit_err(UnknownToolInScopedLint { + span: Some(tool_span.unwrap()), + tool_name, + lint_name, + is_nightly_build: cx.sess.is_nightly_build(), + }); + } + return None; + } + + CheckLintNameResult::Renamed(replacement) => { + if should_lint { + let suggestion = + RenamedLintSuggestion::WithSpan { suggestion: lint_span, replacement }; + cx.emit_lint( + RENAMED_AND_REMOVED_LINTS, + RenamedLint { name: lint_name, replacement, suggestion }, + lint_span, + ); + } + + // If this lint was renamed, apply the new lint instead of ignoring the + // attribute. Ignore any errors or warnings that happen because the new + // name is inaccurate. + // NOTE: `new_name` already includes the tool name, so we don't + // have to add it again. + let replace_check = cx + .sess + .lint_store + .as_ref() + .unwrap() + .check_lint_name(replacement, cx.lint_tools.unwrap()); + let (CheckLintNameResult::Ok(ids) | CheckLintNameResult::Tool(ids, _)) = + replace_check + else { + panic!( + "renamed lint does not exist: {lint_name} => {replacement}\n{replace_check:?}" + ); + }; + + (ids, replacement) + } + + CheckLintNameResult::Removed(ref reason) => { + if should_lint { + cx.emit_lint( + RENAMED_AND_REMOVED_LINTS, + RemovedLint { name: lint_name, reason: reason.clone() }, + lint_span, + ); + } + return None; + } + + CheckLintNameResult::NoLint(suggestion) => { + if should_lint { + let suggestion = suggestion.map(|(replacement, from_rustc)| { + UnknownLintSuggestion::WithSpan { + suggestion: lint_span, + replacement, + from_rustc, + } + }); + cx.emit_lint( + UNKNOWN_LINTS, + UnknownLint { name: lint_name, suggestion }, + lint_span, + ); + } + return None; + } + }; + Some((ids, name)) + } } impl AttributeParser for LintParser { diff --git a/compiler/rustc_attr_parsing/src/diagnostics.rs b/compiler/rustc_attr_parsing/src/diagnostics.rs index 12b2fe8cff6e8..7d0aa9669516f 100644 --- a/compiler/rustc_attr_parsing/src/diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/diagnostics.rs @@ -7,6 +7,7 @@ use rustc_errors::{ }; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Ident, Span, Symbol}; +use rustc_structures::LintName; use rustc_target::spec::TargetTuple; use crate::AttributeTemplate; @@ -2293,3 +2294,84 @@ pub(crate) enum BuiltinUnusedDocCommentSub { #[help("use `/* */` for a plain comment")] BlockHelp, } + +#[derive(Diagnostic)] +#[diag("lint name `{$lint_name}` is deprecated and may not have an effect in the future")] +pub(crate) struct DeprecatedLintName { + pub lint_name: LintName, + #[suggestion("change it to", code = "{replacement}", applicability = "machine-applicable")] + pub suggestion: Span, + pub replacement: LintName, +} + +#[derive(Diagnostic)] +#[diag("unknown tool name `{$tool_name}` found in scoped lint: `{$lint_name}`", code = E0710)] +pub(crate) struct UnknownToolInScopedLint { + #[primary_span] + pub span: Option, + pub tool_name: Symbol, + pub lint_name: LintName, + #[help("add `#![register_tool({$tool_name})]` to the crate root")] + pub is_nightly_build: bool, +} + +#[derive(Diagnostic)] +#[diag("lint `{$name}` has been renamed to `{$replacement}`")] +pub(crate) struct RenamedLint { + pub name: LintName, + pub replacement: LintName, + #[subdiagnostic] + pub suggestion: RenamedLintSuggestion, +} + +#[derive(Subdiagnostic)] +pub enum RenamedLintSuggestion { + #[suggestion("use the new name", code = "{replacement}", applicability = "machine-applicable")] + WithSpan { + #[primary_span] + suggestion: Span, + replacement: LintName, + }, + #[help("use the new name `{$replacement}`")] + WithoutSpan { replacement: LintName }, +} + +#[derive(Diagnostic)] +#[diag("unknown lint: `{$name}`")] +pub(crate) struct UnknownLint { + pub name: LintName, + #[subdiagnostic] + pub suggestion: Option, +} + +#[derive(Subdiagnostic)] +pub enum UnknownLintSuggestion { + #[suggestion( + "{$from_rustc -> + [true] a lint with a similar name exists in `rustc` lints + *[false] did you mean + }", + code = "{replacement}", + applicability = "maybe-incorrect" + )] + WithSpan { + #[primary_span] + suggestion: Span, + replacement: LintName, + from_rustc: bool, + }, + #[help( + "{$from_rustc -> + [true] a lint with a similar name exists in `rustc` lints: `{$replacement}` + *[false] did you mean: `{$replacement}` + }" + )] + WithoutSpan { replacement: LintName, from_rustc: bool }, +} + +#[derive(Diagnostic)] +#[diag("lint `{$name}` has been removed: {$reason}")] +pub(crate) struct RemovedLint { + pub name: LintName, + pub reason: String, +} diff --git a/compiler/rustc_attr_parsing/src/lib.rs b/compiler/rustc_attr_parsing/src/lib.rs index 009ea86b762b2..d2b8ac6cd2db1 100644 --- a/compiler/rustc_attr_parsing/src/lib.rs +++ b/compiler/rustc_attr_parsing/src/lib.rs @@ -119,7 +119,9 @@ pub use attributes::cfg_select::*; pub use attributes::crate_level::PREDEFINED_TOOLS; pub use attributes::util::{is_builtin_attr, parse_version}; pub use context::ShouldEmit; -pub use diagnostics::{DuplicateAttribute, ParsedDescription}; +pub use diagnostics::{ + DuplicateAttribute, ParsedDescription, RenamedLintSuggestion, UnknownLintSuggestion, +}; pub use interface::{AttributeParser, EmitAttribute}; pub use rustc_parse::parser::Recovery; pub use template::AttributeTemplate; diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index da0c8a195cf1a..44aa75e5d7d7b 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -19,8 +19,8 @@ use rustc_hir::def_id::{CrateNum, DefId}; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_hir::{Pat, PatKind}; use rustc_lint_defs::{ - FutureIncompatibleInfo, Lint, LintExpectationId, LintId, StableLintExpectationId, - UnstableLintExpectationId, + CheckLintNameResult, FutureIncompatibleInfo, Lint, LintExpectationId, LintId, + StableLintExpectationId, UnstableLintExpectationId, }; use rustc_middle::lint::{LevelSpec, StableLevelSpec, UnstableLevelSpec}; use rustc_middle::middle::privacy::EffectiveVisibilities; @@ -90,6 +90,14 @@ impl DynLintStore for LintStore { rustc_session::LintGroup { name, lints, is_externally_loaded } })) } + + fn check_lint_name( + &self, + lint_name: LintName, + registered_tools: &RegisteredTools, + ) -> CheckLintNameResult<'_> { + self.check_lint_name(lint_name, registered_tools) + } } /// The target of the `by_name` map, which accounts for renaming/deprecation. @@ -124,29 +132,6 @@ struct LintGroup { depr: Option, } -#[derive(Debug)] -pub enum CheckLintNameResult<'a> { - Ok(&'a [LintId]), - /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name. - NoLint(Option<(LintName, bool)>), - /// The lint refers to a tool that has not been registered. - NoTool(Symbol), - /// The lint has been renamed to a new name. - Renamed(LintName), - /// The lint has been removed due to the given reason. - Removed(String), - - /// The lint is from a tool. The `LintId` will be returned as if it were a - /// rustc lint. The `Option` indicates if the lint has been - /// renamed. - Tool(&'a [LintId], Option), - - /// The lint is from a tool. Either the lint does not exist in the tool or - /// the code was not compiled with the tool and therefore the lint was - /// never added to the `LintStore`. - MissingTool, -} - impl LintStore { pub fn new() -> LintStore { LintStore { diff --git a/compiler/rustc_lint/src/diagnostics.rs b/compiler/rustc_lint/src/diagnostics.rs index 69cdee19a56fb..15d957173589d 100644 --- a/compiler/rustc_lint/src/diagnostics.rs +++ b/compiler/rustc_lint/src/diagnostics.rs @@ -2,6 +2,7 @@ use std::num::NonZero; use rustc_attr_ir::find_attr; +use rustc_attr_parsing::{RenamedLintSuggestion, UnknownLintSuggestion}; use rustc_data_structures::fx::FxIndexMap; use rustc_errors::codes::*; use rustc_errors::formatting::DiagMessageAddArg; @@ -66,17 +67,6 @@ impl Subdiagnostic for OverruledAttributeSub { } } -#[derive(Diagnostic)] -#[diag("unknown tool name `{$tool_name}` found in scoped lint: `{$lint_name}`", code = E0710)] -pub(crate) struct UnknownToolInScopedLint { - #[primary_span] - pub span: Option, - pub tool_name: Symbol, - pub lint_name: LintName, - #[help("add `#![register_tool({$tool_name})]` to the crate root")] - pub is_nightly_build: bool, -} - #[derive(Diagnostic)] #[diag("functions generic over types or consts must be mangled")] pub(crate) struct BuiltinNoMangleGeneric { @@ -1401,15 +1391,6 @@ pub(crate) struct OverruledAttributeLint<'a> { pub sub: OverruledAttributeSub, } -#[derive(Diagnostic)] -#[diag("lint name `{$lint_name}` is deprecated and may not have an effect in the future")] -pub(crate) struct DeprecatedLintName { - pub lint_name: LintName, - #[suggestion("change it to", code = "{replacement}", applicability = "machine-applicable")] - pub suggestion: Span, - pub replacement: LintName, -} - #[derive(Diagnostic)] #[diag("lint name `{$lint_name}` is deprecated and may not have an effect in the future")] #[help("change it to {$replacement}")] @@ -1420,27 +1401,6 @@ pub(crate) struct DeprecatedLintNameFromCommandLine { pub requested_level: RequestedLevel, } -#[derive(Diagnostic)] -#[diag("lint `{$name}` has been renamed to `{$replacement}`")] -pub(crate) struct RenamedLint { - pub name: LintName, - pub replacement: LintName, - #[subdiagnostic] - pub suggestion: RenamedLintSuggestion, -} - -#[derive(Subdiagnostic)] -pub(crate) enum RenamedLintSuggestion { - #[suggestion("use the new name", code = "{replacement}", applicability = "machine-applicable")] - WithSpan { - #[primary_span] - suggestion: Span, - replacement: LintName, - }, - #[help("use the new name `{$replacement}`")] - WithoutSpan { replacement: LintName }, -} - #[derive(Diagnostic)] #[diag("lint `{$lint_name}` has been renamed to `{$replacement}`")] pub(crate) struct RenamedLintFromCommandLine { @@ -1452,13 +1412,6 @@ pub(crate) struct RenamedLintFromCommandLine { pub requested_level: RequestedLevel, } -#[derive(Diagnostic)] -#[diag("lint `{$name}` has been removed: {$reason}")] -pub(crate) struct RemovedLint<'a> { - pub name: LintName, - pub reason: &'a str, -} - #[derive(Diagnostic)] #[diag("lint `{$lint_name}` has been removed: {$reason}")] pub(crate) struct RemovedLintFromCommandLine<'a> { @@ -1468,39 +1421,6 @@ pub(crate) struct RemovedLintFromCommandLine<'a> { pub requested_level: RequestedLevel, } -#[derive(Diagnostic)] -#[diag("unknown lint: `{$name}`")] -pub(crate) struct UnknownLint { - pub name: LintName, - #[subdiagnostic] - pub suggestion: Option, -} - -#[derive(Subdiagnostic)] -pub(crate) enum UnknownLintSuggestion { - #[suggestion( - "{$from_rustc -> - [true] a lint with a similar name exists in `rustc` lints - *[false] did you mean - }", - code = "{replacement}", - applicability = "maybe-incorrect" - )] - WithSpan { - #[primary_span] - suggestion: Span, - replacement: LintName, - from_rustc: bool, - }, - #[help( - "{$from_rustc -> - [true] a lint with a similar name exists in `rustc` lints: `{$replacement}` - *[false] did you mean: `{$replacement}` - }" - )] - WithoutSpan { replacement: LintName, from_rustc: bool }, -} - #[derive(Diagnostic)] #[diag("unknown lint: `{$lint_name}`", code = E0602)] pub(crate) struct UnknownLintFromCommandLine { diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index c053d9478247a..171c36c0455e3 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -5,7 +5,9 @@ use rustc_ast::CRATE_NODE_ID; use rustc_attr_ir::lint::{LintCheck, LintCheckKind}; use rustc_attr_ir::target::{AstTarget, Target}; use rustc_attr_ir::{Attribute, DocAttribute, find_attr}; -use rustc_attr_parsing::{AttributeParser, Recovery, ShouldEmit}; +use rustc_attr_parsing::{ + AttributeParser, Recovery, RenamedLintSuggestion, ShouldEmit, UnknownLintSuggestion, +}; use rustc_data_structures::fx::{FxHashSet, FxIndexMap}; use rustc_data_structures::unord::UnordSet; use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, MultiSpan, msg}; @@ -19,7 +21,8 @@ use rustc_lint_defs::builtin::{ UNFULFILLED_LINT_EXPECTATIONS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES, }; use rustc_lint_defs::{ - Level, Lint, LintExpectationId, LintId, StableLintExpectationId, UnstableLintExpectationId, + CheckLintNameResult, Level, Lint, LintExpectationId, LintId, StableLintExpectationId, + UnstableLintExpectationId, }; use rustc_middle::hir::nested_filter; use rustc_middle::lint::{ @@ -35,13 +38,11 @@ use rustc_structures::LintName; use tracing::{debug, instrument}; use crate::builtin::MISSING_DOCS; -use crate::context::{CheckLintNameResult, LintStore}; +use crate::context::LintStore; use crate::diagnostics::{ - CheckNameUnknownTool, DeprecatedLintName, DeprecatedLintNameFromCommandLine, - IgnoredUnlessCrateSpecified, OverruledAttribute, OverruledAttributeLint, OverruledAttributeSub, - RemovedLint, RemovedLintFromCommandLine, RenamedLint, RenamedLintFromCommandLine, - RenamedLintSuggestion, RequestedLevel, UnknownLint, UnknownLintFromCommandLine, - UnknownLintSuggestion, UnknownToolInScopedLint, UnsupportedGroup, + CheckNameUnknownTool, DeprecatedLintNameFromCommandLine, IgnoredUnlessCrateSpecified, + OverruledAttribute, OverruledAttributeLint, OverruledAttributeSub, RemovedLintFromCommandLine, + RenamedLintFromCommandLine, RequestedLevel, UnknownLintFromCommandLine, UnsupportedGroup, }; use crate::late::unerased_lint_store; @@ -729,13 +730,17 @@ where return; }; - let sess = self.sess; - // FIXME: consider performing these checks in attribute parsing instead for (lint_index, lint_check) in lint_checks.into_iter().enumerate() { - let LintCheck { lint_name, kind, reason, attr_id, attr_span: _, lint_span, tool_span } = - lint_check; - let LintName { tool, name: _ } = lint_name; + let LintCheck { + lint_name_normalized, + lint_span, + kind, + reason, + attr_id, + attr_span: _, + tool_span: _, + } = lint_check; let level = match kind { LintCheckKind::Allow => Level::Allow, @@ -750,105 +755,9 @@ where let lint_id = (level == Level::Expect) .then(|| self.provider.mk_lint_expectation_id(attr_id.attr_id, lint_index as u16)); - let lint_result = self.store.check_lint_name(lint_name, self.registered_lint_tools); - - let (ids, name): (_, LintName) = match lint_result { - CheckLintNameResult::Ok(ids) => (ids, lint_name), - - CheckLintNameResult::Tool(ids, new_lint_name) => { - let name = match new_lint_name { - None => lint_name, - Some(replacement) => { - self.emit_span_lint( - builtin::RENAMED_AND_REMOVED_LINTS, - lint_span.into(), - DeprecatedLintName { - lint_name, - suggestion: lint_span, - replacement, - }, - ); - replacement - } - }; - (ids, name) - } - - CheckLintNameResult::MissingTool => { - // If `MissingTool` is returned, then either the lint does not - // exist in the tool or the code was not compiled with the tool and - // therefore the lint was never added to the `LintStore`. To detect - // this is the responsibility of the lint tool. - continue; - } - - CheckLintNameResult::NoTool(tool_name) => { - sess.dcx().emit_err(UnknownToolInScopedLint { - span: Some(tool_span.unwrap()), - tool_name, - lint_name, - is_nightly_build: sess.is_nightly_build(), - }); - continue; - } - - CheckLintNameResult::Renamed(replacement) => { - if self.lint_added_lints { - let suggestion = - RenamedLintSuggestion::WithSpan { suggestion: lint_span, replacement }; - - self.emit_span_lint( - RENAMED_AND_REMOVED_LINTS, - lint_span.into(), - RenamedLint { name: lint_name, replacement, suggestion }, - ); - } - - // If this lint was renamed, apply the new lint instead of ignoring the - // attribute. Ignore any errors or warnings that happen because the new - // name is inaccurate. - let replace_check = - self.store.check_lint_name(replacement, self.registered_lint_tools); - let (CheckLintNameResult::Ok(ids) | CheckLintNameResult::Tool(ids, _)) = - replace_check - else { - panic!("renamed lint does not exist: {replacement} :{replace_check:?}"); - }; - - (ids, replacement) - } - - CheckLintNameResult::Removed(ref reason) => { - if self.lint_added_lints { - self.emit_span_lint( - RENAMED_AND_REMOVED_LINTS, - lint_span.into(), - RemovedLint { name: lint_name, reason }, - ); - } - continue; - } - - CheckLintNameResult::NoLint(suggestion) => { - if self.lint_added_lints { - let suggestion = suggestion.map(|(replacement, from_rustc)| { - UnknownLintSuggestion::WithSpan { - suggestion: lint_span, - replacement, - from_rustc, - } - }); - self.emit_span_lint( - UNKNOWN_LINTS, - lint_span.into(), - UnknownLint { name: lint_name, suggestion }, - ); - } - continue; - } - }; + let src = LintLevelSource::Node { name: lint_name_normalized, span: lint_span, reason }; + let ids = self.store.find_lints(lint_name_normalized).unwrap(); - let src = LintLevelSource::Node { name, span: lint_span, reason }; for &id in ids { if self.check_gated_lint(id, lint_span, false) { self.insert_spec(id, LevelSpec::new(level, lint_id, src)); @@ -870,7 +779,12 @@ where }; self.provider.push_expectation( expect_id, - LintExpectation::new(reason, lint_span, is_unfulfilled_lint_expectations, tool), + LintExpectation::new( + reason, + lint_span, + is_unfulfilled_lint_expectations, + lint_name_normalized.tool, + ), ); } } diff --git a/compiler/rustc_lint/src/lib.rs b/compiler/rustc_lint/src/lib.rs index 2c3365028844a..7abae06fd81fe 100644 --- a/compiler/rustc_lint/src/lib.rs +++ b/compiler/rustc_lint/src/lib.rs @@ -139,7 +139,7 @@ use unused::*; #[rustfmt::skip] pub use builtin::MissingDoc; -pub use context::{CheckLintNameResult, EarlyContext, LateContext, LintContext, LintStore}; +pub use context::{EarlyContext, LateContext, LintContext, LintStore}; pub use early::diagnostics::DiagAndSess; pub use early::{EarlyCheckNode, check_ast_node}; pub use late::{check_crate, late_lint_mod, unerased_lint_store}; diff --git a/compiler/rustc_lint_defs/Cargo.toml b/compiler/rustc_lint_defs/Cargo.toml index c8201d5ea8ccc..71c9bf153c3cc 100644 --- a/compiler/rustc_lint_defs/Cargo.toml +++ b/compiler/rustc_lint_defs/Cargo.toml @@ -8,6 +8,7 @@ edition = "2024" rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_error_messages = { path = "../rustc_error_messages" } +rustc_structures = { path = "../rustc_structures" } rustc_hir_id = { path = "../rustc_hir_id" } rustc_macros = { path = "../rustc_macros" } rustc_serialize = { path = "../rustc_serialize" } diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 019bb098e99a2..8f3e51d80ed6c 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -15,6 +15,7 @@ use rustc_hir_id::HirId; use rustc_macros::{Decodable, Encodable, StableHash}; use rustc_span::edition::Edition; use rustc_span::{AttrId, Ident, Symbol, sym}; +use rustc_structures::LintName; use serde::{Deserialize, Serialize}; pub use self::Level::*; @@ -635,6 +636,29 @@ impl ToolOptions { pub type RegisteredTools = FxIndexMap; +#[derive(Debug)] +pub enum CheckLintNameResult<'a> { + Ok(&'a [LintId]), + /// Lint doesn't exist. Potentially contains a suggestion for a correct lint name. + NoLint(Option<(LintName, bool)>), + /// The lint refers to a tool that has not been registered. + NoTool(Symbol), + /// The lint has been renamed to a new name. + Renamed(LintName), + /// The lint has been removed due to the given reason. + Removed(String), + + /// The lint is from a tool. The `LintId` will be returned as if it were a + /// rustc lint. The `Option` indicates if the lint has been + /// renamed. + Tool(&'a [LintId], Option), + + /// The lint is from a tool. Either the lint does not exist in the tool or + /// the code was not compiled with the tool and therefore the lint was + /// never added to the `LintStore`. + MissingTool, +} + /// Declares a static item of type `&'static Lint`. /// /// See for diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 5dd1718d68d49..05c0f44afda14 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -1344,8 +1344,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } fn check_lint_check(&self, hir_id: HirId, lints: &[LintCheck]) { - for LintCheck { lint_name, lint_span, .. } in lints { - if lint_name.is(sym::dead_code_pub_in_binary) { + for LintCheck { lint_name_normalized, lint_span, .. } in lints { + if lint_name_normalized.is(sym::dead_code_pub_in_binary) { if !self.tcx.crate_types().contains(&CrateType::Executable) { self.tcx.emit_node_span_lint( UNUSED_ATTRIBUTES, @@ -1359,7 +1359,9 @@ impl<'tcx> CheckAttrVisitor<'tcx> { } } - if lint_name.is(sym::linker_messages) | lint_name.is(sym::linker_info) { + if lint_name_normalized.is(sym::linker_messages) + | lint_name_normalized.is(sym::linker_info) + { if hir_id == CRATE_HIR_ID && self .tcx diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 6b7e2214f26d9..a64ebd5d27c7d 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -21,6 +21,7 @@ use rustc_errors::{ Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, PResult, TerminalUrl, }; use rustc_feature::UnstableFeatures; +use rustc_lint_defs::{CheckLintNameResult, RegisteredTools}; use rustc_macros::StableHash; pub use rustc_span::def_id::StableCrateId; use rustc_span::edition::Edition; @@ -83,6 +84,12 @@ pub struct CompilerIO { pub trait DynLintStore: Any + DynSync + DynSend { /// Provides a way to access lint groups without depending on `rustc_lint` fn lint_groups_iter(&self) -> Box + '_>; + + fn check_lint_name( + &self, + lint_name: LintName, + registered_tools: &RegisteredTools, + ) -> CheckLintNameResult<'_>; } /// Hardware pointer-signing keys in ARM8.3. diff --git a/src/tools/clippy/clippy_lints/src/collapsible_if.rs b/src/tools/clippy/clippy_lints/src/collapsible_if.rs index e334eae38c0dc..2ad1d6c7e6ffb 100644 --- a/src/tools/clippy/clippy_lints/src/collapsible_if.rs +++ b/src/tools/clippy/clippy_lints/src/collapsible_if.rs @@ -248,7 +248,7 @@ impl CollapsibleIf { matches!( lint, LintCheck { - lint_name: LintName { + lint_name_normalized: LintName { tool: Some(sym::clippy), .. }, @@ -257,7 +257,7 @@ impl CollapsibleIf { } ) }) - .any(|lint| [expected_lint_name, sym::style, sym::all].contains(&lint.lint_name.name)) => + .any(|lint| [expected_lint_name, sym::style, sym::all].contains(&lint.lint_name_normalized.name)) => { let attr_span = lints.first().unwrap().attr_span.to(lints.last().unwrap().attr_span); // There is an `expect` attribute -- check that there is no _other_ significant text diff --git a/src/tools/clippy/clippy_lints/src/returns/needless_return.rs b/src/tools/clippy/clippy_lints/src/returns/needless_return.rs index 915211d74fc1b..71b5044879da1 100644 --- a/src/tools/clippy/clippy_lints/src/returns/needless_return.rs +++ b/src/tools/clippy/clippy_lints/src/returns/needless_return.rs @@ -189,7 +189,7 @@ fn check_final_expr<'tcx>( matches!( lint, LintCheck { - lint_name: LintName { + lint_name_normalized: LintName { tool: Some(sym::clippy), name: sym::needless_return | sym::style | sym::all | sym::warnings }, diff --git a/tests/pretty/delegation/generics.pp b/tests/pretty/delegation/generics.pp index f5b42b351633d..dce3886a4f15c 100644 --- a/tests/pretty/delegation/generics.pp +++ b/tests/pretty/delegation/generics.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] #![attr = Feature([fn_delegation#0])] extern crate std; diff --git a/tests/pretty/delegation/inherit-attributes.pp b/tests/pretty/delegation/inherit-attributes.pp index 53f977ebbb7ac..b08a2f37eb4b2 100644 --- a/tests/pretty/delegation/inherit-attributes.pp +++ b/tests/pretty/delegation/inherit-attributes.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] #![attr = Feature([fn_delegation#0])] extern crate std; diff --git a/tests/pretty/delegation/inline-attribute.pp b/tests/pretty/delegation/inline-attribute.pp index 8787a9e167405..faaacfbc6a4b5 100644 --- a/tests/pretty/delegation/inline-attribute.pp +++ b/tests/pretty/delegation/inline-attribute.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] #![attr = Feature([fn_delegation#0])] extern crate std; diff --git a/tests/pretty/hir-delegation.pp b/tests/pretty/hir-delegation.pp index 97364da0e02d8..1b74b8f8ba911 100644 --- a/tests/pretty/hir-delegation.pp +++ b/tests/pretty/hir-delegation.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] #![attr = Feature([fn_delegation#0])] extern crate std; diff --git a/tests/pretty/hir-lifetimes.pp b/tests/pretty/hir-lifetimes.pp index daee41b37889d..85b36fba7ef3c 100644 --- a/tests/pretty/hir-lifetimes.pp +++ b/tests/pretty/hir-lifetimes.pp @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "unused" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "unused" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] diff --git a/tests/pretty/lint-attrs-filtered-out.pp b/tests/pretty/lint-attrs-filtered-out.pp new file mode 100644 index 0000000000000..796fa2fe239b0 --- /dev/null +++ b/tests/pretty/lint-attrs-filtered-out.pp @@ -0,0 +1,11 @@ +extern crate std; +#[attr = PreludeImport] +use ::std::prelude::rust_2015::*; +//@ pretty-compare-only +//@ pretty-mode:hir +//@ pp-exact:lint-attrs-filtered-out.pp + +// `does_not_exist` is filtered out on the hir +#[attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, +kind: Deny}])] +fn main() { } diff --git a/tests/pretty/pin-ergonomics-hir.pp b/tests/pretty/pin-ergonomics-hir.pp index 624cd37ce5fc4..11b4a87b1c4ce 100644 --- a/tests/pretty/pin-ergonomics-hir.pp +++ b/tests/pretty/pin-ergonomics-hir.pp @@ -1,7 +1,7 @@ #![attr = Feature([pin_ergonomics#0])] -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "dead_code" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, kind: Allow}, -LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] diff --git a/tests/ui/eii/cfg_on_eii.stdout b/tests/ui/eii/cfg_on_eii.stdout index 8d3e892b0867d..74922ab51f3f0 100644 --- a/tests/ui/eii/cfg_on_eii.stdout +++ b/tests/ui/eii/cfg_on_eii.stdout @@ -1,5 +1,5 @@ #![attr = Feature([extern_item_impls#0, extern_item_default_impls#0])] -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "deprecated" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "deprecated" }, kind: Deny}])] extern crate std; #[attr = PreludeImport] diff --git a/tests/ui/feature-gates/feature-gate-strict_provenance_lints.stderr b/tests/ui/feature-gates/feature-gate-strict_provenance_lints.stderr index 4e7c835b57912..d14e7328c308c 100644 --- a/tests/ui/feature-gates/feature-gate-strict_provenance_lints.stderr +++ b/tests/ui/feature-gates/feature-gate-strict_provenance_lints.stderr @@ -10,14 +10,6 @@ LL | #![deny(implicit_provenance_casts)] = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date = note: `#[warn(unknown_lints)]` on by default -warning: lint `fuzzy_provenance_casts` has been renamed to `implicit_provenance_casts` - --> $DIR/feature-gate-strict_provenance_lints.rs:7:9 - | -LL | #![deny(fuzzy_provenance_casts)] - | ^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `implicit_provenance_casts` - | - = note: `#[warn(renamed_and_removed_lints)]` on by default - warning: unknown lint: `implicit_provenance_casts` --> $DIR/feature-gate-strict_provenance_lints.rs:7:9 | @@ -29,12 +21,6 @@ LL | #![deny(fuzzy_provenance_casts)] = help: add `#![feature(strict_provenance_lints)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date -warning: lint `lossy_provenance_casts` has been renamed to `implicit_provenance_casts` - --> $DIR/feature-gate-strict_provenance_lints.rs:10:9 - | -LL | #![deny(lossy_provenance_casts)] - | ^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `implicit_provenance_casts` - warning: unknown lint: `implicit_provenance_casts` --> $DIR/feature-gate-strict_provenance_lints.rs:10:9 | @@ -46,5 +32,19 @@ LL | #![deny(lossy_provenance_casts)] = help: add `#![feature(strict_provenance_lints)]` to the crate attributes to enable = note: this compiler was built on YYYY-MM-DD; consider upgrading it if it is out of date +warning: lint `fuzzy_provenance_casts` has been renamed to `implicit_provenance_casts` + --> $DIR/feature-gate-strict_provenance_lints.rs:7:9 + | +LL | #![deny(fuzzy_provenance_casts)] + | ^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `implicit_provenance_casts` + | + = note: `#[warn(renamed_and_removed_lints)]` on by default + +warning: lint `lossy_provenance_casts` has been renamed to `implicit_provenance_casts` + --> $DIR/feature-gate-strict_provenance_lints.rs:10:9 + | +LL | #![deny(lossy_provenance_casts)] + | ^^^^^^^^^^^^^^^^^^^^^^ help: use the new name: `implicit_provenance_casts` + warning: 5 warnings emitted diff --git a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr index f685a989c0aa6..9b091ff4fbf91 100644 --- a/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr +++ b/tests/ui/feature-gates/issue-43106-gating-of-builtin-attrs.stderr @@ -12,6 +12,27 @@ warning: `#[macro_escape]` is a deprecated synonym for `#[macro_use]` LL | #[macro_escape] | ^^^^^^^^^^^^^^^ +warning: the feature `rust1` has been stable since 1.0.0 and no longer requires an attribute to enable + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:101:12 + | +LL | #![feature(rust1)] + | ^^^^^ + | + = note: `#[warn(stable_features)]` on by default + +warning: unused attribute + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:257:9 + | +LL | #![path="3800"] + | ^^^^^^^^^^^^^^^ help: remove this attribute + | + = note: `#[path]` is unused on this inline module +note: the lint level is defined here + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:35:9 + | +LL | #![warn(unused_attributes, unknown_lints)] + | ^^^^^^^^^^^^^^^^^ + warning: unknown lint: `x5400` --> $DIR/issue-43106-gating-of-builtin-attrs.rs:41:9 | @@ -42,6 +63,87 @@ warning: unknown lint: `x5100` LL | #![deny(x5100)] | ^^^^^ +warning: the `macro_use` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:45:4 + | +LL | #![macro_use] + | ^^^^^^^^^ + | + = help: the `macro_use` attribute can be applied to extern crates and modules + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `should_panic` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:51:4 + | +LL | #![should_panic] + | ^^^^^^^^^^^^ + | + = help: the `should_panic` attribute can only be applied to functions + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `ignore` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:55:4 + | +LL | #![ignore] + | ^^^^^^ + | + = help: the `ignore` attribute can only be applied to functions + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `proc_macro_derive` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:63:4 + | +LL | #![proc_macro_derive(Test)] + | ^^^^^^^^^^^^^^^^^ + | + = help: the `proc_macro_derive` attribute can only be applied to functions + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `cold` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:68:4 + | +LL | #![cold] + | ^^^^ + | + = help: the `cold` attribute can only be applied to functions + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `link` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:72:4 + | +LL | #![link(name = "x")] + | ^^^^ + | + = help: the `link` attribute can only be applied to foreign modules + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `link_name` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:76:4 + | +LL | #![link_name = "1900"] + | ^^^^^^^^^ + | + = help: the `link_name` attribute can be applied to foreign functions and foreign statics + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `link_section` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:81:4 + | +LL | #![link_section = ",1800"] + | ^^^^^^^^^^^^ + | + = help: the `link_section` attribute can be applied to functions and statics + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + +warning: the `must_use` attribute cannot be used on crates + --> $DIR/issue-43106-gating-of-builtin-attrs.rs:86:4 + | +LL | #![must_use] + | ^^^^^^^^ + | + = help: the `must_use` attribute can be applied to data types, functions, and traits + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + warning: unknown lint: `x5400` --> $DIR/issue-43106-gating-of-builtin-attrs.rs:112:8 | @@ -186,108 +288,6 @@ warning: unknown lint: `x5100` LL | #[deny(x5100)] impl S { } | ^^^^^ -warning: the feature `rust1` has been stable since 1.0.0 and no longer requires an attribute to enable - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:101:12 - | -LL | #![feature(rust1)] - | ^^^^^ - | - = note: `#[warn(stable_features)]` on by default - -warning: unused attribute - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:257:9 - | -LL | #![path="3800"] - | ^^^^^^^^^^^^^^^ help: remove this attribute - | - = note: `#[path]` is unused on this inline module -note: the lint level is defined here - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:35:9 - | -LL | #![warn(unused_attributes, unknown_lints)] - | ^^^^^^^^^^^^^^^^^ - -warning: the `macro_use` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:45:4 - | -LL | #![macro_use] - | ^^^^^^^^^ - | - = help: the `macro_use` attribute can be applied to extern crates and modules - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `should_panic` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:51:4 - | -LL | #![should_panic] - | ^^^^^^^^^^^^ - | - = help: the `should_panic` attribute can only be applied to functions - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `ignore` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:55:4 - | -LL | #![ignore] - | ^^^^^^ - | - = help: the `ignore` attribute can only be applied to functions - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `proc_macro_derive` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:63:4 - | -LL | #![proc_macro_derive(Test)] - | ^^^^^^^^^^^^^^^^^ - | - = help: the `proc_macro_derive` attribute can only be applied to functions - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `cold` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:68:4 - | -LL | #![cold] - | ^^^^ - | - = help: the `cold` attribute can only be applied to functions - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `link` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:72:4 - | -LL | #![link(name = "x")] - | ^^^^ - | - = help: the `link` attribute can only be applied to foreign modules - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `link_name` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:76:4 - | -LL | #![link_name = "1900"] - | ^^^^^^^^^ - | - = help: the `link_name` attribute can be applied to foreign functions and foreign statics - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `link_section` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:81:4 - | -LL | #![link_section = ",1800"] - | ^^^^^^^^^^^^ - | - = help: the `link_section` attribute can be applied to functions and statics - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - -warning: the `must_use` attribute cannot be used on crates - --> $DIR/issue-43106-gating-of-builtin-attrs.rs:86:4 - | -LL | #![must_use] - | ^^^^^^^^ - | - = help: the `must_use` attribute can be applied to data types, functions, and traits - = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! - warning: the `macro_use` attribute cannot be used on functions --> $DIR/issue-43106-gating-of-builtin-attrs.rs:192:7 | diff --git a/tests/ui/lint/register-tool-lint.rs b/tests/ui/lint/register-tool-lint.rs index 17d3afbf6e26e..f56d9a0a8c362 100644 --- a/tests/ui/lint/register-tool-lint.rs +++ b/tests/ui/lint/register-tool-lint.rs @@ -5,5 +5,3 @@ #![warn(abc::my_lint)] //~^ ERROR unknown tool name `abc` found in scoped lint //~| HELP add `#![register_tool(abc)]` -//~| ERROR unknown tool name `abc` -//~| HELP add `#![register_tool(abc)]` diff --git a/tests/ui/lint/register-tool-lint.stderr b/tests/ui/lint/register-tool-lint.stderr index 7ebdbdec92972..98b4af935d340 100644 --- a/tests/ui/lint/register-tool-lint.stderr +++ b/tests/ui/lint/register-tool-lint.stderr @@ -6,15 +6,6 @@ LL | #![warn(abc::my_lint)] | = help: add `#![register_tool(abc)]` to the crate root -error[E0710]: unknown tool name `abc` found in scoped lint: `abc::my_lint` - --> $DIR/register-tool-lint.rs:5:9 - | -LL | #![warn(abc::my_lint)] - | ^^^ - | - = help: add `#![register_tool(abc)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 2 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0710`. diff --git a/tests/ui/lint/renamed-lints-still-apply.stderr b/tests/ui/lint/renamed-lints-still-apply.stderr index 9eaf711293388..5e4dae1e21be7 100644 --- a/tests/ui/lint/renamed-lints-still-apply.stderr +++ b/tests/ui/lint/renamed-lints-still-apply.stderr @@ -1,11 +1,3 @@ -warning: lint `single_use_lifetime` has been renamed to `single_use_lifetimes` - --> $DIR/renamed-lints-still-apply.rs:2:9 - | -LL | #![deny(single_use_lifetime)] - | ^^^^^^^^^^^^^^^^^^^ help: use the new name: `single_use_lifetimes` - | - = note: `#[warn(renamed_and_removed_lints)]` on by default - error: lifetime parameter `'a` only used once --> $DIR/renamed-lints-still-apply.rs:6:9 | @@ -25,5 +17,13 @@ LL - fn _foo<'a>(_x: &'a u32) {} LL + fn _foo(_x: &u32) {} | +warning: lint `single_use_lifetime` has been renamed to `single_use_lifetimes` + --> $DIR/renamed-lints-still-apply.rs:2:9 + | +LL | #![deny(single_use_lifetime)] + | ^^^^^^^^^^^^^^^^^^^ help: use the new name: `single_use_lifetimes` + | + = note: `#[warn(renamed_and_removed_lints)]` on by default + error: aborting due to 1 previous error; 1 warning emitted diff --git a/tests/ui/tool-attributes/cross-crate.rs b/tests/ui/tool-attributes/cross-crate.rs index 1992174aca3e1..11c594de02aa3 100644 --- a/tests/ui/tool-attributes/cross-crate.rs +++ b/tests/ui/tool-attributes/cross-crate.rs @@ -5,6 +5,4 @@ extern crate use_tool; #[foo::bar] //~ ERROR cannot find module or crate `foo` in this scope #[allow(foo::baz)] //~ ERROR unknown tool name `foo` - //~| ERROR unknown tool name `foo` - //~| ERROR unknown tool name `foo` fn main() {} diff --git a/tests/ui/tool-attributes/cross-crate.stderr b/tests/ui/tool-attributes/cross-crate.stderr index 051a1b05405e9..6b669601f24f2 100644 --- a/tests/ui/tool-attributes/cross-crate.stderr +++ b/tests/ui/tool-attributes/cross-crate.stderr @@ -1,11 +1,3 @@ -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::baz` - --> $DIR/cross-crate.rs:7:9 - | -LL | #[allow(foo::baz)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - error[E0433]: cannot find module or crate `foo` in this scope --> $DIR/cross-crate.rs:6:3 | @@ -19,18 +11,8 @@ LL | #[allow(foo::baz)] | ^^^ | = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::baz` - --> $DIR/cross-crate.rs:7:9 - | -LL | #[allow(foo::baz)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` -error: aborting due to 4 previous errors +error: aborting due to 2 previous errors Some errors have detailed explanations: E0433, E0710. For more information about an error, try `rustc --explain E0433`. diff --git a/tests/ui/tool-attributes/tool_lints.rs b/tests/ui/tool-attributes/tool_lints.rs index 9e4aa7a939acb..0a9be75681ca5 100644 --- a/tests/ui/tool-attributes/tool_lints.rs +++ b/tests/ui/tool-attributes/tool_lints.rs @@ -1,5 +1,3 @@ #[warn(foo::bar)] //~^ ERROR unknown tool name `foo` found in scoped lint: `foo::bar` -//~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` -//~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` fn main() {} diff --git a/tests/ui/tool-attributes/tool_lints.stderr b/tests/ui/tool-attributes/tool_lints.stderr index eee0a9784ece8..a0c5316d95b07 100644 --- a/tests/ui/tool-attributes/tool_lints.stderr +++ b/tests/ui/tool-attributes/tool_lints.stderr @@ -6,24 +6,6 @@ LL | #[warn(foo::bar)] | = help: add `#![register_tool(foo)]` to the crate root -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/tool_lints.rs:1:8 - | -LL | #[warn(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/tool_lints.rs:1:8 - | -LL | #[warn(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 3 previous errors +error: aborting due to 1 previous error For more information about this error, try `rustc --explain E0710`. diff --git a/tests/ui/tool-attributes/unknown-lint-tool-name.rs b/tests/ui/tool-attributes/unknown-lint-tool-name.rs index 84ab7c1944ab2..cf26341d8b588 100644 --- a/tests/ui/tool-attributes/unknown-lint-tool-name.rs +++ b/tests/ui/tool-attributes/unknown-lint-tool-name.rs @@ -1,8 +1,4 @@ #![deny(foo::bar)] //~ ERROR unknown tool name `foo` found in scoped lint: `foo::bar` - //~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` - //~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` #[allow(foo::bar)] //~ ERROR unknown tool name `foo` found in scoped lint: `foo::bar` - //~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` - //~| ERROR unknown tool name `foo` found in scoped lint: `foo::bar` fn main() {} diff --git a/tests/ui/tool-attributes/unknown-lint-tool-name.stderr b/tests/ui/tool-attributes/unknown-lint-tool-name.stderr index 91baf88273756..8ef80efdbcf51 100644 --- a/tests/ui/tool-attributes/unknown-lint-tool-name.stderr +++ b/tests/ui/tool-attributes/unknown-lint-tool-name.stderr @@ -7,49 +7,13 @@ LL | #![deny(foo::bar)] = help: add `#![register_tool(foo)]` to the crate root error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:5:9 + --> $DIR/unknown-lint-tool-name.rs:3:9 | LL | #[allow(foo::bar)] | ^^^ | = help: add `#![register_tool(foo)]` to the crate root -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:1:9 - | -LL | #![deny(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:5:9 - | -LL | #[allow(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:1:9 - | -LL | #![deny(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error[E0710]: unknown tool name `foo` found in scoped lint: `foo::bar` - --> $DIR/unknown-lint-tool-name.rs:5:9 - | -LL | #[allow(foo::bar)] - | ^^^ - | - = help: add `#![register_tool(foo)]` to the crate root - = note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no` - -error: aborting due to 6 previous errors +error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0710`. diff --git a/tests/ui/unpretty/exhaustive.hir.stdout b/tests/ui/unpretty/exhaustive.hir.stdout index 4726e9aa762e7..f9816034b065b 100644 --- a/tests/ui/unpretty/exhaustive.hir.stdout +++ b/tests/ui/unpretty/exhaustive.hir.stdout @@ -3,9 +3,9 @@ coroutines#0, decl_macro#0, deref_patterns#0, explicit_tail_calls#0, forced_keywords#0, gen_blocks#0, more_qualified_paths#0, never_patterns#0, pattern_types#0, prelude_import#0, specialization#0, trace_macros#0, trait_alias#0, try_blocks#0, try_blocks_heterogeneous#0, yeet_expr#0])] -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "incomplete_features" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "incomplete_features" }, kind: Allow}, -LintCheck {lint_name: LintName { tool: None, name: "unused_attributes" }, +LintCheck {lint_name_normalized: LintName { tool: None, name: "unused_attributes" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] @@ -41,9 +41,9 @@ use self::prelude::*; * inner multi-line doc comment */ #[doc = "inner doc attribute"] -#[attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "dead_code" }, +#[attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, kind: Allow}, -LintCheck {lint_name: LintName { tool: None, name: "unused_variables" }, +LintCheck {lint_name_normalized: LintName { tool: None, name: "unused_variables" }, kind: Allow}])] #[attr = NoStd] mod attributes { diff --git a/tests/ui/unpretty/struct-exprs-tuple-call-pretty-printing.stdout b/tests/ui/unpretty/struct-exprs-tuple-call-pretty-printing.stdout index d94a76fb882e1..aa1567fdb0d1c 100644 --- a/tests/ui/unpretty/struct-exprs-tuple-call-pretty-printing.stdout +++ b/tests/ui/unpretty/struct-exprs-tuple-call-pretty-printing.stdout @@ -1,6 +1,6 @@ #![attr = Feature([adt_const_params#0, gca_adts#0, gca_min_const_items#0, gca_macroless_args#0])] -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "dead_code" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] diff --git a/tests/ui/unpretty/unpretty-expr-fn-arg.stdout b/tests/ui/unpretty/unpretty-expr-fn-arg.stdout index d80b073e52b73..93938fed46d47 100644 --- a/tests/ui/unpretty/unpretty-expr-fn-arg.stdout +++ b/tests/ui/unpretty/unpretty-expr-fn-arg.stdout @@ -1,4 +1,4 @@ -#![attr = LintCheck([LintCheck {lint_name: LintName { tool: None, name: "dead_code" }, +#![attr = LintCheck([LintCheck {lint_name_normalized: LintName { tool: None, name: "dead_code" }, kind: Allow}])] extern crate std; #[attr = PreludeImport] From b3908c351b77689225589c96209286a1517415d0 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sun, 1 Nov 2026 12:13:13 +0100 Subject: [PATCH 46/51] Remove span of `tool` --- compiler/rustc_attr_ir/src/lint.rs | 1 - compiler/rustc_attr_parsing/src/attributes/lint.rs | 3 +-- compiler/rustc_lint/src/levels.rs | 1 - 3 files changed, 1 insertion(+), 4 deletions(-) diff --git a/compiler/rustc_attr_ir/src/lint.rs b/compiler/rustc_attr_ir/src/lint.rs index 163de374d96fb..29d99347d8dcf 100644 --- a/compiler/rustc_attr_ir/src/lint.rs +++ b/compiler/rustc_attr_ir/src/lint.rs @@ -66,5 +66,4 @@ pub struct LintCheck { /// #[deny(foo::bar::baz)] /// ^^^^^^^^^^^^^ pub lint_span: Span, - pub tool_span: Option, } diff --git a/compiler/rustc_attr_parsing/src/attributes/lint.rs b/compiler/rustc_attr_parsing/src/attributes/lint.rs index 53ebc9953e03c..c552ea77922f2 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint.rs @@ -81,7 +81,7 @@ impl LintParser { LintName { tool: tool.map(|tool| tool.name), name: lint_name }; let lint_name_normalized = if let Some((_lint_ids, new_lint_name)) = - Self::check_lint_name( + LintParser::check_lint_name( lint_name, tool.map(|tool| tool.span), p.span(), @@ -100,7 +100,6 @@ impl LintParser { attr_id, reason, attr_span, - tool_span: tool.map(|tool| tool.span), }) } // We've found a `reason = "reason"` but we're not the last element. diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 171c36c0455e3..02bd955fc5a0d 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -739,7 +739,6 @@ where reason, attr_id, attr_span: _, - tool_span: _, } = lint_check; let level = match kind { From 9ddf128ef1e38f73797dc7d226784e4d9e56c7b1 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Fri, 30 Oct 2026 11:37:48 +0100 Subject: [PATCH 47/51] Review --- compiler/rustc_attr_ir/src/lint.rs | 2 +- .../rustc_attr_parsing/src/attributes/lint.rs | 28 +++++++------ compiler/rustc_lint/src/context.rs | 6 +-- compiler/rustc_lint/src/levels.rs | 11 +---- compiler/rustc_session/src/session.rs | 4 +- tests/pretty/lint-attrs-filtered-out.rs | 7 ++++ tests/ui/lint/lint-check-on-macro.rs | 15 +++++++ tests/ui/lint/lint-check-on-macro.stderr | 42 +++++++++++++++++++ 8 files changed, 87 insertions(+), 28 deletions(-) create mode 100644 tests/pretty/lint-attrs-filtered-out.rs create mode 100644 tests/ui/lint/lint-check-on-macro.rs create mode 100644 tests/ui/lint/lint-check-on-macro.stderr diff --git a/compiler/rustc_attr_ir/src/lint.rs b/compiler/rustc_attr_ir/src/lint.rs index 29d99347d8dcf..41d89154c72ea 100644 --- a/compiler/rustc_attr_ir/src/lint.rs +++ b/compiler/rustc_attr_ir/src/lint.rs @@ -46,7 +46,7 @@ impl LintCheckKind { #[derive(Clone, Debug, StableHash, Encodable, Decodable, PrintAttribute)] pub struct LintCheck { /// The full normalized lint name of an existing lint, including the tool name. - /// This may not be what we user wrote down, in case of renamed lints the new lint name is here. + /// This may not be what the user wrote down, in case of renamed lints the new lint name is here. /// The above implies that `LintStore::find_lints` is guaranteed to find this lint using this symbol. /// /// For example, `single_use_lifetime` is changed to `single_use_lifetimes`. diff --git a/compiler/rustc_attr_parsing/src/attributes/lint.rs b/compiler/rustc_attr_parsing/src/attributes/lint.rs index c552ea77922f2..51a3e02c7f779 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint.rs @@ -4,7 +4,7 @@ use rustc_attr_ir::lint::{LintCheck, LintCheckKind}; use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target}; use rustc_lint_defs::builtin::{RENAMED_AND_REMOVED_LINTS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES}; use rustc_lint_defs::{CheckLintNameResult, LintId}; -use rustc_span::{DUMMY_SP, Span, Symbol, sym}; +use rustc_span::{Span, Symbol, sym}; use rustc_structures::LintName; use thin_vec::ThinVec; @@ -159,21 +159,25 @@ impl LintParser { } } - fn check_lint_name<'a>( + fn check_lint_name<'sess>( lint_name: LintName, tool_span: Option, lint_span: Span, - cx: &mut AcceptContext<'_, 'a>, - ) -> Option<(&'a [LintId], LintName)> { - let lint_result = - cx.sess.lint_store.as_ref().unwrap().check_lint_name(lint_name, cx.lint_tools.unwrap()); + cx: &mut AcceptContext<'_, 'sess>, + ) -> Option<(&'sess [LintId], LintName)> { + let lint_result = cx + .sess + .lint_store + .as_ref() + .unwrap() + .check_attribute_lint_name(lint_name, cx.lint_tools.unwrap()); // FIXME(164898) Lint attributes are parsed twice, once on the AST and once on the HIR // Both times emit diagnostics, for historic reasons // We only want to emit these lints once, on the HIR. - // On the AST `target_span` will be `DUMMY_SP`, which we use to detect which instance we are. + // On the AST the parse filter will be `Some` (since we're only parsing lint attributes then) // #164898 will fix this, after that PR this check can be removed - let should_lint = cx.target_span != DUMMY_SP; + let should_lint = cx.parse_filter.is_none(); let (ids, name) = match lint_result { CheckLintNameResult::Ok(ids) => (ids, lint_name), @@ -233,14 +237,12 @@ impl LintParser { // If this lint was renamed, apply the new lint instead of ignoring the // attribute. Ignore any errors or warnings that happen because the new // name is inaccurate. - // NOTE: `new_name` already includes the tool name, so we don't - // have to add it again. let replace_check = cx .sess .lint_store .as_ref() .unwrap() - .check_lint_name(replacement, cx.lint_tools.unwrap()); + .check_attribute_lint_name(replacement, cx.lint_tools.unwrap()); let (CheckLintNameResult::Ok(ids) | CheckLintNameResult::Tool(ids, _)) = replace_check else { @@ -252,11 +254,11 @@ impl LintParser { (ids, replacement) } - CheckLintNameResult::Removed(ref reason) => { + CheckLintNameResult::Removed(reason) => { if should_lint { cx.emit_lint( RENAMED_AND_REMOVED_LINTS, - RemovedLint { name: lint_name, reason: reason.clone() }, + RemovedLint { name: lint_name, reason }, lint_span, ); } diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 44aa75e5d7d7b..d5fc3bc415452 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -91,12 +91,12 @@ impl DynLintStore for LintStore { })) } - fn check_lint_name( + fn check_attribute_lint_name( &self, lint_name: LintName, - registered_tools: &RegisteredTools, + lint_tools: &RegisteredTools, ) -> CheckLintNameResult<'_> { - self.check_lint_name(lint_name, registered_tools) + self.check_lint_name(lint_name, lint_tools) } } diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 02bd955fc5a0d..98804e82740be 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -730,16 +730,9 @@ where return; }; - // FIXME: consider performing these checks in attribute parsing instead for (lint_index, lint_check) in lint_checks.into_iter().enumerate() { - let LintCheck { - lint_name_normalized, - lint_span, - kind, - reason, - attr_id, - attr_span: _, - } = lint_check; + let LintCheck { lint_name_normalized, lint_span, kind, reason, attr_id, attr_span: _ } = + lint_check; let level = match kind { LintCheckKind::Allow => Level::Allow, diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index a64ebd5d27c7d..182ff93e6f78a 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -85,10 +85,10 @@ pub trait DynLintStore: Any + DynSync + DynSend { /// Provides a way to access lint groups without depending on `rustc_lint` fn lint_groups_iter(&self) -> Box + '_>; - fn check_lint_name( + fn check_attribute_lint_name( &self, lint_name: LintName, - registered_tools: &RegisteredTools, + lint_tools: &RegisteredTools, ) -> CheckLintNameResult<'_>; } diff --git a/tests/pretty/lint-attrs-filtered-out.rs b/tests/pretty/lint-attrs-filtered-out.rs new file mode 100644 index 0000000000000..9dc4898f3ff41 --- /dev/null +++ b/tests/pretty/lint-attrs-filtered-out.rs @@ -0,0 +1,7 @@ +//@ pretty-compare-only +//@ pretty-mode:hir +//@ pp-exact:lint-attrs-filtered-out.pp + +// `does_not_exist` is filtered out on the hir +#[deny(dead_code, does_not_exist)] +fn main() {} diff --git a/tests/ui/lint/lint-check-on-macro.rs b/tests/ui/lint/lint-check-on-macro.rs new file mode 100644 index 0000000000000..047b024dbab20 --- /dev/null +++ b/tests/ui/lint/lint-check-on-macro.rs @@ -0,0 +1,15 @@ +macro_rules! identity { ($( $tt:tt )*) => { $( $tt )* } } + +fn main() { + #[expect(wat::doesnt_exist)] + //~^ WARN cannot be used on + //~| ERROR unknown tool name + println!(); + + identity!{ + #[expect(wat::doesnt_exist)] + //~^ WARN cannot be used on + //~| ERROR unknown tool name + println!(); + } +} diff --git a/tests/ui/lint/lint-check-on-macro.stderr b/tests/ui/lint/lint-check-on-macro.stderr new file mode 100644 index 0000000000000..0dac7bed002da --- /dev/null +++ b/tests/ui/lint/lint-check-on-macro.stderr @@ -0,0 +1,42 @@ +error[E0710]: unknown tool name `wat` found in scoped lint: `wat::doesnt_exist` + --> $DIR/lint-check-on-macro.rs:4:14 + | +LL | #[expect(wat::doesnt_exist)] + | ^^^ + | + = help: add `#![register_tool(wat)]` to the crate root + +error[E0710]: unknown tool name `wat` found in scoped lint: `wat::doesnt_exist` + --> $DIR/lint-check-on-macro.rs:10:18 + | +LL | #[expect(wat::doesnt_exist)] + | ^^^ + | + = help: add `#![register_tool(wat)]` to the crate root + +warning: the `expect` attribute cannot be used on macro calls + --> $DIR/lint-check-on-macro.rs:4:7 + | +LL | #[expect(wat::doesnt_exist)] + | ^^^^^^ +... +LL | println!(); + | + = help: the `expect` attribute can be applied to associated consts, associated types, break expressions, const parameters, constants, crates, data types, enum variants, extern crates, for loops, foreign modules, foreign statics, function params, functions, global asms, impl blocks, lifetime parameters, loops, macro defs, match arms, modules, pattern fields, statics, struct fields, trait aliases, traits, type aliases, type parameters, use statements, and while loops + = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion + = note: requested on the command line with `-W unused-attributes` + +warning: the `expect` attribute cannot be used on macro calls + --> $DIR/lint-check-on-macro.rs:10:11 + | +LL | #[expect(wat::doesnt_exist)] + | ^^^^^^ +... +LL | println!(); + | + = help: the `expect` attribute can be applied to associated consts, associated types, break expressions, const parameters, constants, crates, data types, enum variants, extern crates, for loops, foreign modules, foreign statics, function params, functions, global asms, impl blocks, lifetime parameters, loops, macro defs, match arms, modules, pattern fields, statics, struct fields, trait aliases, traits, type aliases, type parameters, use statements, and while loops + = note: attributes on a macro invocation apply to the invocation itself and are not forwarded to its expansion + +error: aborting due to 2 previous errors; 2 warnings emitted + +For more information about this error, try `rustc --explain E0710`. From 42a2311bc1fe09424313a64c7779fbc9a37de1d2 Mon Sep 17 00:00:00 2001 From: Jonathan Brouwer Date: Sun, 1 Nov 2026 12:44:38 +0100 Subject: [PATCH 48/51] Move `LintName` to `rustc_lint_defs` --- Cargo.lock | 1 - compiler/rustc_attr_ir/src/lint.rs | 2 +- compiler/rustc_attr_ir/src/pretty_printing.rs | 6 ++---- compiler/rustc_attr_parsing/src/attributes/lint.rs | 3 +-- compiler/rustc_attr_parsing/src/diagnostics.rs | 2 +- compiler/rustc_driver_impl/src/lib.rs | 4 ++-- compiler/rustc_lint/src/context.rs | 3 +-- compiler/rustc_lint/src/diagnostics.rs | 2 +- compiler/rustc_lint/src/levels.rs | 3 +-- compiler/rustc_lint/src/tests.rs | 2 +- compiler/rustc_lint_defs/Cargo.toml | 1 - compiler/rustc_lint_defs/src/lib.rs | 3 ++- .../src/lint.rs => rustc_lint_defs/src/lint_name.rs} | 4 +--- compiler/rustc_middle/src/lint.rs | 3 +-- compiler/rustc_session/src/session.rs | 4 ++-- compiler/rustc_structures/src/lib.rs | 2 -- src/tools/clippy/clippy_lints/src/collapsible_if.rs | 2 +- src/tools/clippy/clippy_lints/src/lib.rs | 1 + .../clippy/clippy_lints/src/returns/needless_return.rs | 2 +- 19 files changed, 20 insertions(+), 30 deletions(-) rename compiler/{rustc_structures/src/lint.rs => rustc_lint_defs/src/lint_name.rs} (95%) diff --git a/Cargo.lock b/Cargo.lock index a8d4849f20267..bae8add757e7f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4347,7 +4347,6 @@ dependencies = [ "rustc_macros", "rustc_serialize", "rustc_span", - "rustc_structures", "serde", ] diff --git a/compiler/rustc_attr_ir/src/lint.rs b/compiler/rustc_attr_ir/src/lint.rs index 41d89154c72ea..7ce2c000419e1 100644 --- a/compiler/rustc_attr_ir/src/lint.rs +++ b/compiler/rustc_attr_ir/src/lint.rs @@ -1,6 +1,6 @@ +use rustc_lint_defs::LintName; use rustc_macros::{Decodable, Encodable, PrintAttribute, StableHash}; use rustc_span::{Span, Symbol, sym}; -use rustc_structures::LintName; use crate::{HashIgnoredAttrId, PrintAttribute}; diff --git a/compiler/rustc_attr_ir/src/pretty_printing.rs b/compiler/rustc_attr_ir/src/pretty_printing.rs index 04e5b94921860..61c2cb838bf27 100644 --- a/compiler/rustc_attr_ir/src/pretty_printing.rs +++ b/compiler/rustc_attr_ir/src/pretty_printing.rs @@ -11,13 +11,11 @@ use rustc_ast::token::{CommentKind, DocFragmentKind}; use rustc_ast::{AttrId, AttrStyle, IntTy, UintTy}; use rustc_ast_pretty::pp::Printer; use rustc_data_structures::fx::FxIndexMap; -use rustc_lint_defs::{Reflectiveness, ToolOptions}; +use rustc_lint_defs::{LintName, Reflectiveness, ToolOptions}; use rustc_span::def_id::DefId; use rustc_span::hygiene::Transparency; use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol}; -use rustc_structures::{ - CollapseMacroDebuginfo, CrateType, Limit, LintName, NativeLibKind, SanitizerSet, -}; +use rustc_structures::{CollapseMacroDebuginfo, CrateType, Limit, NativeLibKind, SanitizerSet}; use thin_vec::ThinVec; use crate::HashIgnoredAttrId; diff --git a/compiler/rustc_attr_parsing/src/attributes/lint.rs b/compiler/rustc_attr_parsing/src/attributes/lint.rs index 51a3e02c7f779..9eb38282c5582 100644 --- a/compiler/rustc_attr_parsing/src/attributes/lint.rs +++ b/compiler/rustc_attr_parsing/src/attributes/lint.rs @@ -3,9 +3,8 @@ use rustc_attr_ir::AttributeKind; use rustc_attr_ir::lint::{LintCheck, LintCheckKind}; use rustc_attr_ir::target::{AssocCtxt, MethodKind, Target}; use rustc_lint_defs::builtin::{RENAMED_AND_REMOVED_LINTS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES}; -use rustc_lint_defs::{CheckLintNameResult, LintId}; +use rustc_lint_defs::{CheckLintNameResult, LintId, LintName}; use rustc_span::{Span, Symbol, sym}; -use rustc_structures::LintName; use thin_vec::ThinVec; use crate::attributes::{AcceptMapping, AttributeParser, AttributeStability}; diff --git a/compiler/rustc_attr_parsing/src/diagnostics.rs b/compiler/rustc_attr_parsing/src/diagnostics.rs index 7d0aa9669516f..5dd00257495e6 100644 --- a/compiler/rustc_attr_parsing/src/diagnostics.rs +++ b/compiler/rustc_attr_parsing/src/diagnostics.rs @@ -5,9 +5,9 @@ use rustc_errors::codes::*; use rustc_errors::{ Applicability, Diag, DiagArgValue, DiagCtxtHandle, Diagnostic, E0264, Level, MultiSpan, }; +use rustc_lint_defs::LintName; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_span::{Ident, Span, Symbol}; -use rustc_structures::LintName; use rustc_target::spec::TargetTuple; use crate::AttributeTemplate; diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 93f84d6cf9635..2cc3466b260d1 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -44,7 +44,7 @@ use rustc_interface::passes::collect_crate_types; use rustc_interface::util::{self, get_codegen_backend}; use rustc_interface::{Linker, create_and_enter_global_ctxt, interface, passes}; use rustc_lint::unerased_lint_store; -use rustc_lint_defs::{Lint, LintId}; +use rustc_lint_defs::{Lint, LintId, LintName}; use rustc_metadata::creader::MetadataLoader; use rustc_metadata::locator; use rustc_middle::ty::TyCtxt; @@ -59,7 +59,7 @@ use rustc_session::output::invalid_output_for_target; use rustc_session::{EarlyDiagCtxt, Session, config}; use rustc_span::def_id::LOCAL_CRATE; use rustc_span::{DUMMY_SP, FileName}; -use rustc_structures::{CrateType, LintName}; +use rustc_structures::CrateType; use rustc_target::json::ToJson; use rustc_target::spec::{Target, TargetTuple}; use tracing::trace; diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index d5fc3bc415452..dc676b16d0745 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -19,7 +19,7 @@ use rustc_hir::def_id::{CrateNum, DefId}; use rustc_hir::definitions::{DefPathData, DisambiguatedDefPathData}; use rustc_hir::{Pat, PatKind}; use rustc_lint_defs::{ - CheckLintNameResult, FutureIncompatibleInfo, Lint, LintExpectationId, LintId, + CheckLintNameResult, FutureIncompatibleInfo, Lint, LintExpectationId, LintId, LintName, StableLintExpectationId, UnstableLintExpectationId, }; use rustc_middle::lint::{LevelSpec, StableLevelSpec, UnstableLevelSpec}; @@ -30,7 +30,6 @@ use rustc_middle::ty::{self, RegisteredTools, Ty, TyCtxt, TypingEnv, TypingMode, use rustc_session::{DynLintStore, Session}; use rustc_span::edit_distance::find_best_match_for_names; use rustc_span::{Ident, Span, Symbol, bug, sym}; -use rustc_structures::LintName; use tracing::debug; use self::TargetLint::*; diff --git a/compiler/rustc_lint/src/diagnostics.rs b/compiler/rustc_lint/src/diagnostics.rs index 15d957173589d..cf52203d6f769 100644 --- a/compiler/rustc_lint/src/diagnostics.rs +++ b/compiler/rustc_lint/src/diagnostics.rs @@ -13,13 +13,13 @@ use rustc_errors::{ use rustc_hir as hir; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::intravisit::Visitor; +use rustc_lint_defs::LintName; use rustc_macros::{Diagnostic, Subdiagnostic}; use rustc_middle::ty::inhabitedness::InhabitedPredicate; use rustc_middle::ty::{Clause, PolyExistentialTraitRef, Ty, TyCtxt}; use rustc_session::Session; use rustc_span::edition::Edition; use rustc_span::{Ident, Span, Symbol, sym}; -use rustc_structures::LintName; use crate::LateContext; use crate::builtin::{InitError, ShorthandAssocTyCollector, TypeAliasBounds}; diff --git a/compiler/rustc_lint/src/levels.rs b/compiler/rustc_lint/src/levels.rs index 98804e82740be..1335c2156134f 100644 --- a/compiler/rustc_lint/src/levels.rs +++ b/compiler/rustc_lint/src/levels.rs @@ -21,7 +21,7 @@ use rustc_lint_defs::builtin::{ UNFULFILLED_LINT_EXPECTATIONS, UNKNOWN_LINTS, UNUSED_ATTRIBUTES, }; use rustc_lint_defs::{ - CheckLintNameResult, Level, Lint, LintExpectationId, LintId, StableLintExpectationId, + CheckLintNameResult, Level, Lint, LintExpectationId, LintId, LintName, StableLintExpectationId, UnstableLintExpectationId, }; use rustc_middle::hir::nested_filter; @@ -34,7 +34,6 @@ use rustc_middle::ty::{RegisteredTools, TyCtxt}; use rustc_session::Session; use rustc_span::def_id::CRATE_MOD_ID; use rustc_span::{AttrId, DUMMY_SP, Span, Symbol, sym}; -use rustc_structures::LintName; use tracing::{debug, instrument}; use crate::builtin::MISSING_DOCS; diff --git a/compiler/rustc_lint/src/tests.rs b/compiler/rustc_lint/src/tests.rs index b4f789564600d..78e94e0352624 100644 --- a/compiler/rustc_lint/src/tests.rs +++ b/compiler/rustc_lint/src/tests.rs @@ -1,7 +1,7 @@ #![allow(rustc::symbol_intern_string_literal)] +use rustc_lint_defs::LintName; use rustc_span::{Symbol, create_default_session_globals_then, sym}; -use rustc_structures::LintName; use crate::builtin::is_hexagon_register_span; diff --git a/compiler/rustc_lint_defs/Cargo.toml b/compiler/rustc_lint_defs/Cargo.toml index 71c9bf153c3cc..c8201d5ea8ccc 100644 --- a/compiler/rustc_lint_defs/Cargo.toml +++ b/compiler/rustc_lint_defs/Cargo.toml @@ -8,7 +8,6 @@ edition = "2024" rustc_ast = { path = "../rustc_ast" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_error_messages = { path = "../rustc_error_messages" } -rustc_structures = { path = "../rustc_structures" } rustc_hir_id = { path = "../rustc_hir_id" } rustc_macros = { path = "../rustc_macros" } rustc_serialize = { path = "../rustc_serialize" } diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 8f3e51d80ed6c..e3366c518c7e3 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -7,6 +7,7 @@ use std::borrow::Cow; use std::fmt::Display; +pub use lint_name::LintName; use rustc_ast::attr::version::RustcVersion; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::stable_hash::{StableCompare, StableHash, StableHashCtxt, StableHasher}; @@ -15,13 +16,13 @@ use rustc_hir_id::HirId; use rustc_macros::{Decodable, Encodable, StableHash}; use rustc_span::edition::Edition; use rustc_span::{AttrId, Ident, Symbol, sym}; -use rustc_structures::LintName; use serde::{Deserialize, Serialize}; pub use self::Level::*; use crate::Reflectiveness::{NonReflective, Reflective}; pub mod builtin; +mod lint_name; #[macro_export] macro_rules! pluralize { diff --git a/compiler/rustc_structures/src/lint.rs b/compiler/rustc_lint_defs/src/lint_name.rs similarity index 95% rename from compiler/rustc_structures/src/lint.rs rename to compiler/rustc_lint_defs/src/lint_name.rs index b76390c47ac4f..329ec6c62a1f4 100644 --- a/compiler/rustc_structures/src/lint.rs +++ b/compiler/rustc_lint_defs/src/lint_name.rs @@ -1,11 +1,10 @@ use std::fmt; -#[cfg(feature = "nightly")] use rustc_macros::{Decodable, Encodable, StableHash}; use rustc_span::{Symbol, sym}; #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)] -#[cfg_attr(feature = "nightly", derive(StableHash, Encodable, Decodable))] +#[derive(StableHash, Encodable, Decodable)] pub struct LintName { /// The lint's tool name, if present. pub tool: Option, @@ -82,7 +81,6 @@ impl fmt::Display for LintName { } } -#[cfg(feature = "nightly")] impl rustc_error_messages::IntoDiagArg for LintName { fn into_diag_arg( self, diff --git a/compiler/rustc_middle/src/lint.rs b/compiler/rustc_middle/src/lint.rs index 94acf8e303a03..08ba9b132c89d 100644 --- a/compiler/rustc_middle/src/lint.rs +++ b/compiler/rustc_middle/src/lint.rs @@ -5,13 +5,12 @@ use rustc_data_structures::sorted_map::SortedMap; use rustc_errors::{Diag, Diagnostic, EmissionOverride, MultiSpan}; use rustc_hir::{HirId, ItemLocalId}; use rustc_lint_defs::{ - EditionFcw, FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId, + EditionFcw, FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId, LintName, StableLintExpectationId, UnstableLintExpectationId, builtin, }; use rustc_macros::{Decodable, Encodable, StableHash}; use rustc_session::Session; use rustc_span::{DUMMY_SP, ExpnKind, Span, Symbol, kw, sym}; -use rustc_structures::LintName; use tracing::instrument; use crate::ty::TyCtxt; diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 182ff93e6f78a..2e25e063bc887 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -21,13 +21,13 @@ use rustc_errors::{ Diag, DiagCtxt, DiagCtxtHandle, DiagMessage, Diagnostic, ErrorGuaranteed, PResult, TerminalUrl, }; use rustc_feature::UnstableFeatures; -use rustc_lint_defs::{CheckLintNameResult, RegisteredTools}; +use rustc_lint_defs::{CheckLintNameResult, LintName, RegisteredTools}; use rustc_macros::StableHash; pub use rustc_span::def_id::StableCrateId; use rustc_span::edition::Edition; use rustc_span::source_map::{FilePathMapping, SourceMap}; use rustc_span::{RealFileName, Span, Symbol}; -use rustc_structures::{CrateType, Limit, LintName}; +use rustc_structures::{CrateType, Limit}; use rustc_target::asm::InlineAsmArch; use rustc_target::spec::{ Arch, CfgAbi, CodeModel, DebuginfoKind, MergeFunctions, Os, PanicStrategy, RelocModel, diff --git a/compiler/rustc_structures/src/lib.rs b/compiler/rustc_structures/src/lib.rs index caa3cdae45acc..cb5dccdfcd180 100644 --- a/compiler/rustc_structures/src/lib.rs +++ b/compiler/rustc_structures/src/lib.rs @@ -5,14 +5,12 @@ mod collapse_macro_debug_info; mod crate_type; mod limit; -mod lint; mod native_lib_kind; mod sanitizer_set; pub use collapse_macro_debug_info::CollapseMacroDebuginfo; pub use crate_type::CrateType; pub use limit::Limit; -pub use lint::LintName; pub use native_lib_kind::NativeLibKind; pub use sanitizer_set::SanitizerSet; diff --git a/src/tools/clippy/clippy_lints/src/collapsible_if.rs b/src/tools/clippy/clippy_lints/src/collapsible_if.rs index 2ad1d6c7e6ffb..48fec57d0066e 100644 --- a/src/tools/clippy/clippy_lints/src/collapsible_if.rs +++ b/src/tools/clippy/clippy_lints/src/collapsible_if.rs @@ -11,7 +11,7 @@ use rustc_hir::{Block, Expr, ExprKind, StmtKind}; use rustc_lexer::TokenKind; use rustc_lint::{LateContext, LateLintPass, impl_lint_pass}; use rustc_span::{BytePos, Span, Symbol}; -use rustc_structures::LintName; +use rustc_lint_defs::LintName; declare_clippy_lint! { /// ### What it does diff --git a/src/tools/clippy/clippy_lints/src/lib.rs b/src/tools/clippy/clippy_lints/src/lib.rs index c8f10f7ba37ed..06dd5246c0b22 100644 --- a/src/tools/clippy/clippy_lints/src/lib.rs +++ b/src/tools/clippy/clippy_lints/src/lib.rs @@ -36,6 +36,7 @@ extern crate rustc_index; extern crate rustc_infer; extern crate rustc_lexer; extern crate rustc_lint; +extern crate rustc_lint_defs; extern crate rustc_middle; extern crate rustc_parse_format; extern crate rustc_resolve; diff --git a/src/tools/clippy/clippy_lints/src/returns/needless_return.rs b/src/tools/clippy/clippy_lints/src/returns/needless_return.rs index 71b5044879da1..677b907a1fb2c 100644 --- a/src/tools/clippy/clippy_lints/src/returns/needless_return.rs +++ b/src/tools/clippy/clippy_lints/src/returns/needless_return.rs @@ -14,7 +14,7 @@ use rustc_hir::{Body, Expr, ExprKind, HirId, MatchSource, StmtKind}; use rustc_lint::{LateContext, LintContext as _}; use rustc_middle::ty::{self, Ty}; use rustc_span::{BytePos, Pos as _, Span}; -use rustc_structures::LintName; +use rustc_lint_defs::LintName; use std::borrow::Cow; use std::fmt::Display; From 09d7afc36ae64d5747f6d5597115d1bf8a9341e4 Mon Sep 17 00:00:00 2001 From: Nicolas Guichard Date: Thu, 4 Jun 2026 16:46:19 +0200 Subject: [PATCH 49/51] 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 50/51] 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 51/51] 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`.